天天看點

android使用者界面-元件Widget-地圖視圖MapView

一、在Google地圖上顯示本地的位置。

1、首先注意在AndroidManifest.xml檔案中,增權重限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

在application中activity外,增加:uses-library

<uses-library android:name="com.google.android.maps" />

2、在類中,将extends Activity改為extends MapActivity

3、設定可放大縮小地圖的控件。

在xml檔案中,添加以下内容:

<LinearLayout android:orientation="vertical" 

android:layout_width="wrap_content" android:layout_height="wrap_content" 

android:id="@+id/zoom" android:layout_alignParentBottom="true" 

android:layout_centerHorizontal="true" > 

</LinearLayout>

在類中,加入:

LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom); 

View zoomView = mapView.getZoomControls(); 

zoomLayout.addView(zoomView, 

new LinearLayout.LayoutParams( 

LayoutParams.WRAP_CONTENT, 

LayoutParams.WRAP_CONTENT)); 

mapView.displayZoomControls(true);

mapView.getController().setZoom(14);//設定縮放級别 

p = this.getCurrentGeoPoint(); 

mapView.getController().animateTo(p);// 通過動畫方式移動到指定坐标s

4、通過以下方法得到目前位置的經緯度

private GeoPoint getCurrentGeoPoint() { 

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

Location location = locationManager 

.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

return new GeoPoint((int) (location.getLatitude() * 1e6), 

(int) (location.getLongitude() * 1e6)); 

}

5、通過以下方式顯示目前位置在地圖上顯示:

class MapOverlay extends com.google.android.maps.Overlay 

@Override 

public boolean draw(Canvas canvas, MapView mapView, 

boolean shadow, long when) 

super.draw(canvas, mapView, shadow); 

//—translate the GeoPoint to screen pixels— 

Point screenPts = new Point(); 

mapView.getProjection().toPixels(p, screenPts); 

//—add the marker— 

Bitmap bmp = BitmapFactory.decodeResource( 

getResources(), R.drawable.pushpin); 

canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null); 

return true; 

在oncreate方法中,加入:

MapOverlay mapOverlay = new MapOverlay(); 

List<Overlay> listOfOverlays = mapView.getOverlays(); 

listOfOverlays.clear(); 

listOfOverlays.add(mapOverlay);

這樣就能在螢幕中顯示你目前位置的地圖顯示了;

如下圖:

二、輸入位址,在地圖上顯示相應的位置。此方法是通過查詢位址名稱,傳回一個list結果。在地圖上顯示:

此方法與上述方法基本一緻,不同之處在于:是用getFromLocationName方法,來查詢目的地的經緯度。

如下代碼:

// 通過系統預設區域設定進行地圖定位 

Geocoder gc = new Geocoder(this); 

mapView.setStreetView(true); 

try { 

// 通過位址名稱描述傳回一個查詢結果的數組(後面參數為傳回最大結果數) 

addresses = gc.getFromLocationName(address, 5);

// 如果未查詢到任何結果 

if (addresses != null) { 

geoPoint = new GeoPoint( 

// 傳回緯度,經度 

(int) (addresses.get(0).getLatitude() * 1E6), 

(int) (addresses.get(0).getLongitude() * 1E6));

setTitle(addresses.get(0).getFeatureName()); 

MyOverlay myOverlay = new MyOverlay(); 

mapView.getOverlays().add(myOverlay); 

mapView.getController().setZoom(16); 

mapView.getController().animateTo(geoPoint); 

} catch (Exception e) { 

e.printStackTrace(); 

如下圖所示:

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080684

繼續閱讀