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

百度地圖開發(二):城市定位與 POI 興趣點搜索

編輯:關於 Android 程式設計

一、知識準備

上一篇講了如何申請百度 API Key 以及解決地圖顯示空白網格的問題,本篇接著談三件事:定位城市、定位自身位置,以及城市 POI(Point of Interest)搜索。

要在地圖上定位某個坐標,用 GeoPoint 保存經緯度即可,再透過 getLastKnownLocation() 拿到 Location 對象,把坐標設為地圖中心。注意 GeoPoint 以「微度」為單位,數值需要乘以 10 的 6 次方:

// 通過網絡獲取當前位置
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1E6),
                              (int)(location.getLongitude() * 1E6));
mMapController.setCenter(point);

同理,只要知道城市經緯度,就能把地圖中心設過去。而經緯度怎麼來?百度提供了地理編碼檢索:

// 初始化 MKSearch
mMKSearch = new MKSearch();
mMKSearch.init(mBMapManager, new MySearchListener());

// 搜索城市
mMKSearch.geocode(city, city);

MKSearch.geocode(address, city) 是按地址檢索,若只想查城市本身,把兩個參數都傳城市名即可。反向操作則用 MKSearch.reverseGeocode(new GeoPoint(latitude, longitude)),由經緯度反查地址。

搜索結果通過 MKSearchListener 異步回調。其中 onGetAddrResult() 處理地址解析,POI 搜索則走 onGetPoiResult():

public class MySearchListener implements MKSearchListener {
    // 經緯度與地址搜索結果
    public void onGetAddrResult(MKAddrInfo result, int iError) { }

    // POI 搜索結果(范圍檢索、城市 POI 檢索、周邊檢索)
    public void onGetPoiResult(MKPoiResult result, int type, int iError) { }

    // 駕車路線搜索結果
    public void onGetDrivingRouteResult(MKDrivingRouteResult result, int iError) { }

    // 公交換乘路線搜索結果
    public void onGetTransitRouteResult(MKTransitRouteResult result, int iError) { }

    // 步行路線搜索結果
    public void onGetWalkingRouteResult(MKWalkingRouteResult result, int iError) { }

    public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) { }
    public void onGetPoiDetailSearchResult(int arg0, int arg1) { }
    public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) { }
    public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) { }
}

關於覆蓋物

所有疊加在地圖上的內容統稱為覆蓋物,包括標注、折線、多邊形、圓以及定位圖標等。它們各自帶有地理坐標,地圖拖動或縮放時會跟著移動。常見類型有:

  • Overlay:覆蓋物抽象基類,所有覆蓋物都繼承它,用於自定義圖層。
  • MyLocationOverlay:顯示使用者當前位置。
  • ItemizedOverlay:包含一組 OverlayItem 的集合型覆蓋物。
  • PoiOverlay:本地搜索圖層,比如在北京市搜索「公園」並標到圖上。
  • RouteOverlay:步行、駕車導航線路圖層。
  • TransitOverlay:公交換乘線路圖層。

二、源碼實現

布局 activity_main.xml

頂部放城市與關鍵詞輸入框加搜索按鈕,中部放 MapView,底部放定位按鈕。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    tools:context="com.example.baidumapshow.MainActivity" >

    <!-- 頂部路徑 -->
    <RelativeLayout
        android:id="@+id/MyLayout_top"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentTop="true"
        android:gravity="center" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="0dip" >

            <EditText
                android:id="@+id/city_edittext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="15"
                android:background="#ffffff"
                android:hint="輸入城市"
                android:textSize="22dp" />

            <EditText
                android:id="@+id/keyword_edittext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="25"
                android:layout_marginLeft="5dp"
                android:background="#ffffff"
                android:hint="輸入關鍵詞"
                android:textSize="22dp" />

            <Button
                android:id="@+id/query_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="搜索"
                android:textColor="#ffffff"
                android:textSize="20dp" />
        </LinearLayout>
    </RelativeLayout>

    <!-- 中部顯示地圖 -->
    <RelativeLayout
        android:id="@+id/Content_Layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/MyLayout_bottom"
        android:layout_below="@+id/MyLayout_top" >

        <com.baidu.mapapi.map.MapView
            android:id="@+id/map_view"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:clickable="true" />
    </RelativeLayout>

    <!-- 底部按鈕 -->
    <RelativeLayout
        android:id="@+id/MyLayout_bottom"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:gravity="center" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="定位"
            android:textColor="#ffffff" />
    </RelativeLayout>
</RelativeLayout>

MainActivity 源碼

public class MainActivity extends Activity {

    // BMapManager 對象管理地圖、定位、搜索功能
    private BMapManager mBMapManager;
    private MapView mapView = null;          // 地圖主控件
    private MapController mMapController = null;  // 地圖控制
    private MKMapViewListener mMapListener = null; // 處理地圖事件回調
    private MKSearch mMKSearch;              // 定義搜索服務類

    private EditText keyWordEditText;
    private EditText cityEditText;
    private Button queryButton;
    private static StringBuilder sb;
    private MyLocationOverlay myLocationOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 創建 BMapManager 並初始化
         * 注意:初始化操作必須在 setContentView() 之前
         */
        mBMapManager = new BMapManager(getApplication());
        mBMapManager.init(null);
        setContentView(R.layout.activity_main);

        mapView = (MapView) findViewById(R.id.map_view);
        cityEditText = (EditText) findViewById(R.id.city_edittext);
        keyWordEditText = (EditText) findViewById(R.id.keyword_edittext);
        queryButton = (Button) findViewById(R.id.query_button);

        mMapController = mapView.getController();   // 獲取地圖控制器
        mMapController.enableClick(true);           // 設置地圖是否響應點擊
        mMapController.setZoom(16);                 // 縮放級別 3-19,級別越高信息越詳細
        mapView.setBuiltInZoomControls(true);       // 顯示內置縮放控件

        // 設置地圖中心點
        GeoPoint point = new GeoPoint((int)(39.96703 * 1E6), (int)(116.323772 * 1E6));
        mMapController.setCenter(point);

        mapView.regMapViewListener(mBMapManager, new MKMapViewListener() {
            @Override
            public void onMapMoveFinish() { }

            @Override
            public void onMapLoadFinish() {
                Toast.makeText(MainActivity.this, "地圖載入", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onMapAnimationFinish() { }

            @Override
            public void onGetCurrentMap(Bitmap arg0) { }

            @Override
            public void onClickMapPoi(MapPoi arg0) {
                if (arg0 != null) {
                    Toast.makeText(MainActivity.this, arg0.strText, Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 初始化 MKSearch,調用城市和 POI 搜索
        mMKSearch = new MKSearch();
        mMKSearch.init(mBMapManager, new MySearchListener());

        queryButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mMapController = mapView.getController();
                mMapController.setZoom(10);
                sb = new StringBuilder();

                String city = cityEditText.getText().toString().trim();
                String keyWord = keyWordEditText.getText().toString().trim();
                if (city.isEmpty()) {
                    city = "貴陽";   // 默認城市
                }
                if (keyWord.isEmpty()) {
                    // 關鍵字為空,只搜索城市 GEO 搜索
                    mMKSearch.geocode(city, city);
                } else {
                    // 搜索城市 + 關鍵字
                    mMKSearch.setPoiPageCapacity(10);   // 每頁返回 POI 數
                    mMKSearch.poiSearchInCity(city, keyWord);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        if (mBMapManager != null) {
            mBMapManager.start();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        if (mBMapManager != null) {
            mBMapManager.stop();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mapView.destroy();
        if (mBMapManager != null) {
            mBMapManager.destroy();
            mBMapManager = null;
        }
        super.onDestroy();
    }

    /** 內部類實現 MKSearchListener 接口,用於異步搜索服務 */
    public class MySearchListener implements MKSearchListener {

        /** 根據經緯度搜索地址信息的結果 */
        @Override
        public void onGetAddrResult(MKAddrInfo result, int iError) {
            if (result == null) {
                return;
            }
            StringBuffer sbcity = new StringBuffer();
            sbcity.append(result.strAddr);

            mapView.getOverlays().clear();       // 清除已有覆蓋物
            mMapController.setCenter(result.geoPt);   // 置為地圖中心

            // 添加原點並刷新
            LocationData locationData = new LocationData();
            locationData.latitude = result.geoPt.getLatitudeE6();
            locationData.longitude = result.geoPt.getLongitudeE6();
            myLocationOverlay = new MyLocationOverlay(mapView);
            myLocationOverlay.setData(locationData);
            mapView.getOverlays().add(myLocationOverlay);
            mapView.refresh();

            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("顯示當前城市地圖")
                    .setMessage(sbcity.toString())
                    .setPositiveButton("關閉", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }).create().show();
        }

        /** POI 搜索結果(范圍檢索、城市 POI 檢索、周邊檢索) */
        @Override
        public void onGetPoiResult(MKPoiResult result, int type, int iError) {
            if (result == null) {
                return;
            }
            mapView.getOverlays().clear();
            PoiOverlay poioverlay = new PoiOverlay(MainActivity.this, mapView);
            poioverlay.setData(result.getAllPoi());   // 設置搜索到的 POI 數據
            mapView.getOverlays().add(poioverlay);    // 興趣點標注在地圖上
            mapView.refresh();

            // 將第一個搜索結果設為地圖中心
            if (result.getNumPois() > 0) {
                MKPoiInfo poiInfo = result.getPoi(0);
                mMapController.setCenter(poiInfo.pt);
            }

            // 遍歷當前頁返回的 POI(默認只返回 10 個)
            sb.append("共搜索到").append(result.getNumPois()).append("個POI ");
            for (MKPoiInfo poiInfo : result.getAllPoi()) {
                sb.append("名稱:").append(poiInfo.name).append(" ");
            }

            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("搜索到的POI信息")
                    .setMessage(sb.toString())
                    .setPositiveButton("關閉", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }).create().show();
        }

        @Override
        public void onGetDrivingRouteResult(MKDrivingRouteResult result, int iError) { }
        @Override
        public void onGetTransitRouteResult(MKTransitRouteResult result, int iError) { }
        @Override
        public void onGetWalkingRouteResult(MKWalkingRouteResult result, int iError) { }
        @Override
        public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) { }
        @Override
        public void onGetPoiDetailSearchResult(int arg0, int arg1) { }
        @Override
        public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) { }
        @Override
        public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) { }
    }
}

AndroidManifest.xml

需要申請網絡、定位、存儲等權限,並配置 API Key:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.baidumapshow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="19" />

    <!-- 獲取網絡狀態 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 訪問網絡 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 獲取 WiFi 狀態 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- 寫入外部存儲 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <!-- 讀取電話狀態 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <!-- GPS 精確定位,精度可達 10 米以內 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 通過 WiFi 或移動基站獲取粗略經緯度 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />

    <application>
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="你的API_KEY" />
    </application>
</manifest>

三、運行結果

只輸入城市名時,顯示該城市對應的地圖,如下圖的貴陽:

輸入「城市 + 關鍵詞」時,則顯示 POI 興趣點,例如北京的大學(本例限制只顯示 10 個):

測試縣份級別同樣能顯示,例如施秉縣,但城市名錯誤的異常處理尚未做:

幾點補充

搜索城市時覆蓋物沒有正常顯示,原因通常是 geocode() 回調裡對 overlays 的清理與添加時序有衝突,可以在添加後再調一次 mapView.refresh() 確認。另外示例用的是 V2.4.1 版本的 SDK,如今官方已迭代到更新版本,API 差異較大,建議直接參考現行官方文檔與其提供的 Demo,本篇思路仍可借鑑。

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