GPS(Global Positioning System)是全球定位系統,屬於中高度圓形軌道衛星導航系統,能為地球表面絕大部分區域(約 98%)提供可靠的定位、測速與高精度時間基準。
Android 內建了完整的地理定位 API,全部集中在 android.location 套件中。核心類別如下:
LocationManager:進入定位服務的總入口,負責取得最佳定位提供者,也能實現臨時警報功能。
LocationProvider:定位提供者的抽象類別,具備週期性回報裝置地理位置的能力。
LocationListener:定位資訊變動時的回呼介面,必須先向 LocationManager 註冊。
Criteria:讓應用依條件(精度、耗電、是否需要海拔與方位)篩選合適的提供者。
Geocoder:處理地理編碼與反向地理編碼。地理編碼把地址轉為經緯度,反向地理編碼把經緯度轉為地址描述,getFromLocation 會回傳一組 Address。
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
接著註冊週期性更新:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
四個參數分別是提供者、更新間隔(毫秒)、最小位移,以及監聽器。LocationListener 需要實作四個方法:
onLocationChanged(Location location):座標改變時觸發;若提供者回報相同座標則不會觸發。
onProviderDisabled(String provider):提供者被停用時觸發,例如 GPS 被關閉。
onProviderEnabled(String provider):提供者被啟用時觸發。
onStatusChanged(String provider, int status, Bundle extras):提供者在可用、暫時不可用、無服務三種狀態間切換時觸發。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps" />
要使用 MapView 就必須引入 com.google.android.maps 這個函式庫,並讓 Activity 繼承 MapActivity。
模擬器沒有真實 GPS,必須手動餵座標,有兩種方式。一是用 DDMS:在 Eclipse 中開啟 Window → Show View → Emulator Control,手動輸入或匯入 KML/GPX 檔。二是用 telnet 連到本機 5554 埠,下達 geo fix 指令:
geo fix -121.45365 46.51119 4392
三個參數依序為經度、緯度與(選填的)海拔。設定後模擬器畫面上會出現一個定位標記。
package cn.edu.pku;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
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 android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class GPSActivity extends MapActivity {
public MapController mapController;
public MyLocationOverlay myPosition;
public MapView myMapView;
public static final int ZOOM_IN = Menu.FIRST;
public static final int ZOOM_OUT = Menu.FIRST + 1;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
myMapView = (MapView)findViewById(R.id.mapView1);
mapController = myMapView.getController();
myMapView.setSatellite(true); // 衛星模式
myMapView.setStreetView(true);
myMapView.displayZoomControls(false); // 改用自製縮放選單
mapController.setZoom(17);
myPosition = new MyLocationOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(myPosition);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 3000, 0, locationListener);
}
private void updateWithNewLocation(Location location){
String latLongString;
TextView myLocationText = (TextView)findViewById(R.id.textView1);
String addressString = "沒有找到地址\n";
if(location != null){
Double geoLat = location.getLatitude() * 1E6;
Double geoLng = location.getLongitude() * 1E6;
GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
mapController.animateTo(point);
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "經度:" + lat + "\n緯度:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try{
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size() > 0){
Address address = addresses.get(0);
for(int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
addressString = sb.toString();
}
}
}catch(IOException e){}
}else{
latLongString = "沒有找到坐標.\n";
}
myLocationText.setText("你當前的坐標如下:\n" + latLongString + "\n" + addressString);
}
private final LocationListener locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
};
protected boolean isRouteDisplayed() { return false; }
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case ZOOM_IN:
mapController.zoomIn();
return true;
case ZOOM_OUT:
mapController.zoomOut();
return true;
}
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, ZOOM_IN, Menu.NONE, "放大");
menu.add(0, ZOOM_OUT, Menu.NONE, "縮小");
return true;
}
class MyLocationOverlay extends Overlay{
Location mLocation;
public void setLocation(Location location){ mLocation = location; }
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow, when);
Paint paint = new Paint();
Point myScreenCoords = new Point();
GeoPoint tmpGeoPoint = new GeoPoint((int)(mLocation.getLatitude() * 1E6),
(int)(mLocation.getLongitude() * 1E6));
mapView.getProjection().toPixels(tmpGeoPoint, myScreenCoords);
paint.setARGB(255, 255, 0, 0);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home);
canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
return true;
}
}
}
Location 常常拿到 null。查了許多資料後發現,主因是 getBestProvider 挑中的提供者當下並沒有可用的定位資料。若用 while 迴圈硬等,很可能等很久都取不到。我最後改用的折衷做法是遍歷所有提供者,挑第一個有快照的:
String provider = locationManager.getBestProvider(criteria, true);
List<String> privatelist = locationManager.getAllProviders();
for(String privates : privatelist)
{
Location locat = locationManager.getLastKnownLocation(privates);
if(locat != null)
{
provider = privates;
break;
}
}
Location location = locationManager.getLastKnownLocation(provider);
這不是最優雅的解法,但足以讓程式跑出效果。更完整的做法應該是在 onProviderDisabled 中回退到下一個提供者,並對 Geocoder 加上逾時與快取處理,因為反向地理編碼在無網路時經常拋出 IOException。