在Android平台下建立Android Map工程首先需要建立模拟器。
一、创建基于Google APIs的AVD
新建Google Map工程时,在Build Target处需要选择相应开发版本的Google APIs,在运行工程时也需要选择创建的基于Google APIs的AVD来运行。
二、创建基于Google APIs的AVD
三、Google Map API的使用
Android中定义了一个名为com.google.android.maps的包,其中包含了一系列用于在Google Map上显示、控制和层叠信息的功能类,以下是该包中最重要的几个类:
.MapActivity:这个类是用于显示Google Map的Activity类,它需要连接底层网络。MapActivity是一个抽象类,任何想要显示MapView的activity都需要派生自MapActivity,并且在其派生类的onCreate()中,都要创建一个MapView实例。
.MapView:MapView是用于显示地图的View组件。它派生自android.view.ViewGroup。它必须和MapActivity配合使用,而且只能被MapActivity创建,这是因为MapView需要通过后台的线程来连接网络或者文件系统,而这些线程需要由MapActivity来管理。
.MapController:用于控制地图的移动缩放等。
.Overlay:这是一个可显示与地图之上的可绘制的对象。
.GeoPoint:这是一个包含经纬度位置的对象。
以下将使用com.google.android.maps包来实现一个Android Map工程。
步骤一:创建工程,注意选择Build Target为“Google APIs”。
步骤二:修改AndroidManifest.xml文件,此文件是整个项目的配置文件。
(1)加入Android平台开发中需要的Google Map API库
<uses-library android:name="com.google.android.maps" />
(2)加入程序访问网络的许可
<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.huge.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".MyMapActivity"
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>
步骤三:创建MapVIew
要显示地图,需要创建一个MapView。在布局文件中加入Android Map API Key:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.google.android.maps.MapView
android:id="@+id/map_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0sALnGG8Kx6nFx0DbIBiphi7Jov1Wr4hs0F7deA">
</com.google.android.maps.MapView>
</LinearLayout>
步骤四:实现MapActivity
要使用MapView必须通过MapActivity,需要自定义一个类来实现MapActivity。
步骤五:给出显示中心点地理坐标(桂林站为例)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mv = (MapView) findViewById(R.id.map_view);
mc = mv.getController();
center = new GeoPoint((int)(25.261182)*1000000,(int)(110.282886)*1000000);
mc.setCenter(center);
}
运行结果: