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

第 3 章(第 12 講):百度地圖 POI 搜索與 Suggestion 聯想查詢實作

編輯:關於 Android 開發

第 3 章(第 12 講) POI 搜索功能

分類:C#、Android、百度地圖應用;日期:2016-02-04

一、簡介

POI(Point of Interest)中文譯作「興趣點」。在地理信息系統中,一個 POI 可以是一棟樓、一家商鋪、一個郵筒或一座公交站。

1. POI 檢索

百度地圖 SDK 提供三類檢索方式:

  • 周邊檢索:以某點為圓心、指定距離為半徑,按關鍵詞檢索。
  • 區域檢索:在指定矩形區域內按關鍵詞檢索。
  • 城市內檢索:在指定城市範圍內按關鍵詞檢索。

自 v3.6.1 起,城市 POI 檢索的返回結果新增了門址類列表數據。例如在「北京」搜索「上地十街 1 號」,除了包含該關鍵詞的 POI 列表,還會返回地址明確為「上地十街 1 號」的門址結果。具體來說,PoiSearch.SearchInCity() 返回的 PoiResult 新增了 GetAllAddr();當 isHasAddrInfo() 為 true 時,除原 POI 列表外還包含門址結果。

2. POI 詳情檢索

根據 POI 的 UID 檢索該興趣點的詳情信息。

3. 在線建議查詢(Suggestion)

根據輸入的部分關鍵詞,返回可能的完整關鍵詞建議。自 3.5.0 起,SDK 同時開放建議結果的經緯度與對應 POI 的 UID。

需要注意兩點:

  • 建議檢索的本質是「用部分關鍵詞換完整名稱」,若需要具體 POI 信息,仍要再走一次 POI 檢索。
  • 建議結果的第一條可能沒有經緯度。例如輸入「肯」,第一條是「肯德基」——這是聯想出來的泛指名稱,並不對應任何確切 POI 點。

二、示例說明

本示例演示關鍵詞查詢、Suggestion 聯想查詢,以及餐飲類 Place 詳情頁的查看:

  1. 點擊某些關鍵詞(如「餐廳」)檢索後的結果,可跳轉到 Place 詳情頁;
  2. 提供 Suggestion 聯想查詢,例如輸入「天安門」會彈出聯想列表。

1. 布局文件

顶部一個輸入城市與關鍵詞的檢索欄(關鍵詞框用 AutoCompleteTextView 承載聯想列表),下面一排「開始」與「下一組數據」按鈕,主體是地圖 Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal">
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="在" />
        <EditText android:id="@+id/city" android:layout_width="wrap_content"
            android:layout_height="match_parent" android:text="北京" />
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="市內找" />
        <AutoCompleteTextView android:id="@+id/searchkey"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_weight="0.88" android:text="餐廳" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal">
        <Button android:id="@+id/search" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:layout_weight="12"
            android:background="@drawable/button_style" android:padding="10dip"
            android:text="開始" />
        <Button android:id="@+id/map_next_data" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:layout_weight="12"
            android:background="@drawable/button_style" android:padding="10dip"
            android:text="下一組數據" />
    </LinearLayout>

    <fragment android:id="@+id/map" android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.baidu.mapapi.map.TextureMapFragment" />
</LinearLayout>

2. 添加 OverlayManager.cs

新建 SrcOverlayUtil 文件夾並在其中添加該文件。這個文件夾用於存放基於基礎 Overlay 組合而成的高級覆蓋物,比如顯示 POI 數據、規劃路線、公交詳情等。

namespace BdMapV371Demos.SrcOverlayUtil
{
    /// <summary>
    /// 提供一個能夠顯示和管理多個 Overlay 的基類。
    /// 將覆蓋物點擊事件傳遞給 OverlayManager 後,才能響應點擊事件。
    /// </summary>
    public abstract class OverlayManager : Java.Lang.Object,
            BaiduMap.IOnMarkerClickListener, BaiduMap.IOnPolylineClickListener
    {
        BaiduMap mBaiduMap = null;
        private List<OverlayOptions> mOverlayOptionList = null;
        protected List<Overlay> mOverlayList = null;

        public OverlayManager(BaiduMap baiduMap)
        {
            mBaiduMap = baiduMap;
            mBaiduMap.SetOnMarkerClickListener(this);
            mOverlayOptionList = new List<OverlayOptions>();
            mOverlayList = new List<Overlay>();
        }

        /// 子類重寫此方法,返回要管理的 Overlay 列表
        public abstract List<OverlayOptions> GetOverlayOptions();

        public void AddToMap()
        {
            if (mBaiduMap == null) return;
            RemoveFromMap();
            mOverlayOptionList.AddRange(GetOverlayOptions());
            foreach (OverlayOptions option in mOverlayOptionList)
            {
                mOverlayList.Add(mBaiduMap.AddOverlay(option));
            }
        }

        public void RemoveFromMap()
        {
            if (mBaiduMap == null) return;
            foreach (Overlay marker in mOverlayList) marker.Remove();
            mOverlayOptionList.Clear();
            mOverlayList.Clear();
        }

        /// 縮放地圖使所有 Overlay 進入視野(僅對 Marker 有效)
        public void ZoomToSpan()
        {
            if (mBaiduMap == null || mOverlayList.Count == 0) return;
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            foreach (Overlay overlay in mOverlayList)
            {
                if (overlay is Marker) builder.Include(((Marker) overlay).Position);
            }
            mBaiduMap.SetMapStatus(MapStatusUpdateFactory.NewLatLngBounds(builder.Build()));
        }

        public virtual bool OnMarkerClick(Marker marker) { return false; }
        public virtual bool OnPolylineClick(Polyline polyline) { return false; }
    }
}

3. 添加 PoiOverlay.cs

public class PoiOverlay : OverlayManager
{
    private static readonly int MaxPoiSize = 10;
    private PoiResult mPoiResult = null;

    public PoiOverlay(BaiduMap baiduMap) : base(baiduMap) { }

    public void SetData(PoiResult poiResult)
    {
        this.mPoiResult = poiResult;
    }

    public override List<OverlayOptions> GetOverlayOptions()
    {
        if (mPoiResult == null || mPoiResult.AllPoi == null) return null;
        List<OverlayOptions> markerList = new List<OverlayOptions>();
        int markerSize = 0;
        for (int i = 0; i < mPoiResult.AllPoi.Count && markerSize < MaxPoiSize; i++)
        {
            if (mPoiResult.AllPoi[i].Location == null) continue;
            markerSize++;
            Bundle bundle = new Bundle();
            bundle.PutInt("index", i);
            markerList.Add(new MarkerOptions()
                .InvokeIcon(BitmapDescriptorFactory.FromAssetWithDpi("Icon_mark" + markerSize + ".png"))
                .InvokeExtraInfo(bundle)
                .InvokePosition(mPoiResult.AllPoi[i].Location));
        }
        return markerList;
    }

    public PoiResult GetPoiResult() { return mPoiResult; }

    public override bool OnMarkerClick(Marker marker)
    {
        if (!mOverlayList.Contains(marker)) return false;
        if (marker.ExtraInfo != null) return OnPoiClick(marker.ExtraInfo.GetInt("index"));
        return false;
    }

    public virtual bool OnPoiClick(int i)
    {
        if (mPoiResult.AllPoi != null && mPoiResult.AllPoi[i] != null)
        {
            Toast.MakeText(BMapManager.Context, mPoiResult.AllPoi[i].Name,
                ToastLength.Long).Show();
        }
        return false;
    }
}

4. 添加 Demo12PoiSearch.cs

[Activity(Label = "@string/demo_name_poi",
    ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden,
    ScreenOrientation = ScreenOrientation.Sensor)]
public class Demo12PoiSearch : FragmentActivity
{
    private PoiSearch mPoiSearch = null;
    private SuggestionSearch mSuggestionSearch = null;
    private BaiduMap mBaiduMap = null;
    private AutoCompleteTextView keyWorldsView = null;
    private ArrayAdapter<string> sugAdapter = null;
    private int load_Index = 0;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.demo12_poisearch);

        // 初始化搜索模塊,注册搜索事件監聽
        mPoiSearch = PoiSearch.NewInstance();
        mPoiSearch.GetPoiResult += (s, e) =>
        {
            var result = e.P0;
            if (result == null || result.Error == SearchResult.ERRORNO.ResultNotFound) return;
            if (result.Error == SearchResult.ERRORNO.NoError)
            {
                mBaiduMap.Clear();
                PoiOverlay overlay = new MyPoiOverlay(this, mBaiduMap);
                mBaiduMap.SetOnMarkerClickListener(overlay);
                overlay.SetData(result);
                overlay.AddToMap();
                overlay.ZoomToSpan();
                return;
            }
            if (result.Error == SearchResult.ERRORNO.AmbiguousKeyword)
            {
                // 本市沒找到,但其他城市找到了,返回城市列表提示
                string strInfo = "在";
                foreach (CityInfo cityInfo in result.SuggestCityList)
                {
                    strInfo += cityInfo.City + ",";
                }
                strInfo += "找到結果";
                Toast.MakeText(this, strInfo, ToastLength.Long).Show();
            }
        };

        mPoiSearch.GetPoiDetailResult += (s, e) =>
        {
            var result = e.P0;
            Toast.MakeText(this,
                result.Error != SearchResult.ERRORNO.NoError ? "抱歉,未找到結果" : "成功,查看詳情頁面",
                ToastLength.Short).Show();
        };

        mSuggestionSearch = SuggestionSearch.NewInstance();
        mSuggestionSearch.GetSuggestionResult += (s, e) =>
        {
            var res = e.P0;
            if (res == null || res.AllSuggestions == null) return;
            sugAdapter.Clear();
            foreach (SuggestionResult.SuggestionInfo info in res.AllSuggestions)
            {
                if (info.Key != null) sugAdapter.Add(info.Key);
            }
            sugAdapter.NotifyDataSetChanged();
        };

        keyWorldsView = FindViewById<AutoCompleteTextView>(Resource.Id.searchkey);
        sugAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleDropDownItem1Line);
        keyWorldsView.Adapter = sugAdapter;

        mBaiduMap = FragmentManager
            .FindFragmentById<TextureMapFragment>(Resource.Id.map).BaiduMap;

        // 輸入變化時動態更新建議列表
        keyWorldsView.TextChanged += (sender, e) =>
        {
            string s = e.Text.ToString();
            if (s.Length <= 0) return;
            string city = FindViewById<EditText>(Resource.Id.city).Text;
            mSuggestionSearch.RequestSuggestion(
                new SuggestionSearchOption().Keyword(s).City(city));
        };

        FindViewById<Button>(Resource.Id.search).Click += delegate { SearchButtonProcess(); };
        FindViewById<Button>(Resource.Id.map_next_data).Click += delegate
        {
            load_Index++;
            SearchButtonProcess();
        };
    }

    protected override void OnDestroy()
    {
        mPoiSearch.Destroy();
        mSuggestionSearch.Destroy();
        base.OnDestroy();
    }

    public void SearchButtonProcess()
    {
        string city = FindViewById<EditText>(Resource.Id.city).Text;
        string key  = FindViewById<EditText>(Resource.Id.searchkey).Text;
        mPoiSearch.SearchInCity(new PoiCitySearchOption()
            .City(city).Keyword(key).PageNum(load_Index));
    }

    /// 點擊 marker 時,若該 POI 有餐飲詳情,則檢索詳情頁
    private class MyPoiOverlay : PoiOverlay
    {
        Demo12PoiSearch poiSearchDemo;
        public MyPoiOverlay(Demo12PoiSearch poiSearchDemo, BaiduMap baiduMap) : base(baiduMap)
        {
            this.poiSearchDemo = poiSearchDemo;
        }
        public override bool OnPoiClick(int index)
        {
            base.OnPoiClick(index);
            PoiInfo poi = GetPoiResult().AllPoi[index];
            if (poi.HasCaterDetails)
            {
                poiSearchDemo.mPoiSearch.SearchPoiDetail(
                    new PoiDetailSearchOption().PoiUid(poi.Uid));
            }
            return true;
        }
    }
}

5. 修改 MainActivity.cs

在 demos 字段定義中,去掉【示例 12】下方的注釋即可,然後運行觀察結果。

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