編輯:關於 Android 程式設計
要在地圖上畫出一條路徑,Android 的傳統做法是自己寫一個 Overlay。原理不複雜:把地理座標換算成螢幕座標,串成一條 Path,再用 Canvas 畫上去。
MapView 本身只負責顯示地圖磚,任何額外的標記、線段、圖層都是「覆蓋物」。Android 的 com.google.android.maps.Overlay 就是這個概念的類別,想畫什麼就繼承它並覆寫 draw() 方法,再把物件加入 mapView.getOverlays()。
package net.blogjava.mobile.map;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class Main extends MapActivity {
private GeoPoint gpoint1, gpoint2, gpoint3;
private MapView mapView;
private MapController mapController;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapView.setTraffic(true);
// 加入自定義 Overlay
mapView.getOverlays().add(new MyOverlay());
mapController.setZoom(15);
// GeoPoint 的經緯度必須乘以 1E6 轉為整數微度
gpoint1 = new GeoPoint((int) (24.477384 * 1E6), (int) (118.158216 * 1E6));
gpoint2 = new GeoPoint((int) (24.488967 * 1E6), (int) (118.144277 * 1E6));
gpoint3 = new GeoPoint((int) (24.491091 * 1E6), (int) (118.136781 * 1E6));
mapController.animateTo(gpoint1);
}
@Override
protected boolean isRouteDisplayed() {
// 回傳 false 可避免地圖顯示「非步行路線」的提示對話框
return false;
}
class MyOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
// 地理座標 → 螢幕像素座標
Projection projection = mapView.getProjection();
Point p1 = new Point();
Point p2 = new Point();
Point p3 = new Point();
projection.toPixels(gpoint1, p1);
projection.toPixels(gpoint2, p2);
projection.toPixels(gpoint3, p3);
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
canvas.drawPath(path, paint);
}
}
}
對應的 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="你的API Key" />
</LinearLayout>
權限別忘了補上,同時要在 application 標籤內宣告使用 maps 函式庫:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application>
<uses-library android:name="com.google.android.maps" />
</application>
做法一只適合「把幾個點連起來」的示意圖,線段是直線,不會沿著道路走。要畫出真正可導航的路線,得向 Google Directions 服務索取路線資料,它會回傳一段名為 overview_polyline 的編碼字串,解碼後就是沿著道路的座標序列。
/** 解析 Directions 回傳的 XML,在圖上畫出實際路線 */
public void drawRoute() {
String url = "https://maps.google.com/maps/api/directions/xml?origin=23.055291,113.391802"
+ "&destination=23.046604,113.397510&sensor=false&mode=walking";
String strResult = "";
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
if (httpResponse.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
return;
}
if (-1 == strResult.indexOf("<status>OK</status>")) {
Toast.makeText(this, "獲取導航路線失敗!", Toast.LENGTH_SHORT).show();
this.finish();
return;
}
// 取出 overview_polyline 中的 points 區段
int pos = strResult.indexOf("<overview_polyline>");
pos = strResult.indexOf("<points>", pos + 1);
int pos2 = strResult.indexOf("</points>", pos);
strResult = strResult.substring(pos + 8, pos2);
List<GeoPoint> points = decodePoly(strResult);
MyOverLay mOverlay = new MyOverLay(points);
List<Overlay> overlays = mMapView.getOverlays();
overlays.add(mOverlay);
if (points.size() >= 2) {
mMapController.animateTo(points.get(0));
}
mMapView.invalidate();
}
/** 解碼 polyline 編碼:每個座標以可列印 ASCII 字元壓縮,需依序還原 */
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
MyOverLay 的寫法與前面類似,只是把 Path 換成遍歷 points 清單連續 lineTo。polyline 的解碼邏輯值得說明:每個座標值先乘以 1E5 取整數,再用「取後 5 個 bit、若還沒結束就設第 6 個 bit」的方式切成多個字元,每個字元減 63 後還原。這是一種把二進位資料塞進可列印字元的壓縮手法,能大幅縮短 URL 長度。
上述 com.google.android.maps 是 Google Maps Android API v1,早已停止服務,且 Directions API 現已改為需要 API Key 並綁定計費帳戶,舊的無認證 HTTP 端點不再可用。這份程式碼的價值在於理解原理,新專案請改用:
SupportMapFragment 搭配 PolylineOptions 畫線,或用 GroundOverlay 貼圖。Polyline 繪製介面,比自己解析資料輕鬆得多。另外,所有網路請求都必須放在背景執行緒;在 onCreate 或主執行緒直接呼叫 HttpClient 會拋出 NetworkOnMainThreadException。
Android 圖片三級緩存策略詳解(網絡、本地、內存)
一、簡介 如今的 Android 應用幾乎離不開圖片,而每加載一張圖就重新從網絡拉取,不僅浪費用戶流量,加載速度也慢,體驗自然大打折扣。因此,一套合理的圖片緩存策略對應用
Android 中 JSON 的封裝與解析實戰
JSON 定義: JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。它基於 JavaScript(Standard ECMA-2
小豬的 Android 入門之路 Day 7 part 4:ContentProvider 內容提供者
轉載請註明出處:coder-pig 本節引言 在前面的學習中,我們已經接觸過一些存儲數據的方式,而這些方式大多是可以共享的。比如文件,我們可以把操作模式設置為 Conte
Android 4.1 移植開發中踩過的四個坑與解法
在 Android 4.1 上手機開發的過程中,累積了幾個比較典型的問題,這裡一併記錄。 問題一:只 push odex 到手機,程式無法運行 解法:修改 dalvik