編輯:關於 Android 程式設計
在 Android 應用中,地圖功能的使用頻率相當高。回顧過去寫過的專案和用過的百度地圖 API,這裡整理一份從零開始實作 Android 百度地圖的完整流程,第一篇聚焦在地圖初始化與定位。
使用百度地圖時,首先會碰到 appkey 這個概念。官方說明是這樣的:
在使用百度地圖 SDK 為您提供的各種 LBS 能力之前,您需要獲取百度地圖移動版的開發密鑰,該密鑰與您的百度帳戶相關聯。因此,您必須先有百度帳戶,才能獲得開發密鑰。並且,該密鑰與您創建的過程名稱有關。Key 位址為:https://lbsyun.baidu.com/apiconsole/key
簡單講:一個專案的「套件包名 + SHA1」組合對應一個 appkey。所以先註冊百度帳號,然後按照官方教程一步步建立即可。要特別注意的是,如果日後改了包名或簽名憑證,舊的 appkey 就會失效,地圖會直接顯示不出來。
有了 appkey,就能開始部署環境。到百度地圖 API 的相關下載頁,把需要的功能勾選上,下載開發包與範例程式碼,然後把開發包匯入專案的 libs 資料夾。
接著配置 AndroidManifest.xml,需要三件事:加入權限、加入 appkey、註冊定位用的 Service。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="自己的包名"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<!-- 百度地圖權限 -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!-- 網路定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 存取得 WiFi 狀態,WiFi 資訊會用於網路定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 取得電信商資訊 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 讀取手機當前狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 寫入擴充儲存,用於寫入離線定位資料 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 網路定位需要連網 -->
<uses-permission android:name="android.permission.INTERNET" />
<application>
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="申請的appkey" />
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" />
</application>
</manifest>
補充一句實務提醒:Android 6.0 之後,ACCESS_COARSE_LOCATION、ACCESS_FINE_LOCATION、READ_PHONE_STATE 都屬於危險權限,光在 Manifest 宣告不夠,還必須在執行期用 requestPermissions() 動態向使用者申請,否則定位會直接失敗。
在 activity_main.xml 中加入地圖控件,本文還示範了自製的放大、縮小、定位等控制按鈕。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
<ImageButton
android:id="@+id/ib_small"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="60dp"
android:layout_marginRight="10dp"
android:background="@drawable/small" />
<ImageButton
android:id="@+id/ib_large"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_above="@+id/ib_small"
android:layout_alignLeft="@+id/ib_small"
android:background="@drawable/large" />
<ImageButton
android:id="@+id/ib_mode"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_above="@+id/ib_large"
android:layout_alignLeft="@+id/ib_large"
android:layout_marginBottom="12dp"
android:background="@drawable/mode" />
<ImageButton
android:id="@+id/ib_loc"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/ib_small"
android:layout_marginLeft="10dp"
android:background="@drawable/loc" />
<ImageButton
android:id="@+id/ib_traffic"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_above="@+id/ib_loc"
android:layout_alignLeft="@+id/ib_loc"
android:layout_marginBottom="12dp"
android:background="@drawable/offtraffic" />
</RelativeLayout>
顯示效果:

程式整體有三個功能:顯示地圖、顯示定位、按鈕控制。初始化順序如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 使用 SDK 各元件之前必須先初始化 context,傳入 ApplicationContext
// 注意:這個方法要在 setContentView 之前呼叫
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
// 初始化控件
initView();
// 初始化地圖
initMap();
// 定位
initLocation();
}
// 取得地圖控件引用
mMapView = (MapView) findViewById(R.id.bmapView);
// 不顯示縮放比例尺
mMapView.showZoomControls(false);
// 移除百度地圖 Logo(第 1 個子 View)
mMapView.removeViewAt(1);
// 取得百度地圖物件
mBaiduMap = mMapView.getMap();
// 改變地圖狀態,讓地圖顯示在合適的縮放級別
MapStatus mMapStatus = new MapStatus.Builder().zoom(15).build();
MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
mBaiduMap.setMapStatus(mMapStatusUpdate);
這裡有個細節值得注意:mMapView.removeViewAt(1) 這行是在移除官方 Logo。實務上是否該這麼做,要看你是否符合百度地圖的服務條款要求——多數商用場景下 Logo 與版權資訊是不能隨意移除的,這點建議先確認清楚。
在地圖初始化時我們把自帶的縮放比例尺關掉了,所以需要自製一組縮放按鈕。一般地圖顯示會落在 6 到 18 級之間,因此點擊事件裡要對級別做邊界判斷。
case R.id.ib_large:
if (zoomLevel < 18) {
mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
ib_small.setEnabled(true);
} else {
showInfo("已經放至最大,可繼續滑動操作");
ib_large.setEnabled(false);
}
break;
case R.id.ib_small:
if (zoomLevel > 6) {
mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
ib_large.setEnabled(true);
} else {
ib_small.setEnabled(false);
showInfo("已經縮至最小,可繼續滑動操作");
}
break;
zoomLevel 是一個全域變數,要讓它保持正確,就必須即時監控地圖的縮放級別。做法是替地圖掛上一個狀態變更監聽器:
// 設定地圖狀態改變監聽器
mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
@Override
public void onMapStatusChangeStart(MapStatus arg0) { }
@Override
public void onMapStatusChangeFinish(MapStatus arg0) { }
@Override
public void onMapStatusChange(MapStatus arg0) {
// 地圖狀態改變時,取得縮放級別
zoomLevel = arg0.zoom;
}
});
切換顯示模式與即時路況
boolean modeFlag = true; // 初始為普通模式
case R.id.ib_mode: // 衛星模式 / 普通模式切換
if (modeFlag) {
modeFlag = false;
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
showInfo("開啟衛星模式");
} else {
modeFlag = true;
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
showInfo("開啟普通模式");
}
break;
case R.id.ib_traffic: // 是否開啟路況圖
if (mBaiduMap.isTrafficEnabled()) {
mBaiduMap.setTrafficEnabled(false);
ib_traffic.setBackgroundResource(R.drawable.offtraffic);
showInfo("關閉即時路況圖");
} else {
mBaiduMap.setTrafficEnabled(true);
ib_traffic.setBackgroundResource(R.drawable.ontraffic);
showInfo("開啟即時路況圖");
}
break;
思路是這樣的:程式啟動時開啟定位圖層並開始定位,收到位置資訊後把自己的位置顯示在地圖中央;當使用者在地圖上滑動離開自身位置後,點擊定位圖標可把畫面重新拉回自身位置。
先開啟定位圖層並啟動定位:
@Override
protected void onStart() {
super.onStart();
// 開啟定位
mBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted()) {
// 若定位 client 尚未開啟,則啟動
mLocationClient.start();
}
}
private void initLocation() {
// 定位客戶端設定
mLocationClient = new LocationClient(this);
mLocationListener = new MyLocationListener();
// 註冊監聽
mLocationClient.registerLocationListener(mLocationListener);
// 定位參數設定
LocationClientOption option = new LocationClientOption();
option.setCoorType("bd09ll"); // 座標型別
option.setIsNeedAddress(true); // 是否需要地址資訊,預設不需要
option.setOpenGps(true); // 開啟 GPS
option.setScanSpan(1000); // 每 1000 毫秒定位一次
option.setIsNeedLocationPoiList(true); // 是否需要 POI 結果
mLocationClient.setLocOption(option);
}
自訂的定位監聽:
// 自訂的定位監聽
private class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// 把取得的 location 資訊交給百度地圖
MyLocationData data = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此處設定開發者取得的方向資訊,順時針 0-360
.direction(100)
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.build();
mBaiduMap.setMyLocationData(data);
if (isFirstLocation) {
// 取得經緯度
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
// mBaiduMap.setMapStatus(status); // 直接跳到位
mBaiduMap.animateMapStatus(status); // 以動畫方式移動過去
isFirstLocation = false;
showInfo("位置:" + location.getAddrStr());
}
}
}
這裡有個關鍵技巧:把 isFirstLocation 設為 true,只讓程式在啟動時定位一次並置中,避免每秒都跳一次。當使用者需要重新定位時,只要把它重設為 true 就行:
case R.id.ib_loc:
isFirstLocation = true;
showInfo("返回自己位置");
break;
最後別忘了在 Activity 結束時停止定位,否則會持續耗電:
@Override
protected void onStop() {
super.onStop();
// 關閉定位
mBaiduMap.setMyLocationEnabled(false);
if (mLocationClient.isStarted()) {
mLocationClient.stop();
}
}
此外,MapView 必須跟著 Activity 生命週期走,否則會出現畫面錯亂或資源洩漏:
@Override protected void onResume() { super.onResume(); mMapView.onResume(); }
@Override protected void onPause() { super.onPause(); mMapView.onPause(); }
@Override protected void onDestroy() { super.onDestroy(); mMapView.onDestroy(); }
package 包名;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* 我的百度地圖首頁
*/
public class MainActivity extends Activity implements OnClickListener {
private MapView mMapView = null;
private BaiduMap mBaiduMap;
private ImageButton ib_large, ib_small, ib_mode, ib_loc, ib_traffic;
// 模式切換,正常模式
private boolean modeFlag = true;
// 當前地圖縮放級別
private float zoomLevel;
// 定位相關
private LocationClient mLocationClient;
private MyLocationListener mLocationListener;
// 是否第一次定位,若是則需將自身位置顯示在地圖中央
private boolean isFirstLocation = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 使用 SDK 各元件之前初始化 context
// 注意:必須在 setContentView 之前呼叫
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
initView();
initMap();
initLocation();
}
private void initMap() {
mMapView = (MapView) findViewById(R.id.bmapView);
mMapView.showZoomControls(false);
mMapView.removeViewAt(1);
mBaiduMap = mMapView.getMap();
MapStatus mMapStatus = new MapStatus.Builder().zoom(15).build();
MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
mBaiduMap.setMapStatus(mMapStatusUpdate);
// 設定地圖狀態改變監聽器
mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
@Override public void onMapStatusChangeStart(MapStatus arg0) { }
@Override public void onMapStatusChangeFinish(MapStatus arg0) { }
@Override public void onMapStatusChange(MapStatus arg0) {
zoomLevel = arg0.zoom;
}
});
}
private void initLocation() {
mLocationClient = new LocationClient(this);
mLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(mLocationListener);
LocationClientOption option = new LocationClientOption();
option.setCoorType("bd09ll");
option.setIsNeedAddress(true);
option.setOpenGps(true);
option.setScanSpan(1000);
option.setIsNeedLocationPoiList(true);
mLocationClient.setLocOption(option);
}
private void initView() {
ib_large = (ImageButton) findViewById(R.id.ib_large);
ib_large.setOnClickListener(this);
ib_small = (ImageButton) findViewById(R.id.ib_small);
ib_small.setOnClickListener(this);
ib_mode = (ImageButton) findViewById(R.id.ib_mode);
ib_mode.setOnClickListener(this);
ib_loc = (ImageButton) findViewById(R.id.ib_loc);
ib_loc.setOnClickListener(this);
ib_traffic = (ImageButton) findViewById(R.id.ib_traffic);
ib_traffic.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ib_large:
if (zoomLevel < 18) {
mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
ib_small.setEnabled(true);
} else {
showInfo("已經放至最大,可繼續滑動操作");
ib_large.setEnabled(false);
}
break;
case R.id.ib_small:
if (zoomLevel > 6) {
mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
ib_large.setEnabled(true);
} else {
ib_small.setEnabled(false);
showInfo("已經縮至最小,可繼續滑動操作");
}
break;
case R.id.ib_mode: // 衛星模式與普通模式
if (modeFlag) {
modeFlag = false;
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
showInfo("開啟衛星模式");
} else {
modeFlag = true;
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
showInfo("開啟普通模式");
}
break;
case R.id.ib_loc:
isFirstLocation = true;
showInfo("返回自己位置");
break;
case R.id.ib_traffic: // 是否開啟路況圖
if (mBaiduMap.isTrafficEnabled()) {
mBaiduMap.setTrafficEnabled(false);
ib_traffic.setBackgroundResource(R.drawable.offtraffic);
showInfo("關閉即時路況圖");
} else {
mBaiduMap.setTrafficEnabled(true);
ib_traffic.setBackgroundResource(R.drawable.ontraffic);
showInfo("開啟即時路況圖");
}
break;
default:
break;
}
}
@Override
protected void onStart() {
super.onStart();
mBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted()) {
mLocationClient.start();
}
}
@Override
protected void onStop() {
super.onStop();
mBaiduMap.setMyLocationEnabled(false);
if (mLocationClient.isStarted()) {
mLocationClient.stop();
}
}
@Override
protected void onResume() { super.onResume(); mMapView.onResume(); }
@Override
protected void onPause() { super.onPause(); mMapView.onPause(); }
@Override
protected void onDestroy() { super.onDestroy(); mMapView.onDestroy(); }
// 顯示訊息
private void showInfo(String str) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
// 自訂的定位監聽
private class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
MyLocationData data = new MyLocationData.Builder()
.accuracy(location.getRadius())
.direction(100)
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.build();
mBaiduMap.setMyLocationData(data);
if (isFirstLocation) {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
mBaiduMap.animateMapStatus(status);
isFirstLocation = false;
showInfo("位置:" + location.getAddrStr());
}
}
}
}
跑起來之後,你會得到一個帶定位功能、能部分控制地圖顯示的 App。這篇要掌握的關鍵點有四個:SDKInitializer 必須在 setContentView 之前初始化;appkey 與包名及簽名綁定;定位要在 onStart 開、onStop 關;MapView 必須跟著 Activity 生命週期呼叫對應方法。這四點沒做對,地圖不會動。
用 RadioGroup 與 RadioButton 實作單選與預設選中
本文將透過 RadioGroup 搭配 RadioButton 來實作「組內單選」。所謂 RadioGroup,就是把多個 RadioButton 進行分組,讓它們能被統
Android 安全機制解讀:進程、多用戶與文件權限模型
Android 的安全基石並非什麼黑科技,而是沿用了 Linux 的一套成熟機制:進程隔離、多用戶邊界,以及 UID/GID 加 rwx 權限位。理解了這三層,才能看懂後
自定義 View 實作水波紋效果
效果一:遮罩式水波紋 第一種效果的核心,是把波紋圖與圓形遮罩圖結合,利用 PorterDuff 的 DST_IN 模式,只保留兩者交集的下半部分,讓水波看起來像是在圓形區
徹底搞懂 BaseAdapter 的 getView:ListView 為什麼只創建一屏 ItemView
先說結論:ListView 從不為每一條數據都造一個 View ListView 是 Android 開發裡出鏡率最高的控件之一,而與它配套的資料管理者就是 Adapte