Develop a Google Map Application

Source: Internet
Author: User
Map-based application development is a required feature for new mobile devices. To develop a map-based app in Android, Google has provided the Map Library as an additional function. This article describes how to develop a library based on

About this article

Map-based application development is a required feature for new mobile devices. To develop a map-based app in Android, Google has provided the Map Library as an additional function. This article describes how to develop a Google Map-based app in Android.

Range:

This article is designed for beginners who want to learn more about Android programming. It will guide you step by step to develop Google map applications. This document assumes that the developer has installed Android and necessary application development tools. It is also assumed that developers are familiar with Java or object-oriented programming concepts.

For more details about Android, see the knowledge base of Samsung mobile innovator Garden (SMI.

Http://innovator.samsungmobile.com/cn/cms/cnts/knowledge.list.do? Platformid = 1

Introduction

Android provides the Google external image library "com. Google. Android. Maps" as an additional function to develop Google API-based applications. The Map Library provides built-in map download, rendering, and map image buffering, as well as various display options and controls.

This document assumes that you are currently using Eclipse IDE and the android plug-in that you have added to develop applications.

Install Google API

Before developing the Google map application, make sure that you have installed the Google API plug-in the android SDK.

The external library is not included in the standard Android library provided in the SDK. The Google API append tool provides a Map Library to develop, create, and run map-based applications in the android SDK.

To check whether Google APIs have been added to the android SDK, enable the android SDK and AVD manager shown in Figure 1.

If Google APIs are not yet installed, manually install them.

Select"Installed options (installed options )"To view the installed content, and select "available packages" to download the additional API.

Figure 2 shows that Google APIs have been added to the android SDK.

Create a project

After all the necessary conditions are met, start to develop the application.

Create a Google Map Project in Eclipse IDE, as shown in 3. Specify the project name and select Google API as the target. It is important to use Google API as a target because this option includes Google extensions that allow you to use Google Maps.

If you cannot view the Google API options, you need to install them according to the Google API installation Description.

Create an AVD with a Google API

After creating a project, you must create a device that supports Google APIs.

EnableAndroid SDK and AVD Manager, 1. Select"Virtual Devices (Virtual Device )".Click"New )"To create an AVD. The dialog box shown in Step 4 is displayed.

Specify the AVD name and select one of the targets of "Google API (Google. Configure other options, and then click "create AVD (create AVD )". The new AVD that can run the project has been created.

Get Google API registration code

Google map provides Google map data for rendering maps. Because applications will access Google data, developers need to register Google network services.

The Google map API registration code allows Google APIs to access networks that provide map data.

Register to obtain a simple and free map API registration code, which consists of two parts:

1. Extract the md5fingerprint of the certificate.

2. register the md5fingerprint of the certificate.

Extract md5fingerprint Authentication

To get a registration code for a map API, developers need to provide md5fingerprint certification, which can be used to sign the application. Here we need to use two types of applications.

Debug. keystore

By default, the build tool creates and debugs the keystore in the activated avd directory by default. Different platforms have different AVD directories:

-Windows Vista: C: \ Users \. Android \ Debug. keystore

-Windows XP: C: \ Documents ents and Settings \. Android \ Debug. keystore

-OS X and Linux :~ /. Android/debug.keystorekeytool.exe

Keytool.exe

You need to use the keytool.exe application included with JDK installation to extract md5fingerprint. This fingerprint requires a free Google map registration code. The keytool.exe file usually appears in the % java_home %/bin directory of Windows or the $ java_home/bin directory of Linux/OS X.

As we are currently developing and debugging applications in debug mode, we need to sign the application in debug mode, that is, the SDK build tool will automatically use the debug certificate to sign your application.

To access this application, We need to extract the md5fingerprint authentication and use the Debug. keystore file for this purpose. If you cannot find the Debug. keystore file, you can select Windows> preferences> Android> build in Eclipse IDE to check the path. Figure 5 shows the Debug. keystore path in Eclipse IDE.

Once you have found the keystore, use this keytool command to obtain the md5fingerprint of the debug certificate.

$ Keytool-list-alias androiddebugkey-keystore. keystore-storepass Android-keypass android

Example: $ keytool-list-alias androiddebugkey-keystore "C: \ Android \ Debug. keystore"-storepass Android-keypass android

Register the md5fingerprint of the certificate

The output of keytool is similar to that shown in figure 6.

Copy the MD5 Certificate and open the web browser to http://code.google.com/android/maps-api-signup.html.

7. agree to the terms and conditions of Google API and enter the md5fingerprint of the certificate.

Click"Generate API key (generate API registration code )"Button to generate the API registration code. The generated API registration code 8 is shown in.

Modify androidmanifest. xml

To access Google Maps in an application, developers need to modify the androidmanifest. xml file using the following operations.

Add license

You need to use the Tag Element to add a network license. The required license is as follows:

-Android. Permission. access_coarse_location

Or

-Android. Permission. access_fine_location-android. Permission. Internet

Add Library

You need to use the Tag Element to add a Google Image Library. This is because Google Image Library is not the complete part of the standard library.

The final androidmanifest. xml file 9 is shown in.

As you can see, it is placed on the element and the external elements inside the element.

Modify main. xml

Open the main. xml file in the res \ Layout folder of the project. Developers need to use this element to display Google Maps in your activity. Use the element to locate the map within the activity range.

The modified main. xml10 file is shown in.

 

As you can see, the Google map API registration code has been entered in the main. xml file.

Create GoogleMap Activity

Extends the mapactivity class rather than the activity class to render a map in the application.

Mapactivity is actually a base class with code. It can manage the tedious transactions of any activity that can display mapview. Activity responsibilities include:

-Activity lifecycle management

-Create and revoke services for the mapview class

ToMapactivityFor expansion, we must executeIsroutedisplayedMethod, which indicates whether to display route information of any type, such as traffic, satellite, and street view information. We will not provide such information, so here we can only return false.

View the Google map API documentation before continuing. The GoogleMap class 11 is shown in.

Deploy applications

To deploy an application on the simulator, press F11 in Eclipse IDE. This output is shown in 12.

As you can see, the map has been rendered in the application, and you can add a built-in zoom control to zoom the map.

Change map view

By default, Google Maps are displayed in map mode. If you want to display the map in the satellite view, you can useSetsatellite ()Method, as follows:

Mapview. setsatellite (true );

You can also useSetstreetview ()Method to display the map in the street view.

Mapview. setstreetview (true );

Figure 13 shows the Google maps shown in the satellite and street views respectively.

Show special locations

By default, a map of the United States is displayed when Google maps are loaded for the first time. However, you can also set a Google Map to display a special location. In this case, you can useAnimateto ()Method.

As shown in figure 14MapviewOneMapcontroller. Then, a geopoint object is used to represent a geographical location. The longitude and latitude of A geopoint class are represented by a micron (stored as an integer.

To move the map navigation to a special location, we need to useAnimateto ()Method andSetzoom ()Method To set the scaling ratio.

The output is shown in 15. The geopoint coordinate indicates Mexico City.

Add an overlay Project

So far, we have seen the map, but you may want to create and add a sign and a stop point to the map to show the places of interest.

Now we will add a flag to the map. First, we need to display the logo image. Copy figure 16 and add it to the res/drawable folder of the project. 17.

First, you need to define a class that can expand the overlay class to add the flag to the map:

In the mapoverlay class that you must define, reloadDraw ()Method to draw a map. Note that the geographic location (represented by the geopoint object p) needs to be converted to the screen coordinate.

The method for adding a flag is to create a mapoverlap class example and add the mapoverlap class example to the available overlays list of the mapview object. Figure 18 shows the final code.

The output is shown in 19.

GoogleMap Application

The following shows the GoogleMap project file.

Main. xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    <com.google.android.maps.MapView

        android:id="@+id/mapView"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:enabled="true"

        android:clickable="true"

        android:apiKey="YOUR API KEY HERE"/>       

</RelativeLayout>

Androidmanifest. xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.samsung.maps.google"

      android:versionCode="1"

      android:versionName="1.0">   

      <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" android:maxSdkVersion="8" />             

   <uses-permission android:name="android.permission.INTERNET" />

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">     

      <application android:icon="@drawable/icon" android:label="@string/app_name">

        <uses-library android:name="com.google.android.maps" />   

          <activity android:name=".GoogleMap"  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

      </application>

</manifest>

GoogleMap. Java

package com.samsung.maps.google;import java.util.List;import android.content.Context;import android.content.res.Resources;import android.os.Bundle;import com.google.android.maps.MapActivity;import com.google.android.maps.GeoPoint;import com.google.android.maps.MapController;import com.google.android.maps.MapView;import com.google.android.maps.Overlay;public class GoogleMap extends MapActivity  {  MapView mapView; MapController mc; GeoPoint p; Resources res; Context context; MapOverlay mapOverlay;  /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)   {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);               res = getResources();        context = getApplicationContext();               mapView = (MapView) findViewById(R.id.mapView);        mapView.setBuiltInZoomControls(true);        mc = mapView.getController();        p = new GeoPoint(19240000,-99120000);                      mc.animateTo(p);        mc.setZoom(8);                //Add location marker        //MapOverlay mapOverlay = new MapOverlay();        mapOverlay = new MapOverlay(p, res, context);        List listOfOverlays = mapView.getOverlays();        listOfOverlays.clear();        listOfOverlays.add(mapOverlay);                mapView.invalidate();    }     @Override    protected boolean isRouteDisplayed() {        return false;    }}

Mapoverlay. Java

package com.samsung.maps.google;import android.content.Context;import android.content.res.Resources;import com.google.android.maps.Overlay;import android.app.AlertDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Point;import com.google.android.maps.GeoPoint;import com.google.android.maps.MapView;public class MapOverlay extends Overlay {  Resources res; Context context; GeoPoint geoPoint; public MapOverlay(GeoPoint g, Resources r, Context c) {  super();  res = r;  context = c;  geoPoint = g; } @Overridepublic boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)   {        super.draw(canvas, mapView, shadow);                            //translate the GeoPoint to screen pixels        Point screenPts = new Point();        mapView.getProjection().toPixels(geoPoint, screenPts);         //add marker        Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.androidmarker);                   canvas.drawBitmap(bmp, screenPts.x, screenPts.y-58, null);                return true;    }       @Override    public boolean onTap(GeoPoint p, MapView mapView) {                AlertDialog.Builder dialog = new AlertDialog.Builder(context);

      dialog.setTitle("Hi");

      dialog.setMessage("Hi Im in Mexico");

      dialog.show();

      return true;

    }

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.