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

百度地圖實戰:動態添加 Marker 與自訂 InfoWindow

編輯:關於 Android 程式設計

本文示範如何在百度地圖上動態生成覆蓋物、為每個覆蓋物綁定商家資料,並在點擊時彈出自訂的資訊窗與詳情面板。

需求是這樣的:使用者點擊「衣食住行」或進行周邊搜尋,伺服器回傳經緯度與商家資訊,App 據此動態生成覆蓋物,點擊後顯示詳情。

關於圖片:手機記憶體有限,所有網路圖片都應該走快取(如 LruCache),命中就直接取,未命中才下載並寫回,讓圖片佔用的記憶體永不超過設定上限。本篇重點不在此,因此直接放了幾張本地圖片來模擬。

一、資料載體

伺服器回傳的 JSON 需轉成實體集合。這裡用靜態清單模擬:

public class Info implements Serializable {
    private static final long serialVersionUID = -758459502806858414L;

    private double latitude;   // 緯度
    private double longitude;  // 經度
    private int imgId;         // 圖片 ID(真實專案可能是 URL)
    private String name;       // 商家名稱
    String distance;       // 距離
    private int zan;           // 讚數量

    public static List<Info> infos = new ArrayList<Info>();

    static {
        infos.add(new Info(34.242652, 108.971171, R.drawable.a01,
                "英倫貴族小旅館", "距離209米", 1456));
        infos.add(new Info(34.242952, 108.972171, R.drawable.a02,
                "沙井國際洗浴會所", "距離897米", 456));
        infos.add(new Info(34.242852, 108.973171, R.drawable.a03,
                "五環服裝城", "距離249米", 1456));
        infos.add(new Info(34.242152, 108.971971, R.drawable.a04,
                "老米家泡饃小炒", "距離679米", 1456));
    }

    // getter / setter 省略
}

二、動態添加 Overlay

為了方便,按鈕放在 OptionsMenu 裡:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.id_menu_map_addMaker:
            addInfosOverlay(Info.infos);
            break;
    }
    return true;
}

/** 初始化圖層 */
public void addInfosOverlay(List<Info> infos) {
    mBaiduMap.clear();
    LatLng latLng = null;
    for (Info info : infos) {
        latLng = new LatLng(info.getLatitude(), info.getLongitude());
        OverlayOptions overlayOptions = new MarkerOptions()
                .position(latLng)
                .icon(mIconMaker)
                .zIndex(5);
        Marker marker = (Marker) mBaiduMap.addOverlay(overlayOptions);

        // 把商家資料掛在 Marker 上,點擊時再取出
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", info);
        marker.setExtraInfo(bundle);
    }
    // 把地圖移到最後一個座標
    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
}

重點是 setExtraInfo():Marker 本身只能表達位置與圖示,但我們可以把任意 Bundle 掛上去,讓後續點擊事件能取回對應的業務資料。這是實作「覆蓋物與資料關聯」最乾淨的做法。

三、為 Marker 掛上點擊事件

mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(final Marker marker) {
        Info info = (Info) marker.getExtraInfo().get("info");

        // 建立要在地圖上顯示的 InfoWindow 內容
        TextView location = new TextView(getApplicationContext());
        location.setBackgroundResource(R.drawable.location_tips);
        // 注意順序:先設背景,再設 padding,否則 padding 可能失效
        location.setPadding(30, 20, 30, 50);
        location.setText(info.getName());

        // 把經緯度轉成螢幕座標,往上偏移避免遮住圖示
        final LatLng ll = marker.getPosition();
        Point p = mBaiduMap.getProjection().toScreenLocation(ll);
        p.y -= 47;
        LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);

        mInfoWindow = new InfoWindow(location, llInfo,
                new OnInfoWindowClickListener() {
                    @Override
                    public void onInfoWindowClick() {
                        mBaiduMap.hideInfoWindow();
                    }
                });
        mBaiduMap.showInfoWindow(mInfoWindow);

        mMarkerInfoLy.setVisibility(View.VISIBLE);
        popupInfo(mMarkerInfoLy, info);
        return true;
    }
});

用 ViewHolder 避免重複 findViewById:

private class ViewHolder {
    ImageView infoImg;
    TextView infoName;
    TextView infoDistance;
    TextView infoZan;
}

protected void popupInfo(RelativeLayout mMarkerLy, Info info) {
    ViewHolder viewHolder;
    if (mMarkerLy.getTag() == null) {
        viewHolder = new ViewHolder();
        viewHolder.infoImg = (ImageView) mMarkerLy.findViewById(R.id.info_img);
        viewHolder.infoName = (TextView) mMarkerLy.findViewById(R.id.info_name);
        viewHolder.infoDistance = (TextView) mMarkerLy.findViewById(R.id.info_distance);
        viewHolder.infoZan = (TextView) mMarkerLy.findViewById(R.id.info_zan);
        mMarkerLy.setTag(viewHolder);
    }
    viewHolder = (ViewHolder) mMarkerLy.getTag();

    viewHolder.infoImg.setImageResource(info.getImgId());
    viewHolder.infoName.setText(info.getName());
    viewHolder.infoDistance.setText(info.getDistance());
    viewHolder.infoZan.setText(info.getZan() + "");
}

最後補上地圖空白處的單擊事件,用來收起詳情面板與資訊窗:

mBaiduMap.setOnMapClickListener(new OnMapClickListener() {
    @Override
    public boolean onMapPoiClick(MapPoi arg0) {
        return false;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        mMarkerInfoLy.setVisibility(View.GONE);
        mBaiduMap.hideInfoWindow();
    }
});

四、布局檔

除了 MapView,其餘都是詳情面板,預設隱藏:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <RelativeLayout
        android:id="@+id/id_marker_info"
        android:layout_width="fill_parent"
        android:layout_height="220dp"
        android:layout_alignParentBottom="true"
        android:background="#CC4e5a6b"
        android:clickable="true"
        android:visibility="gone">

        <ImageView
            android:id="@+id/info_img"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:layout_margin="10dp"
            android:scaleType="fitXY" />

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/info_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#FFF5EB" />

                <TextView
                    android:id="@+id/info_distance"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#FFF5EB" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="20dp"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="zan"
                    android:src="@drawable/map_zan" />

                <TextView
                    android:id="@+id/info_zan"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#FFF5EB" />
            </LinearLayout>
        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>

實務上要注意的地方

  • API Key 與 MD5 是地圖能不能顯示的前提。Key 綁定到簽章檔的 SHA1/MD5,除錯與正式簽章不同,換機器就會白地圖,這是新手最常見的困惑。
  • 大量覆蓋物要用聚合。市中心幾百個 Marker 全畫上去會嚴重掉幀,百度 SDK 提供 MarkerCluster 工具,按縮放層級合併顯示。
  • InfoWindow 的座標換算是靜態的。地圖縮放或平移後,之前算好的 llInfo 不會跟著動。若需要「資訊窗永遠貼在圖示上方」,改用 BitmapDescriptorFactory 把資訊畫進圖示本身,或改用 Marker 的 perspective 能力。
  • 記得在 onDestroy 釋放:呼叫 mBaiduMap.clear() 並 dispose MapView,否則容易記憶體洩漏。
  • 定位權限要分開處理:顯示地圖只需網路權限,但「我的位置」藍點需要 ACCESS_FINE_LOCATION,且 Android 6.0 後必須動態申請。
  • 經緯度座標系別忘了對齊。百度使用 BD-09,GPS 原始資料是 WGS-84,直接丟進去會有幾百公尺偏移,必須先做座標轉換。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved