編輯:關於 Android 程式設計
在上一篇把地圖顯示出來之後,下一步自然是「我在哪裡」。高德定位 SDK 把 GPS、Wi-Fi、基站等多種來源封裝成一致的 API,你只要實作幾個回呼,就能拿到經緯度並在地圖上顯示藍點。本文以官方範例為基礎,逐段加上註解,讓整個流程更容易讀懂。
定位涉及網路、儲存、電話狀態、Wi-Fi 狀態等多項能力,因此 AndroidManifest.xml 需要一次把權限補齊。另外有一個關鍵點常被忽略:必須宣告 com.amap.api.location.APSService,否則定位會直接失敗並回報錯誤碼 10。
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.dragon.arnav">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application>
<!-- 請替換為自己在高德平台申請的 Key -->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="你的apikey" />
<activity android:name=".Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 定位服務,缺少這一段會導致定位失敗 -->
<service android:name="com.amap.api.location.APSService" />
</application>
</manifest>
提醒兩點:meta-data 中的 value 一定要換成你自己申請的 Key,直接照抄別人的沒有用;另外若在 Activity 上加上 android:configChanges="orientation|keyboardHidden|screenSize",可以自行處理橫豎屏切換而不重建 Activity。
版面很單純:一個填滿父容器的 MapView,加上一組 RadioButton 用來切換定位模式,再放一個 TextView 顯示錯誤資訊。
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.amap.api.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/location_errInfo_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:visibility="gone" />
<RadioGroup
android:id="@+id/gps_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/gps_locate_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/gpslocate" />
<RadioButton
android:id="@+id/gps_follow_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/gpsfollow" />
<RadioButton
android:id="@+id/gps_rotate_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/gpsrotate" />
</RadioGroup>
</FrameLayout>
這裡的關鍵是讓 Activity 同時實作 LocationSource(提供定位啟動/停止的入口)與 AMapLocationListener(接收定位結果)。地圖只負責顯示,定位由 AMapLocationClient 負責,兩者透過 LocationSource 串接起來。
package com.dragon.arnav;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
public class Main extends Activity
implements LocationSource, AMapLocationListener,
RadioGroup.OnCheckedChangeListener {
private AMap aMap;
private MapView mapView;
private OnLocationChangedListener mListener;
private AMapLocationClient mlocationClient;
private AMapLocationClientOption mLocationOption;
private RadioGroup mGPSModeGroup;
private TextView mLocationErrText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState); // 必須呼叫
init();
}
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
setUpMap();
}
mGPSModeGroup = (RadioGroup) findViewById(R.id.gps_radio_group);
mGPSModeGroup.setOnCheckedChangeListener(this);
mLocationErrText = (TextView) findViewById(R.id.location_errInfo_text);
mLocationErrText.setVisibility(View.GONE);
}
/** 設定地圖與定位相關屬性 */
private void setUpMap() {
aMap.setLocationSource(this); // 設定定位來源
aMap.getUiSettings().setMyLocationButtonEnabled(true); // 顯示定位按鈕
aMap.setMyLocationEnabled(true); // 顯示定位層並可觸發定位
aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE); // 定位模式
}
/** 切換定位模式:定位 / 跟隨 / 依地圖朝向旋轉 */
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.gps_locate_button:
aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
break;
case R.id.gps_follow_button:
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
break;
case R.id.gps_rotate_button:
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
break;
}
}
/** 激活定位:由地圖在顯示定位層時呼叫 */
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mlocationClient == null) {
mlocationClient = new AMapLocationClient(this);
mLocationOption = new AMapLocationClientOption();
mlocationClient.setLocationListener(this);
// 高精度模式,也可改為 Battery_Saving 或 Device_Sensors
mLocationOption.setLocationMode(
AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mlocationClient.setLocationOption(mLocationOption);
// 週期定位,最小間隔 2000ms;不需要時請 stopLocation() 以節電
mlocationClient.startLocation();
}
}
/** 停止定位 */
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
/** 定位結果回呼 */
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (mListener != null && amapLocation != null) {
if (amapLocation.getErrorCode() == 0) {
mLocationErrText.setVisibility(View.GONE);
mListener.onLocationChanged(amapLocation); // 地圖顯示藍點
} else {
String errText = "定位失敗, " + amapLocation.getErrorCode()
+ ": " + amapLocation.getErrorInfo();
Log.e("AmapErr", errText);
mLocationErrText.setVisibility(View.VISIBLE);
mLocationErrText.setText(errText);
}
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
deactivate();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (mlocationClient != null) {
mlocationClient.onDestroy();
}
}
}
LOCATION_TYPE_LOCATE 每次定位地圖都會移動到新位置;LOCATION_TYPE_MAP_FOLLOW 不移動地圖;LOCATION_TYPE_MAP_ROTATE 會依設備朝向旋轉地圖。onPause() 或不需要時呼叫 stopLocation(),這對電量與流量都有明顯影響。
執行後可以看到地圖上的藍點隨著位置移動,也能透過上方三個選項切換定位、跟隨與旋轉模式。定位成功後,你就能拿到完整的 AMapLocation 物件,裡面的經緯度、精度、地址等資訊可以進一步做周邊搜尋、導航或地理圍欄等進階應用。
【造輪子系列】轉輪選擇控件 WheelView 的性能改進之路
早期的 WheelView 存在兩個問題:滑動的性能和流暢性有待提高,尤其是快速滑動時的效果;另外沒有實現循環滾動。經過一段時間的不斷改進,如今已接近 iOS 鬧鐘滾輪時
Android 最佳實踐:UI 開發從多螢幕適配到沉浸式體驗
這篇整理 Android 官方 UI 訓練指南的實作要點,從多螢幕適配一路談到自訂 View、向下相容與沉浸式全螢幕,適合當作專案開發時的對照清單。 一、支援多種螢幕尺
Android ListView 靜態資料設定完整教學
有些時候,ListView 只需要呈現固定資料,不必從網路或資料庫動態取得。本文示範如何以靜態陣列建立圖文列表,並透過自訂 Adapter 完成顯示。 版面設計 主頁面
Android 播放視頻時的可拖拽懸浮窗口:DragVideo 與 ViewDragHelper 解析
為什麼做這個項目 在視頻網站看電影時有個細節很打動人:當頁面滑動遮住了播放窗口,播放器會縮成一個小窗固定在角落,而且這個小窗可以隨意拖動。既然 Web 端能做,移動端自然