使用Google API中提供的MapView库,我们可以很容易的在我们的程序中添加地图功能。
MapView库封装了Google Map的API以及用户的基本操作,所以只需一些简单的配置,就可以将Google Map完美的嵌入到工程中。
为了保证Google Map的合理应用,Google要求每个使用MapView的应用程序都必须为其MapView申请一个Maps API key。
首先,我们来获取Maps API Key。
1. 得到用来签名apk的Certificate文件,即证书文件。
release版本的证书文件是开发人员自己生成的,这个就不用说了。
debug版本的证书文件,用来在ADT虚拟机上发布程序,在Windows XP系统中的路径一般是C:\Documents and Settings\<user>\.android\debug.keystore
。
2. 生成证书的MD5码。
生成证书的命令是 keytool -list -keystore [证书文件]
执行后会要求用户输入证书的密码,debug版本的证书密码是android,而release版,自己回忆去吧。。
输入后命令将返回证书的信息,在最后一行,我们得到了证书的MD5码,例如:
Certificate fingerprint (MD5): 28:DC:C8:F8:7E:70:C6:86:B6:F9:23:A5:2E:43:50:38
3. 打开浏览器,连接到http://code.google.com/android/maps-api-signup.html,如下图
勾上复选框,点“Generate API Key",好了,我们成功的注册了我们的证书,并得到了Maps API Key:
如果忘记了API Key也没关系,重新按上述方法获取一次就可以了,两次获取的API Key值是一样的。
Key搞定了,在工程中加入MapView试试吧。
1. Layout文件 test_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0AbLT2lwf0gC5INzAw5iLqo8fDilY1zeu80pxwA"/>
</LinearLayout>
注意把android:apiKey换成你获得的Key,如果要在ADT上调试,使用debug证书对应的key,如果要发布在手机上,就要使用签名apk的证书key了。
每个证书只能对应一个Maps API Key;这个Key可以被任意个App的任意个MapView引用,只要保证引用Key的App被这个Key对应的证书签名就可以了。
如果在代码中构造MapView,需将API Key做为构造函数的参数传入,如:
mMapView = new MapView(this, "example_Maps_ApiKey_String");
2. Activity文件 TestMapActivity.java:
import com.google.android.maps.MapActivity;
public class TestMapActivity extends MapActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_map);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
...
}
3. 最后,在AndroidManifest.xml文件中,在<application>中添加一条配置:
<application ...>
<uses-library android:name="com.google.android.maps"/>
...
</application>
大功告成,试试你的Google Map吧。关于Google Map的更多操作将在下一篇文章中继续分解。