一:百度地圖開發必須要到百度開發平台android開發api下載相應的庫,已經申請百度地圖開發key.
二:新建項目baidumaplocation.設計main.xml文件這里注意的是MapView控件必須使用來自百度庫封裝好的com.baidu.mapapi.MapView 。設計代碼如下:
- <?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" >
- <FrameLayout
- android:id="@+id/map_layout"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <!-- 百度MapView控件 -->
- <com.baidu.mapapi.MapView
- android:id="@+id/map_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:apiKey="0Mg_koWoyZUiYLfZxmPfp4LKInB5LqTnagYueaw"
- android:clickable="true"
- android:enabled="true" />
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:orientation="vertical"
- android:paddingBottom="105dip" >
- <!-- 地址信息顯示TextView -->
- <TextView
- android:id="@+id/map_bubbleText"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/location_tips"
- android:gravity="left|center"
- android:maxEms="12"
- android:paddingLeft="12dip"
- android:paddingRight="10dip"
- android:text="@string/load_tips"
- android:textColor="#cfcfcf"
- android:textSize="14sp" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:orientation="vertical" >
- <!-- 位置指標顯示ImageView -->
- <ImageView
- android:id="@+id/point_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:layout_marginBottom="30dip"
- android:src="@drawable/point_start" />
- </LinearLayout>
- </FrameLayout>
- </LinearLayout>
三:創建覆蓋整個地圖捕捉觸控事件的MyMapOverlay繼承Overlay
- import android.view.MotionEvent;
- import com.baidu.mapapi.GeoPoint;
- import com.baidu.mapapi.MapView;
- import com.baidu.mapapi.Overlay;
- //覆蓋整個地圖捕捉觸控事件的OverLay
- public abstract class MyMapOverlay extends Overlay{
- private int point_X;
- private int point_Y;
- private GeoPoint newPoint;
- public MyMapOverlay(int x,int y){
- point_X = x;
- point_Y = y;
- }
- boolean flagMove=false;
- //這里實現根據地圖移動時重新獲取屏幕中心點的經緯度坐標
- @Override
- public boolean onTouchEvent(MotionEvent event, MapView mapView) {
- System.out.println("X->"+event.getX()+":"+point_X);
- System.out.println("Y->"+event.getY()+":"+point_Y);
- if(event.getAction() == MotionEvent.ACTION_DOWN){
- changePoint(newPoint,1);
- }else if(event.getAction() == MotionEvent.ACTION_UP){
- newPoint = mapView.getProjection().fromPixels(point_X,point_Y);
- changePoint(newPoint,2);
- }
- return false;
- }
- public abstract void changePoint(GeoPoint newPoint,int type);
- }
四:LocationActivity類繼承百度庫的MapActivity以及實現LocationListener接口,代碼如下:
package com.location.activity;- import java.io.IOException;
- import java.util.List;
- import java.util.Locale;
- import android.content.Intent;
- import android.location.Address;
- import android.location.Geocoder;
- import android.location.Location;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.Window;
- import android.widget.TextView;
- import com.android.map.MyMapOverlay;
- import com.baidu.mapapi.BMapManager;
- import com.baidu.mapapi.GeoPoint;
- import com.baidu.mapapi.LocationListener;
- import com.baidu.mapapi.MKAddrInfo;
- import com.baidu.mapapi.MKBusLineResult;
- import com.baidu.mapapi.MKDrivingRouteResult;
- import com.baidu.mapapi.MKLocationManager;
- import com.baidu.mapapi.MKPoiResult;
- import com.baidu.mapapi.MKSearch;
- import com.baidu.mapapi.MKSearchListener;
- import com.baidu.mapapi.MKSuggestionResult;
- import com.baidu.mapapi.MKTransitRouteResult;
- import com.baidu.mapapi.MKWalkingRouteResult;
- import com.baidu.mapapi.MapActivity;
- import com.baidu.mapapi.MapController;
- import com.baidu.mapapi.MapView;
- import com.baidu.mapapi.Overlay;
- public class LocationActivity extends MapActivity implements LocationListener {
- private MapView mapView;
- private MapController mMapCtrl;
- private List<Overlay> mapOverlays;
- public GeoPoint locPoint;
- private MyMapOverlay mOverlay;
- private TextView desText;
- private String lost_tips;
- private int point_X;
- private int point_Y;
- public final int MSG_VIEW_LONGPRESS = 10001;
- public final int MSG_VIEW_ADDRESSNAME = 10002;
- public final int MSG_GONE_ADDRESSNAME = 10003;
- private Intent mIntent;
- private int mLatitude;
- private int mLongitude;
- private String name;
- private BMapManager mapManager;
- private MKLocationManager mLocationManager = null;
- private boolean isLoadAdrr = true;
- private MKSearch mMKSearch;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.main);
- initMap();
- mIntent = getIntent();
- mLatitude = mIntent.getIntExtra("latitude", 0);
- mLongitude = mIntent.getIntExtra("longitude", 0);
- name = mIntent.getStringExtra("name");
- mapView = (MapView) findViewById(R.id.map_view);
- desText = (TextView) this.findViewById(R.id.map_bubbleText);
- lost_tips = getResources().getString(R.string.load_tips);
- if (mLatitude != 0 && mLongitude != 0) {
- locPoint = new GeoPoint((int) (mLatitude * 1E6),
- (int) (mLongitude * 1E6));
- desText.setText(name);
- }
- mapView.setBuiltInZoomControls(true);
- mapView.setClickable(true);
- mMapCtrl = mapView.getController();
- point_X = this.getWindowManager().getDefaultDisplay().getWidth() / 2;
- point_Y = this.getWindowManager().getDefaultDisplay().getHeight() / 2;
- mOverlay = new MyMapOverlay(point_X, point_Y) {
- @Override
- public void changePoint(GeoPoint newPoint, int type) {
- if (type == 1) {
- mHandler.sendEmptyMessage(MSG_GONE_ADDRESSNAME);
- } else {
- locPoint = newPoint;
- mHandler.sendEmptyMessage(MSG_VIEW_LONGPRESS);
- }
- }
- };
- mapOverlays = mapView.getOverlays();
- if (mapOverlays.size() > 0) {
- mapOverlays.clear();
- }
- mapOverlays.add(mOverlay);
- mMapCtrl.setZoom(20);
- }
- private void initMap() {
- // 初始化MapActivity
- mapManager = new BMapManager(getApplication());
- // init方法的第一個參數需填入申請的API Key
- mapManager.init("C66C0501D0280744759A6957C42543AE38F5D540", null);
- super.initMapActivity(mapManager);
- // 實例化搜索地址類
- mMKSearch = new MKSearch();
- // 初始化搜索地址實例
- mMKSearch.init(mapManager, new MySearchListener());
- mLocationManager = mapManager.getLocationManager();
- // 注冊位置更新事件
- mLocationManager.requestLocationUpdates(this);
- // 使用GPS定位
- mLocationManager
- .enableProvider((int) MKLocationManager.MK_GPS_PROVIDER);
- }
- @Override
- protected void onResume() {
- if (mapManager != null) {
- mapManager.start();
- }
- super.onResume();
- }
- @Override
- protected void onPause() {
- isLoadAdrr = false;
- if (mapManager != null) {
- mapManager.stop();
- }
- super.onPause();
- }
- @Override
- protected boolean isRouteDisplayed() {
- // TODO Auto-generated method stub
- return false;
- }
- /**
- * 通過經緯度獲取地址
- *
- * @param point
- * @return
- */
- private String getLocationAddress(GeoPoint point) {
- String add = "";
- Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
- try {
- List<Address> addresses = geoCoder.getFromLocation(
- point.getLatitudeE6() / 1E6, point.getLongitudeE6() / 1E6,
- 1);
- Address address = addresses.get(0);
- int maxLine = address.getMaxAddressLineIndex();
- if (maxLine >= 2) {
- add = address.getAddressLine(1) + address.getAddressLine(2);
- } else {
- add = address.getAddressLine(1);
- }
- } catch (IOException e) {
- add = "";
- e.printStackTrace();
- }
- return add;
- }
- private Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_VIEW_LONGPRESS:// 處理長按時間返回位置信息
- {
- if (null == locPoint)
- return;
- mMKSearch.reverseGeocode(locPoint);
- desText.setVisibility(View.VISIBLE);
- desText.setText(lost_tips);
- mMapCtrl.animateTo(locPoint);
- mapView.invalidate();
- }
- break;
- case MSG_VIEW_ADDRESSNAME:
- desText.setText((String) msg.obj);
- desText.setVisibility(View.VISIBLE);
- break;
- case MSG_GONE_ADDRESSNAME:
- desText.setVisibility(View.GONE);
- break;
- }
- }
- };
- // 關閉程序也關閉定位
- @Override
- protected void onDestroy() {
- if (mapManager != null) {
- mapManager.destroy();
- mapManager = null;
- }
- super.onDestroy();
- }
- /**
- * 根據MyLocationOverlay配置的屬性確定是否在地圖上顯示當前位置
- */
- @Override
- protected boolean isLocationDisplayed() {
- return false;
- }
- /**
- * 當位置發生變化時觸發此方法
- *
- * @param location
- * 當前位置
- */
- public void onLocationChanged(Location location) {
- if (location != null) {
- locPoint = new GeoPoint((int) (location.getLatitude()* 1E6),
- (int) (location.getLongitude()* 1E6));
- mHandler.sendEmptyMessage(MSG_VIEW_LONGPRESS);
- }
- }
- /**
- * 內部類實現MKSearchListener接口,用於實現異步搜索服務
- *
- * @author liufeng
- */
- public class MySearchListener implements MKSearchListener {
- /**
- * 根據經緯度搜索地址信息結果
- *
- * @param result
- * 搜索結果
- * @param iError
- * 錯誤號(0表示正確返回)
- */
- public void onGetAddrResult(MKAddrInfo result, int iError) {
- if (result == null) {
- return;
- }
- Message msg = new Message();
- msg.what = MSG_VIEW_ADDRESSNAME;
- msg.obj = result.strAddr;
- mHandler.sendMessage(msg);
- }
- /**
- * 駕車路線搜索結果
- *
- * @param result
- * 搜索結果
- * @param iError
- * 錯誤號(0表示正確返回)
- */
- public void onGetDrivingRouteResult(MKDrivingRouteResult result,
- int iError) {
- }
- /**
- * POI搜索結果(范圍檢索、城市POI檢索、周邊檢索)
- *
- * @param result
- * 搜索結果
- * @param type
- * 返回結果類型(11,12,21:poi列表 7:城市列表)
- * @param iError
- * 錯誤號(0表示正確返回)
- */
- public void onGetPoiResult(MKPoiResult result, int type, int iError) {
- }
- /**
- * 公交換乘路線搜索結果
- *
- * @param result
- * 搜索結果
- * @param iError
- * 錯誤號(0表示正確返回)
- */
- public void onGetTransitRouteResult(MKTransitRouteResult result,
- int iError) {
- }
- /**
- * 步行路線搜索結果
- *
- * @param result
- * 搜索結果
- * @param iError
- * 錯誤號(0表示正確返回)
- */
- public void onGetWalkingRouteResult(MKWalkingRouteResult result,
- int iError) {
- }
- public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
- // TODO Auto-generated method stub
- }
- public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
- // TODO Auto-generated method stub
- }
- }
- }
五:在AndroidManifest.xml住添加相關的訪問權限
<!-- 訪問網絡的權限 -->
- <uses-permission android:name="android.permission.INTERNET" />
- <!-- 訪問精確位置的權限 -->
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- <!-- 訪問網絡狀態的權限 -->
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <!-- 訪問WIFI網絡狀態的權限 -->
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- <!-- 改變WIFI網絡狀態的權限 -->
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
- <!-- 讀寫存儲卡的權限 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <!-- 讀取電話狀態的權限 -->
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />
六:運行結果如下圖: