本篇通过一个简单的示例一步步介绍如何在Android应用中使用百度地图api。
1)下载百度地图移动版API(Android)开发包 要在Android应用中使用百度地图API,就需要在工程中引用百度地图API开发包,这个开发包包含两个文件:baidumapapi.jar和libBMapApiEngine.so。下载地址:
http://dev.baidu.com/wiki/static/imap/files/BaiduMapApi_Lib_Android_1.0.zip 2)申请API Key
和使用Google map api一样,在使用百度地图API之前也需要获取相应的API Key。百度地图API Key与你的百度账户相关联,因此您必须先有百度帐户,才能获得API Key;并且,该Key与您引用API的程序名称有关。
百度API Key的申请要比Google的简单多了,其实只要你有百度帐号,应该不超过30秒就能完成API Key的申请。申请地址:http://dev.baidu.com/wiki/static/imap/key/
4)在布局文件中添加地图控件(res/layout/main.xml)
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <com.baidu.mapapi.MapView android:id="@+id/map_View"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:clickable="true"
- />
- </LinearLayout>
5)创建Activity继承com.baidu.mapapi.MapActivity
- package com.liufeng.baidumap;
-
- import android.graphics.drawable.Drawable;
- import android.os.Bundle;
-
- import com.baidu.mapapi.BMapManager;
- import com.baidu.mapapi.GeoPoint;
- import com.baidu.mapapi.MapActivity;
- import com.baidu.mapapi.MapController;
- import com.baidu.mapapi.MapView;
-
- public class MainActivity extends MapActivity {
- private BMapManager mapManager;
- private MapView mapView;
- private MapController mapController;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
-
- mapManager = new BMapManager(getApplication());
-
- mapManager.init("285B415EBAB2A92293E85502150ADA7F03C777C4", null);
- super.initMapActivity(mapManager);
-
- mapView = (MapView) findViewById(R.id.map_View);
-
- mapView.setTraffic(true);
-
- mapView.setBuiltInZoomControls(true);
-
-
- GeoPoint point = new GeoPoint((int) (47.118440 * 1E6), (int) (87.493147 * 1E6));
-
-
- Drawable marker = this.getResources().getDrawable(R.drawable.iconmarka);
-
- marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
-
-
- mapController = mapView.getController();
-
- mapController.setCenter(point);
-
- mapController.setZoom(12);
- }
-
- @Override
- protected boolean isRouteDisplayed() {
- return false;
- }
-
- @Override
- protected void onDestroy() {
- if (mapManager != null) {
- mapManager.destroy();
- mapManager = null;
- }
- super.onDestroy();
- }
-
- @Override
- protected void onPause() {
- if (mapManager != null) {
- mapManager.stop();
- }
- super.onPause();
- }
-
- @Override
- protected void onResume() {
- if (mapManager != null) {
- mapManager.start();
- }
- super.onResume();
- }
- }