Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

百度地圖 SDK 實作:定位與路線檢索完整範例

編輯:關於 Android 程式設計

本文以一個完整的 Activity 為例,示範如何整合百度地圖 SDK,實作地圖顯示、當前定位、地圖標註,以及公交路線規劃與檢索等功能。

整體流程可分為幾個關鍵步驟:初始化 SDK、設定定位參數、註冊定位監聽、在回呼中取得座標並標註到地圖,最後透過路線檢索 API 規劃起訖點之間的公交路線。

public class Baidumap extends AppCompatActivity {
    private BaiduMap mBaiduMap;
    MapView mMapView = null;
    boolean isFirstLoc = true; // 是否首次定位
    LocationClient mLocClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private RoutePlanSearch mSearch;
    boolean useDefaultIcon = false;
    private Button btn1;
    private String name;
    private String adr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使用 SDK 各組件前先初始化 context,傳入 ApplicationContext
        // 注意此方法要在 setContentView 之前呼叫
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_baidumap);
        Intent intent = getIntent();
        adr = intent.getStringExtra("adr"); // 取得傳入的目的地
        btn1 = (Button) findViewById(R.id.btn1);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); // 普通地圖
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener); // 註冊監聽函式
        initLocation();
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", name);
                PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", adr);
                mSearch.transitSearch((new TransitRoutePlanOption())
                        .from(stNode)
                        .city("北京")
                        .to(enNode));
            }
        });
    }

    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        public void onGetWalkingRouteResult(WalkingRouteResult result) { }
        public void onGetTransitRouteResult(TransitRouteResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(Baidumap.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
            }
            if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                // 起終點或途經點地址有歧義,可透過 result.getSuggestAddrInfo() 取得建議資訊
                return;
            }
            if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaiduMap);
                mBaiduMap.setOnMarkerClickListener(overlay);
                overlay.setData(result.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();
            }
        }
        public void onGetDrivingRouteResult(DrivingRouteResult result) { }
        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) { }
    };

    private class MyTransitRouteOverlay extends TransitRouteOverlay {
        public MyTransitRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }
        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }
        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy(); // 生命週期管理
        mLocClient.stop(); // 退出時銷毀定位
        mBaiduMap.setMyLocationEnabled(false); // 關閉定位圖層
        mMapView = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume(); // 生命週期管理
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause(); // 生命週期管理
    }

    // 地圖標註
    public void getLatLag(Double x, Double y) {
        LatLng point = new LatLng(x, y); // 定義座標點
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka); // 構建 Marker 圖示
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap)
                .zIndex(9) // 設定 marker 所在層級
                .draggable(true); // 支援手勢拖拽
        Marker marker = (Marker) mBaiduMap.addOverlay(option);
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); // 高精度定位模式
        option.setCoorType("bd09ll"); // 設定回傳座標系
        int span = 0;
        option.setScanSpan(span); // 0 表示僅定位一次,需 ≥1000ms 才有效
        option.setIsNeedAddress(true); // 是否需要地址資訊
        option.setOpenGps(true); // 是否使用 GPS
        option.setLocationNotify(true); // GPS 有效時是否以 1 秒 1 次頻率輸出
        option.setIsNeedLocationDescribe(true); // 是否需要位置語義化結果
        option.setIsNeedLocationPoiList(true); // 是否需要 POI 結果
        option.setIgnoreKillProcess(false); // stop 時是否殺死定位行程
        option.SetIgnoreCacheException(false); // 是否收集 CRASH 資訊
        option.setEnableSimulateGps(false); // 是否過濾 GPS 模擬結果
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) { // GPS 定位結果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed()); // 單位:公里每小時
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude()); // 單位:公尺
                sb.append("\ndirection : ");
                sb.append(location.getDirection()); // 單位:度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps 定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { // 網路定位結果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\noperationers : ");
                sb.append(location.getOperators()); // 運營商資訊
                sb.append("\ndescribe : ");
                sb.append("網路定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) { // 離線定位結果
                sb.append("\ndescribe : ");
                sb.append("離線定位成功,離線定位結果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服務端網路定位失敗,可回饋 IMEI 號與大致定位時間");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("網路不同導致定位失敗,請檢查網路是否通暢");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("無法取得有效定位依據,可能處於飛行模式,可嘗試重啟手機");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe()); // 位置語義化資訊
            List<poi> list = location.getPoiList(); // POI 數據
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());
            getLatLag(location.getLatitude(), location.getLongitude());
            name = list.get(0).getName();
        }
    }
}

使用時特別提醒:記得在 onResume、onPause、onDestroy 中相應地呼叫 MapView 的生命週期方法,並在退出時停止定位、關閉定位圖層,才能確保地圖資源被正確管理,避免記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved