編輯:關於 Android 程式設計
本文以一個實際案例,講解如何在 Android 中接入百度地圖 SDK,完成定位後再檢索周邊地點的完整流程,分享出來供大家參考。
效果預覽:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="@dimen/height_top_bar" android:background="@color/common_top_bar_dark" android:gravity="center_vertical"> <Button android:id="@+id/btn_location_back" android:layout_width="wrap_content" android:layout_height="match_parent" android:drawableLeft="@drawable/back" android:text="@string/top_back" android:layout_alignParentLeft="true" android:onClick="back" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/location_message" /> <Button android:id="@+id/btn_location_ok" android:layout_width="52dp" android:layout_height="match_parent" android:layout_alignParentRight="true" android:background="@drawable/common_tab_bg" android:text="@string/txt_queding" /> </RelativeLayout> <com.baidu.mapapi.map.MapView android:layout_weight="2" android:id="@+id/mapview_location" android:layout_width="fill_parent" android:layout_height="match_parent" android:clickable="true" /> <ListView android:layout_weight="3" android:id="@+id/lv_location_nearby" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>

佈局很直觀:上方是百度地圖的 MapView,下方是一個用來列出周邊地點的 ListView。
先來看看如何依據裝置當前位置自動定位。
1. 初始化各元件
/** * 初始化組件 */ private void initView() { btnLocationBack = (Button) findViewById(R.id.btn_location_back); btnLocationBack.setOnClickListener(this); btnLocationOk = (Button) findViewById(R.id.btn_location_ok); btnLocationOk.setOnClickListener(this); mapViewLocation = (MapView) findViewById(R.id.mapview_location); lvLocNear = (ListView) findViewById(R.id.lv_location_nearby); nearList = new ArrayList<PoiInfo>(); adapter = new LocNearAddressAdapter(context, nearList, isSelected); lvLocNear.setAdapter(adapter); }
2. 初始化 LocationClient,該物件需宣告於主執行緒
public LocationClient mLocationClient = null; public BDLocationListener myListener = new MyLocationListener(); public void onCreate() { mLocationClient = new LocationClient(getApplicationContext()); //聲明LocationClient類 mLocationClient.registerLocationListener( myListener ); //注冊監聽函數 }
3. 設定定位 SDK 參數
定位參數涵蓋:定位模式(高精度、低功耗、僅裝置三種)、回傳座標類型、是否啟用 GPS、是否回傳地址資訊、位置語意化資訊與 POI 資訊等。這些設定透過 LocationClientOption 類完成,它決定了 SDK 的定位行為。
private void initLocation(){ LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Hight_Accuracy );//可選,默認高精度,設置定位模式,高精度,低功耗,僅設備 option.setCoorType("bd09ll");//可選,默認gcj02,設置返回的定位結果坐標系 int span=1000; option.setScanSpan(span);//可選,默認0,即僅定位一次,設置發起定位請求的間隔需要大於等於1000ms才是有效的 option.setIsNeedAddress(true);//可選,設置是否需要地址信息,默認不需要 option.setOpenGps(true);//可選,默認false,設置是否使用gps option.setLocationNotify(true);//可選,默認false,設置是否當gps有效時按照1S1次頻率輸出GPS結果 option.setIsNeedLocationDescribe(true);//可選,默認false,設置是否需要位置語義化結果,可以在BDLocation.getLocationDescribe裡得到,結果類似於“在北京天安門附近” option.setIsNeedLocationPoiList(true);//可選,默認false,設置是否需要POI結果,可以在BDLocation.getPoiList裡得到 option.setIgnoreKillProcess(false);//可選,默認false,定位SDK內部是一個SERVICE,並放到了獨立進程,設置是否在stop的時候殺死這個進程,默認殺死 option.SetIgnoreCacheException(false);//可選,默認false,設置是否收集CRASH信息,默認收集 option.setEnableSimulateGps(false);//可選,默認false,設置是否需要過濾gps仿真結果,默認需要 mLocationClient.setLocOption(option); }
4. 實作 BDLocationListener 介面
/** * 監聽函數,有新位置的時候,格式化成字符串,輸出到屏幕中 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) { return; } Log.d("map", "On location change received:" + location); Log.d("map", "addr:" + location.getAddrStr()); if (progressDialog != null) { progressDialog.dismiss(); } if (lastLocation != null) { if (lastLocation.getLatitude() == location.getLatitude() && lastLocation.getLongitude() == location.getLongitude()) { Log.d("map", "same location, skip refresh"); // mMapView.refresh(); //need this refresh? return; } } lastLocation = location; mBaiduMap.clear(); mCurrentLantitude = lastLocation.getLatitude(); mCurrentLongitude = lastLocation.getLongitude(); Log.e(">>>>>>>", mCurrentLantitude + "," + mCurrentLongitude); LatLng llA = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()); CoordinateConverter converter = new CoordinateConverter(); converter.coord(llA); converter.from(CoordinateConverter.CoordType.COMMON); LatLng convertLatLng = converter.convert(); OverlayOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory .fromResource(R.drawable.icon_marka)) .zIndex(4).draggable(true); mCurrentMarker = (Marker) mBaiduMap.addOverlay(ooA); MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 16.0f); mBaiduMap.animateMapStatus(u); new Thread(new Runnable() { @Override public void run() { searchNeayBy(); } }).start(); } public void onReceivePoi(BDLocation poiLocation) { if (poiLocation == null) { return; } } }
回傳的 BDLocation 物件裡包含了大量欄位,幾乎都能派上用場。
這種方式不做自動定位,而是直接依據一組經緯度在地圖上標記位置。
/* * 顯示經緯度的位置 * */ private void showMap(double latitude, double longtitude, String address) { // sendButton.setVisibility(View.GONE); LatLng llA = new LatLng(latitude, longtitude); CoordinateConverter converter = new CoordinateConverter(); converter.coord(llA); converter.from(CoordinateConverter.CoordType.COMMON); LatLng convertLatLng = converter.convert(); OverlayOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marka)) .zIndex(4).draggable(true); markerA = (Marker) (mBaiduMap.addOverlay(ooA)); u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 16.0f); mBaiduMap.animateMapStatus(u); new Thread(new Runnable() { @Override public void run() { searchNeayBy(); } }).start(); }
最後的重點是取得周邊地理位置,這裡需要用到 SDK 的 PoiNearbySearchOption 類,先看看它提供的方法:
也就是說,我們只要設定關鍵字、檢索半徑、中心座標、排序方式、分頁編號與每頁數量,再實作 OnGetPoiSearchResultListener 介面來接收結果即可。
/** * 搜索周邊地理位置 */ private void searchNeayBy() { PoiNearbySearchOption option = new PoiNearbySearchOption(); option.keyword("寫字樓"); option.sortType(PoiSortType.distance_from_near_to_far); option.location(new LatLng(mCurrentLantitude, mCurrentLongitude)); if (radius != 0) { option.radius(radius); } else { option.radius(1000); } option.pageCapacity(20); mPoiSearch.searchNearby(option); } /* * 接受周邊地理位置結果 * @param poiResult */ @Override public void onGetPoiResult(PoiResult poiResult) { if (poiResult != null) { if (poiResult.getAllPoi()!=null&&poiResult.getAllPoi().size()>0){ nearList.addAll(poiResult.getAllPoi()); if (nearList != null && nearList.size() > 0) { for (int i = 0; i < nearList.size(); i++) { isSelected.put(i, false); } } Message msg = new Message(); msg.what = 0; handler.sendMessage(msg); } } }
取得資料後,更新 Adapter 並刷新列表即可。最後再補上一個小功能:點擊列表中的任一地點,地圖上的標記會隨之移動到對應位置。
/** * 周邊地理位置列表點擊事件 */ lvLocNear.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { adapter.setSelected(i); adapter.notifyDataSetChanged(); PoiInfo ad = (PoiInfo) adapter.getItem(i); u = MapStatusUpdateFactory.newLatLng(ad.location); mBaiduMap.animateMapStatus(u); if (!isLoc) { mCurrentMarker.setPosition(ad.location); } else { markerA.setPosition(ad.location); } } });
這樣就完成了一個實用又貼心的小功能,能顯著提升使用者體驗,希望大家會喜歡這篇文章。
Android Studio 教程(四):Gradle 基礎知識
很早之前就寫過一篇 Gradle 基礎博客,但時隔已久,Gradle 已經更新了很多。這次就結合 Studio 1.0 正式版與最新的 Gradle 語法,帶大家一步步重
深入淺出 Android 座標系統:自定義 View 的地基知識
網路上談自定義控件的文章很多,但多半停在「怎麼畫出來」,很少系統性地談「怎麼算對位置」。而重寫 View 的那些 onXXX() 方法,本質上處理的幾乎都是座標運算。所以
Android 自訂控件之滑動解鎖九宮格
概述 滑動解鎖九宮格的分析:1、需要自訂控件;2、需要重寫 onTouchEvent() 事件;3、需要給九個點設定序號與坐標,這裡用 Map 即可;4、需要判斷手指是否
Android 源碼解析(十四):Activity 啟動流程
Activity 是 Android 應用中最核心的組件之一。理解 Activity 的啟動流程,不僅能幫助我們更好地掌握 Android 系統的工作機制,也能讓我們在面