「附近有什麼」是 LBS 應用最典型的需求。百度地圖 SDK 把這件事抽象成 poiSearchNearBy 一個方法:給定關鍵字、中心座標與半徑,結果會透過 onGetPoiResult 非同步送回,再用 PoiOverlay 標註到地圖上即可。
public class LBSProjectActivity extends MapActivity {
private BMapManager mapManager;
private MapView mapView;
private MapController mapController;
private MKSearch mSearch = null;
private GeoPoint geoPoint = new GeoPoint(122084095, 37422006);
private MyLocationOverlay mLocationOverlay = null;
private EditText editCity, editGeoCodeKey, areaText;
private GetOverlay getOverlay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getInitLoc(); // 先取當前位置
mapManager = new BMapManager(getApplication());
mapManager.init("請填入你申請的 APIKey", null); // 第一個參數為 APIKey
super.initMapActivity(mapManager);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setDrawOverlayWhenZooming(true);
mLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mLocationOverlay); // 定位圖層
getOverlay = new GetOverlay();
mapView.getOverlays().add(getOverlay);
gotoLocate();
// ... 按鈕與輸入框的監聽器設定
}
}
只要把關鍵字、中心點與距離(公尺)交給 poiSearchNearBy:
areaText = (EditText) findViewById(R.id.searchKeywords);
Button buttonSearchArea = (Button) findViewById(R.id.buttonSearchArea);
buttonSearchArea.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 搜尋 geoPoint 周邊 5000 公尺內的指定關鍵字
mSearch.poiSearchNearBy(areaText.getText().toString(), geoPoint, 5000);
}
});
也可以用選單預設幾個常用類別,切換時只是換關鍵字:
case 0: mSearch.poiSearchNearBy("KTV", geoPoint, 5000); break;
case 1: mSearch.poiSearchNearBy("學校", geoPoint, 5000); break;
case 2: mSearch.poiSearchNearBy("餐廳", geoPoint, 5000); break;
case 3: mSearch.poiSearchNearBy("公園", geoPoint, 5000); break;
結果回呼裡要先判空與判錯誤碼,再依「有 POI 結果」或「只回傳城市列表」兩種情況分別處理。
public void onGetPoiResult(MKPoiResult res, int type, int error) {
if (error != 0 || res == null) {
Toast.makeText(LBSProjectActivity.this, "抱歉,未找到結果",
Toast.LENGTH_LONG).show();
return;
}
// 情況一:找到興趣點,用 PoiOverlay 全部標到圖上
if (res.getCurrentNumPois() > 0) {
PoiOverlay poiOverlay = new PoiOverlay(LBSProjectActivity.this, mapView);
poiOverlay.setData(res.getAllPoi());
mapView.getOverlays().clear();
mapView.getOverlays().add(getOverlay);
mapView.getOverlays().add(poiOverlay);
mapView.invalidate();
mapView.getController().animateTo(res.getPoi(0).pt);
}
// 情況二:只匹配到城市,提示使用者
else if (res.getCityListNum() > 0) {
String strInfo = "在";
for (int i = 0; i < res.getCityListNum(); i++) {
strInfo += res.getCityListInfo(i).city + ",";
}
strInfo += "找到結果";
Toast.makeText(LBSProjectActivity.this, strInfo, Toast.LENGTH_LONG).show();
}
}
定位有兩條路:一是用 Android 原生的 LocationManager 搭配 Criteria 取最後已知位置,二是註冊百度自己的 LocationListener 做持續更新。兩者取到的經緯度都要乘上 1e6 轉成 GeoPoint 使用的整數格式。
private void getInitLoc() { // 啟動時取一次座標
try {
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
geoPoint = new GeoPoint((int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6));
} catch (Exception e) {
// 定位失敗時保留預設座標即可
}
}
class GetOverlay extends Overlay {
GeoPoint geo;
@Override
public boolean onTap(GeoPoint geo, MapView arg1) {
geoPoint = geo; // 更新中心點
Drawable marker = getResources().getDrawable(R.drawable.iconmarka);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
mapView.getOverlays().clear();
mapView.getOverlays().add(getOverlay);
mapView.getOverlays().add(new OverItemT(marker, LBSProjectActivity.this,
geoPoint, ""));
return super.onTap(geo, arg1);
}
}
百度地圖 SDK 對生命週期很敏感,四個回呼都要照顧到,否則會出現地圖空白或定位不更新的問題:
@Override
protected void onResume() {
if (mapManager != null) {
mapManager.getLocationManager().requestLocationUpdates(mLocationListener);
mLocationOverlay.enableMyLocation();
mLocationOverlay.enableCompass(); // 開啟指南針
mapManager.start();
}
super.onResume();
}
@Override
protected void onPause() {
if (mapManager != null) {
mapManager.getLocationManager().removeUpdates(mLocationListener);
mLocationOverlay.disableMyLocation();
mLocationOverlay.disableCompass();
mapManager.stop();
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mapManager != null) {
mapManager.destroy(); // 程式退出前必須呼叫
mapManager = null;
}
super.onDestroy();
}
另外別忘了 isRouteDisplayed() 要回傳 false,並在 manifest 中補上網路與定位相關權限。把「取中心點 → 發起檢索 → 非同步繪製 → 生命週期管理」這四塊拼起來,一個可用的周邊搜尋功能就完成了。