編輯:關於 Android 程式設計
上一篇我們已經完成地圖定位,並結合方向感測器解決了「路癡不知道朝哪走」的痛點。若還沒看過,可以先參考〈定位與結合方向感測器〉那篇。本篇要往更實用的方向推進:如何在地圖上動態鋪滿覆蓋物、如何實現周邊搜尋結果的呈現,以及點擊覆蓋物後彈出商家介紹卡片。

先說清楚需求情境:當使用者點擊「衣食住行」這類分類,或執行附近搜尋時,伺服器會回傳一批資料(經緯度、商家名稱、介紹、距離等),App 需要根據這批資料動態生成覆蓋物,點擊後再展開詳情。
至於圖片處理,由於手機記憶體有限,正式專案裡所有網路圖片都應該寫入快取(例如 LruCache),取用時先查快取,命中就直接讀、未命中才下載並回填。這樣可以確保圖片佔用的記憶體永遠不超過預設上限。本篇重點不在此,為了示範方便,我直接放了幾張本地圖片進專案充當素材。
伺服器回傳的通常是一段 JSON 陣列,需要先反序列化成實體集合。以下用 Info.java 表示單筆商家資訊:
package com.zhy.zhy_baidu_ditu_demo03;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Info implements Serializable {
private static final long serialVersionUID = -758459502806858414L;
/** 經度 */
private double latitude;
/** 緯度 */
private double longitude;
/** 圖片 ID,真實專案中通常是圖片路徑或 URL */
private int imgId;
/** 商家名稱 */
private String name;
/** 距離描述 */
private 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));
}
public Info() { }
public Info(double latitude, double longitude, int imgId,
String name, String distance, int zan) {
super();
this.latitude = latitude;
this.longitude = longitude;
this.imgId = imgId;
this.name = name;
this.distance = distance;
this.zan = zan;
}
public double getLatitude() { return latitude; }
public void setLatitude(double latitude) { this.latitude = latitude; }
public double getLongitude() { return longitude; }
public void setLongitude(double longitude) { this.longitude = longitude; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getImgId() { return imgId; }
public void setImgId(int imgId) { this.imgId = imgId; }
public String getDistance() { return distance; }
public void setDistance(String distance) { this.distance = distance; }
public int getZan() { return zan; }
public void setZan(int zan) { this.zan = zan; }
}
這裡在實體類中宣告了一個靜態清單,用來模擬伺服器回傳的 Info.infos,實際專案中把這段換成網路請求即可。
為了示範方便,我把各功能入口都放進 Options Menu:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.id_menu_map_addMaker:
addInfosOverlay(Info.infos);
break;
// ... 其他選單項
}
return super.onOptionsItemSelected(item);
}
接著是核心的圖層初始化方法。這裡有兩個關鍵動作值得注意:一是用 MarkerOptions 描述每個標記的位置與圖示,二是透過 Bundle 把商家資料綁到 Marker 上,讓後續點擊時能取回對應資料。
/**
* 初始化圖層
*/
public void addInfosOverlay(List<Info> infos) {
mBaiduMap.clear();
LatLng latLng = null;
OverlayOptions overlayOptions = null;
Marker marker = null;
for (Info info : infos) {
// 座標位置
latLng = new LatLng(info.getLatitude(), info.getLongitude());
// 圖示與堆疊層級
overlayOptions = new MarkerOptions()
.position(latLng)
.icon(mIconMaker)
.zIndex(5);
marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
// 把商家資料掛在 Marker 上,點擊時再取出
Bundle bundle = new Bundle();
bundle.putSerializable("info", info);
marker.setExtraInfo(bundle);
}
// 把視角移動到最後一個座標
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
mBaiduMap.setMapStatus(u);
}
迴圈中逐一加入 Overlay,並在回傳的 Marker 上寫入商家資料。這樣一來,使用者點擊 Marker 時就能拿到對應的資料去組裝詳情畫面。
點擊之後要做兩件事:在地圖上彈出一個小型的 InfoWindow 氣泡,同時把畫面下方的詳情面板顯示出來並填入資料。
// 監聽 Marker 點擊
mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(final Marker marker) {
// 取出 Marker 上附掛的資料
Info info = (Info) marker.getExtraInfo().getSerializable("info");
InfoWindow mInfoWindow;
// 建立氣泡內容(這裡先用 TextView 示意)
TextView location = new TextView(getApplicationContext());
// 注意:先設背景再設 padding,順序顛倒可能導致 padding 失效
location.setBackgroundResource(R.drawable.location_tips);
location.setPadding(30, 20, 30, 50);
location.setText(info.getName());
// 把 Marker 的經緯度換算成螢幕座標,再往上偏移避免遮住圖示
final LatLng ll = marker.getPosition();
Point p = mBaiduMap.getProjection().toScreenLocation(ll);
Log.e(TAG, "-->" + p.x + ", " + p.y);
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;
}
});
這段程式示範了一個實用技巧:由於 Marker 的座標是地理座標,而 InfoWindow 的呈現位置需要避開圖示,因此透過 getProjection() 在經緯度與螢幕座標之間來回換算,做一個 Y 軸偏移,視覺上就自然多了。
詳情面板裡有四個子控制項(圖片、名稱、距離、讚數)。每次點擊都去 findViewById 顯得浪費,這裡用 ViewHolder 模式把查詢結果快取在 tag 上,只執行一次。
/**
* 依 info 為面板控制項填入資料
*/
protected void popupInfo(RelativeLayout mMarkerLy, Info info) {
ViewHolder viewHolder = null;
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.infoDistance.setText(info.getDistance());
viewHolder.infoName.setText(info.getName());
viewHolder.infoZan.setText(info.getZan() + "");
}
/** 複用詳情面板的控制項 */
private class ViewHolder {
ImageView infoImg;
TextView infoName;
TextView infoDistance;
TextView infoZan;
}
詳情面板是浮在地圖之上的覆蓋層,使用者點地圖空白處時理應收起,這個行為要另外掛在地圖本身的點擊監聽上。
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 之外,其餘都是詳情面板的內容,預設隱藏,點擊 Marker 時顯示並填入初值。
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools">
<com.baidu.mapapi.map.MapView
android:clickable="true"
android:id="@+id/id_bmapView"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<RelativeLayout
android:background="#CC4e5a6b"
android:clickable="true"
android:id="@+id/id_marker_info"
android:layout_alignParentBottom="true"
android:layout_height="220dp"
android:layout_width="fill_parent"
android:visibility="gone">
<ImageView
android:alpha="1.0"
android:background="@drawable/map_image_border_white"
android:clickable="true"
android:id="@+id/info_img"
android:layout_height="150dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:src="@drawable/a04">
<RelativeLayout
android:background="@drawable/bg_map_bottom"
android:layout_alignParentBottom="true"
android:layout_height="50dp"
android:layout_width="fill_parent">
<LinearLayout
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/info_name"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="老米家泡饃小炒"
android:textColor="#FFF5EB" />
<TextView
android:id="@+id/info_distance"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="距離200米"
android:textColor="#FFF5EB" />
</LinearLayout>
<LinearLayout
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_width="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="zan"
android:src="@drawable/map_zan" />
<TextView
android:id="@+id/info_zan"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="652"
android:textColor="#FFF5EB" />
</LinearLayout>
</RelativeLayout>
</ImageView>
</RelativeLayout>
</com.baidu.mapapi.map.MapView>
</RelativeLayout>
到這裡,覆蓋物與 InfoWindow 的整套流程就走完了。核心其實只有三件事:把資料掛在 Marker 上、點擊時取出資料、根據資料更新介面。理解了這條主線,之後要擴充成複合標記、聚合顯示或自訂氣泡樣式,都只是在同一個骨架上加肉而已。
帶著疑惑走進 Dagger2:從依賴注入到注解的實戰
Dagger2 最初由 Square 研發,後交由 Google 維護,是一款依賴注入(Dependency Injection,簡稱 DI)框架。它之所以越來越受歡迎,
PagerSlidingTabStrip 極簡接入指南:三步搞定 ViewPager 頂部 Tab
Android 原生的 Tab 控件一直不太好使,所以社群裡 PagerSlidingTabStrip 這個開源方案被廣泛使用。它的官方 demo 代碼偏長,新手往往看得
Android 開發筆記(一百零六):支付繳費 SDK 集成實踐
第三方支付概述 第三方支付指的是第三方平台與各大銀行簽約,在買方與賣方之間充當中介擔保,從而增強交易的安全性。國內常用的支付平台以支付寶和微信支付為主,二者合計佔據了約八
以 Xposed 為例:Android 逆向分析中如何定位 Hook 點
在 Android 的 Hook 工作中,最關鍵也最困難的一步,就是找到合適的 Hook 點。修改系統方法時可以直接查閱原始碼,但若要分析第三方 App,就得先逆向定位。