Android Google Map API 开发基础知识

转载:http://www.cnblogs.com/playing/archive/2011/04/23/2025419.html

http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/

开发基于谷歌地图的应用和普通的android应用差不多都要使用它提供给我们的类库,所不同的是google map的类库不是android平台的基本类库,是google api的一部分,所以建立项目时,SDK要选择Google APIs;

还有一点,开发基于地图的应用时候需要使用google map的APIkey,必须先申请key,然后才能开发基于地图的应用。

下边分步骤记录下,整个过程:

 一、申请google Maps API key(用于开发和debug)

为了能顺利的申请Android Map API Key,必须要准备google的账号和系统的证明书。一般Google发布Key都需要Google账号,Google账号是通用的,Gmail的账号就可以。当一个程序发布时必须要证明书,证明书其实就是MD5.我们这里并不是发布,而只是为了开发测试,可以使用Debug版的证明书,下面我们就来学习如何申请Debug版的Key:

1.找到你的debug.keystore文件

在Eclipse工具下,选择windows-->Preference-->Android-->Build,其中Default debug keystore的值便是debug.keystore的路径了。

2.取得debug.keystore的MD5值

首先cmd命令行进入debug.keystore文件所在的路径,执行命令:keytool -list -keystore debug.keystore,这时可能会提示你输入密码,这里默认的密码是“android",这样即可取得MD5值。

3.申请Android Map 的API Key.

打开浏览器,输入网址:http://code.google.com/android/maps-api-signup.html,填入你的认证指纹(MD5)即可获得apiKey了,结果显示如下:

感谢您注册 Android 地图 API 密钥!
您的密钥是:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
我IE打开的时候是乱码,不知道是不是自己电脑有问题。后来改用了chrome就正常显示了。

到此,我们就完成了API Key的申请了,记录下Key值,在后续开发中使用。(放在layout中加入的MapView中)

二.Google Map API的使用

Android中定义了一个名为com.google.android.map的包,其中包含了一系列用于在google map上显示、控制和叠层信息的功能类,以下是该包中最重要的几个类:

1.MapActivity:这个类是用于显示Google Map的Activity类,它需要连接底层网络。MapActivity是一个抽象类,任何想要显示MapView的activity都需要派生自MapActivity,并且在其派生类的onCreate()中,都要创建一个MapView实例。

2.MapView:MapView是用于显示地图的View组件。它派生自android.view.ViewGroup。它必须和MapActivity配合使用,而且只能被MapActivity创建,这是因为MapView需要通过后台的线程来连接网络或者文件系统,而这些线程需要有MapActivity来管理。

3.MapController:MapController用于控制地图的移动、缩放等。

4.OverLay:这是一个可显示于地图之上的可绘制的对象。

5.GeoPoint:这是一个包含经纬度位置的对象。

三.实例开发

1.创建工程,注意SDK旋转为"Goolge APIs”

2.修改AndroidManifest.xml文件

由于使用Google Map API,所以必须添加<uses-library android:name="com.google.android.maps" />

由于需要从网络获取地图数据,所以需要访问网络的权限<uses-permission android:name="android.permission.INTERNET"/>

可能还需要添加其他权限。

例如:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.yarin.android.Examples_09_03"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
       <uses-library android:name="com.google.android.maps" />
        <activity android:name=".Activity01"
                  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>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-sdk android:minSdkVersion="5" />
</manifest> 

3.创建MapView

要显示地图,需要创建一个MapView,在Xml文件中的布局如下。其中的android:apiKey的值就是我们第一步申请的Key了。

<?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/MapView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="0AubmfALdupLSlQkE67OTXgcQgWtyhXcO7uhsIQ"/>
</RelativeLayout> 

当然,可以在程序中通过如下代码来创建MapView:

MapView map = new MapView( this, "(android maps api key)");

4.实现MapActivity

MapView需要由MapActivity来管理,所以程序部分应该继承自MapActivity类,必须实现isRouteDisplay方法。

MapView提供了3中模式的地图,分别可以通过以下方式设置采用什么模式来显示地图。

      mMapView.setTraffic(true); //设置为交通模式 

      mMapView.setSatellite(true); //设置为卫星模式//

     mMapView.setStreetView(false); //设置为街景模式

通过setBuiltZoomControls方法设置地图是否支持缩放。

5.MapController的使用

如果需要设置地图显示的地点以及放大倍数等,就需要使用MapController来控制地图。可以通过如下代码获得MapController对象:

mMapController = mMapView.getController(); 

要定位地点,需要构造一个GeoPoint来表示地点的经纬度,然后使用animateTo方法将地图定位到指定的GeoPoint上,

代码如下:

//设置起点为成都
mGeoPoint = new GeoPoint((int) (30.659259 * 1000000), (int) (104.065762 * 1000000));
//定位到成都
mMapController.animateTo(mGeoPoint); 

6.Ovelay的使用

如果需要在地图上标注一些图标文字等信息,就需要使用Overlay。这里我们首先要将地图上的经度和纬度转换成屏幕上的实际坐标,才能将信息绘制上去。Map API中提供了Projection.toPixels(GeoPoint in,GeoPoint out)方法,可以将经度和纬度转换成屏幕上的坐标。

首先需要实现OverLay中的draw方法才能在地图上绘制信息,代码如下:

class MyLocationOverlay extends Overlay
{
     @Override
     public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
     {
             ........
     }
}

综合上面的代码如下:



import java.util.List;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class Activity01 extends MapActivity
{
    private MapView     mMapView;
    private MapController mMapController; 
    private GeoPoint mGeoPoint;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMapView = (MapView) findViewById(R.id.MapView01);
        //设置为交通模式
//        mMapView.setTraffic(true);
        //设置为卫星模式
//        mMapView.setSatellite(true); 
        //设置为街景模式
        mMapView.setStreetView(false);
        //取得MapController对象(控制MapView)
        mMapController = mMapView.getController(); 
        mMapView.setEnabled(true);
        mMapView.setClickable(true);
        //设置地图支持缩放
        mMapView.setBuiltInZoomControls(true); 
        
        
        //设置起点为成都
        mGeoPoint = new GeoPoint((int) (30.659259 * 1000000), (int) (104.065762 * 1000000));
        //定位到成都
        mMapController.animateTo(mGeoPoint); 
        //设置倍数(1-21)
        mMapController.setZoom(15); 
        
        
        
        //添加Overlay,用于显示标注信息
        MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
        List<Overlay> list = mMapView.getOverlays();
        list.add(myLocationOverlay);
    }
    protected boolean isRouteDisplayed()
    {
        return false;
    }
    class MyLocationOverlay extends Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
        {
            super.draw(canvas, mapView, shadow);
            Paint paint = new Paint();
            Point myScreenCoords = new Point();
            // 将经纬度转换成实际屏幕坐标
            mapView.getProjection().toPixels(mGeoPoint, myScreenCoords);
            paint.setStrokeWidth(1);
            paint.setARGB(255, 255, 0, 0);
            paint.setStyle(Paint.Style.STROKE);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home);
            canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
            canvas.drawText("天府广场", myScreenCoords.x, myScreenCoords.y, paint);
            return true;
        }
    }
}


If you have developed any app that contains Google Maps v1, It’s time to upgrade it to Google Maps V2 as google maps version 1 deprecated officially on December 3rd, 2012 and it won’t work anymore. This article aims to give knowledge about how to implements newer Google Maps into your applications. If you have already worked with V1, implementing V2 is very easy. Refer Google Maps Docs for any topic that is not covered in this tutorial.

Download Code

Before starting a new project, we need to go through some pre required steps. These steps involves importing required library, generating SHA1 fingerprint and configuring maps in google console. 

1. Downloading Google Play Services

Google made new Maps V2 API as a part of Google Play Services SDK. So before we start developing maps we need to download google play services from SDK manger. You can open SDK manager either from Eclipse or from android sdk folder.

Open Eclipse ⇒ Windows ⇒ Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.

Android downloading google play services

2. Importing Google Play Services into Eclipse

After downloading play services we need to import it to Eclipse which will be used as a library for our maps project.

1 . In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace

2 . Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from  android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib

3 . Importantly while importing check Copy projects into workspace option as shown in the below image.

android linking google play services library

3. Getting the Google Maps API key

1 . Same as in maps v1 we need to generate SHA-1 fingerprint using java keytool . Open your terminal and execute the following command to generate SHA-1 fingerprint.

On Windows

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

On Linux or Mac OS

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

In the output you can see SHA 1 finger print.

android google mapsSHA finger print

2 . Now open Google API Console

3 . Select Services on left side and turn on Google Maps Android API v2

android google console maps api

4 . Now select API Access on left side and on the right side click on Create new Android key…

google console generating api key

5 . It will popup a window asking the SHA1 and package name. Enter your SHA 1 and your android project package name separated by semicolon ; and click on create.

google console sha 1 finger print

I have given like below

BE:03:E1:44:39:7B:E8:17:02:9F:7F:B7:98:82:EA:DF:84:D0:FB:6A;info.androidhive.googlemapsv2

And note down the API key which required later in our project.

google console android maps v2 api key

4. Creating new Project

After completing required configuration, It’s time to start our project.

1 . In Eclipse create a new project by going to File ⇒ New ⇒ Android Application Project and fill required details. I kept my project name as Google Maps V2 and package name as info.androidhive.info

2 . Now we need to use Google Play Services project as a library to use project. Soright click on project and select properties . In the properties window on left side selectAndroid . On the right you can see a Add button under library section. Click it and selectgoogle play services project which we imported previously.

android google play services library project
android google play services library project
android google play services library project

3 . Add the Map Key in the manifest file. Open AndroidManifest.xml file and add the following code before tag. Replace the android:value with your map key which you got from google console.

<!-- Goolge Maps API Key -->
<meta-data
     android:name="com.google.android.maps.v2.API_KEY"
     android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" />

4 . Google maps needs following permissions and features.

ACCESS_NETWORK_STATE – To check network state whether data can be downloaded or not 
INTERNET – To check internet connection status 
WRITE_EXTERNAL_STORAGE – To write to external storage as google maps store map data in external storage 
ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile cell data 
ACCESS_FINE_LOCATION – To determine user’s location using GPS 
OpenGL ES V2 – Required for Google Maps V2

Finally my AndroidManifest.xml file looks like this (Replace the package name with your project package)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="info.androidhive.googlemapsv2.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" />
    </application>

</manifest>

5 . New google maps are implemented using MapFragments which is a sub class ofFragments class. Open your main activity layout file activity_main.xml file and add following code. I used RelativeLayout as a parent element. You can remove it and use MapFragment directly.

<?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" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

6 . Add the following code in your Main Activity java ( MainActivity.java ) class.

public class MainActivity extends Activity {

  // Google Map
  private GoogleMap googleMap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
      // Loading map
      initilizeMap();

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  /**
   * function to load map. If map is not created it will create it for you
   * */
  private void initilizeMap() {
    if (googleMap == null) {
      googleMap = ((MapFragment) getFragmentManager().findFragmentById(
          R.id.map)).getMap();

      // check if map is created successfully or not
      if (googleMap == null) {
        Toast.makeText(getApplicationContext(),
            "Sorry! unable to create maps", Toast.LENGTH_SHORT)
            .show();
      }
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    initilizeMap();
  }

}

Run your project and congratulations if you see a map displaying on your device.

android google maps version 2 v2

Placing a Marker

You can place a marker on the map by using following code.

// latitude and longitude
double latitude = ;
double longitude = ;

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");

// adding marker
googleMap.addMarker(marker);
android google maps v2 placing a marker

Changing Marker Color

By default map marker color will be RED. Google maps provides some set of predefined colored icons for the marker.

// ROSE color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

// GREEN color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
android google maps v2 changing marker icon color

Custom Marker Icon

Apart from maps native marker icons, you can use own image to show as a marker. You can load the icon from any kind of supported sources.

fromAsset(String assetName) – Loading from assets folder 
fromBitmap (Bitmap image) – Loading bitmap image 
fromFile (String path) – Loading from file 
fromResource (int resourceId) – Loading from drawable resource

Below I loaded a custom marker icon from drawable folder

// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");

// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));

// adding marker
googleMap.addMarker(marker);

Moving Camera to a Location with animation

You may want to move camera to a particular position. Google maps provides set of functions to achieve this.

CameraPosition cameraPosition = new CameraPosition.Builder().target(
        new LatLng(17.385044, 78.486671)).zoom(12).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Following are enhancements and features that google maps provides. You can utilize these features which suites to your requirements. 

Changing Map Type

Google provides 4 kinds of map types Normal , Hybrid , Satellite and Terrain . You can toggle to any kind of map using googleMap.setMapType() method.

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
android google maps v2 changing map type

Showing Current Location

You can show user’s current location on the map by calling setMyLocationEnabled() . Pass true / false to enable or disable this feature

googleMap.setMyLocationEnabled(true); // false to disable

Zooming Buttons

You can call setZoomControlsEnabled() function to get rid of those zooming controls on the map. By disabling these buttons map zooming functionality still work by pinching gesture.

googleMap.getUiSettings().setZoomControlsEnabled(false); // true to enable

Zooming Functionality

You can disable zooming gesture functionality by calling setZoomGesturesEnabled()

googleMap.getUiSettings().setZoomGesturesEnabled(false);

Compass Functionality

Compass can be disabled by calling setCompassEnabled() function

googleMap.getUiSettings().setCompassEnabled(true);

My Location Button

My location button will be used to move map to your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled() function

googleMap.getUiSettings().setMyLocationButtonEnabled(true);

Map Rotate Gesture

My rotate gesture can be enabled or disabled by calling setRotateGesturesEnabled()method

googleMap.getUiSettings().setRotateGesturesEnabled(true);

Although google maps provides lot of other features, I covered only basic topics in this tutorial. Remaining topics seems to be pretty much lengthy, so I’ll post them as separate articles.










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值