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

百度地圖定位簽到功能實作

編輯:關於 Android 開發

百度地圖定位簽到功能實作

本文說明如何在 Android 專案中整合百度地圖定位功能,並將定位結果顯示在地圖上,常用於簽到、位置分享與附近服務等情境。

一、設定 API Key

在 AndroidManifest.xml 中加入百度地圖 API Key。請將 value 替換為你在百度地圖開放平台申請的 Key。

<meta-data
    android:name="com.baidu.lbsapi.API_KEY"
    android:value="你的百度地圖 API Key" />

二、加入 MapView

在版面配置中加入百度地圖 MapView 元件。

<com.baidu.mapapi.map.MapView
    android:id="@+id/map_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

三、初始化定位

在 Activity 中初始化 SDK、取得地圖物件、建立 LocationClient,並註冊定位監聽器。

SDKInitializer.initialize(getApplicationContext());
mMapView = findViewById(R.id.map_view);
mBaiduMap = mMapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.setLocOption(getDefaultLocationClientOption());
mLocationClient.registerLocationListener(mBDLocationListener);
mLocationClient.start();

四、設定定位參數

LocationClientOption 可設定定位模式、座標系統、是否需要地址資訊與周邊 POI 等。

mOption = new LocationClientOption();
mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
mOption.setCoorType("bd09ll");
mOption.setIsNeedAddress(true);
mOption.setIsNeedLocationDescribe(true);
mOption.setIsNeedLocationPoiList(true);

五、顯示定位結果

收到定位結果後,可建立 MyLocationData 顯示目前位置;若是第一次定位,可加上標記與圓圈,並將地圖中心移動到該座標。

MyLocationData locData = new MyLocationData.Builder()
        .accuracy(location.getRadius())
        .latitude(location.getLatitude())
        .longitude(location.getLongitude())
        .build();
mBaiduMap.setMyLocationData(locData);

六、生命週期管理

記得在 onResume、onPause 與 onDestroy 中呼叫 MapView 對應方法,並停止定位與釋放資源。

完成以上步驟後,即可實現基本的定位簽到畫面。若要計算兩點距離,可再使用座標轉換與距離公式進行處理。

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