定位 android8.1.0,8.1.2 实现Android定位(2)
8.1.2? 實現Android定位(2)
(3)實現定位管理器
可以使用Context.getSystemService()方法實現定位管理器功能,并傳入Context.LOCATION_ SERVICE參數來獲取定位管理器。例如下面的代碼。
LocationManagerlm=?(LocationManager)?getSystemService(Context.LOCATION_SERVICE);
接下來將原先的MyGPSActivity做一些修改,讓它實現一個LocationListener接口,使其能夠監聽定位信息的改變。
class?MyGPSActivity?extends?MapActivity?implements?LocationListener?{
…………
public?void?onLocationChanged(Location?location)?{}
public?void?onProviderDisabled(String?provider)?{}
public?void?onProviderEnabled(String?provider)?{}
public?void?onStatusChanged(String?provider,?int?status,?Bundle?extras)?{}
protected?boolean?isRouteDisplayed()?{
return?false;
}
}
接下來初始化LocationManager,并在它的onCreate()方法中注冊定位監聽器。例如下面的代碼。
@Override
public?void?onCreate(Bundle?savedInstanceState)?{
LocationManagerlm=?(LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,?1000L,?500.0f,?this);
}
這樣代碼中的方法onLocationChanged()會在用戶的位置發生500米距離的改變之后進行調用。這里默認使用的LocationProvider是"gps"(GSP_PROVIDER),但是可以根據你的需要,使用特定的Criteria對象調用LocationManger類的getBestProvider方法獲取其他的 LocationProvider。以下代碼是onLocationChanged()方法的參考實現。
public?void?onLocationChanged(Location?location)?{
if?(location?!=?null)?{
doublelat=location.getLatitude();
doublelng=location.getLongitude();
p=newGeoPoint((int)?lat?*?1000000,?(int)?lng?*?1000000);
mc.animateTo(p);
}
通過上面的代碼,獲取了當前的新位置并在地圖上更新位置顯示。還可以為應用程序添加一些諸如縮放效果、地圖標注和文本等功能。
(4)添加縮放控件
//將縮放控件添加到地圖上
ZoomControlszoomControls=??(ZoomControls)?gMapView.getZoomControls();
zoomControls.setLayoutParams(new?ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
gMapView.addView(zoomControls);
gMapView.displayZoomControls(true);
(5)添加Map Overlay
***一步是添加Map Overlay,例如通過下面的代碼可以定義一個overlay。
class?MyLocationOverlay?extends?com.google.android.maps.Overlay?{
public?boolean?draw(Canvas?canvas,?MapView?mapView,?boolean?shadow,?long?when)?{
super.draw(canvas,?mapView,?shadow);
Paintpaint=newPaint();
//?將經緯度轉換成實際屏幕坐標
PointmyScreenCoords=newPoint();
mapView.getProjection().toPixels(p,?myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255,?255,?255,?255);
paint.setStyle(Paint.Style.STROKE);
Bitmapbmp=BitmapFactory.decodeResource(getResources(),?R.drawable.marker);
canvas.drawBitmap(bmp,?myScreenCoords.x,?myScreenCoords.y,?paint);
canvas.drawText(”how?are?you…”,?myScreenCoords.x,?myScreenCoords.y,?paint);
return?true;
}
}
通過上面的Overlay會在地圖上顯示一段文本,接下來可以把這個Overlay添加到地圖上去。
MyLocationOverlaymyLocationOverlay=newMyLocationOverlay();
Listlist=gMapView.getOverlays();
list.add(myLocationOverlay);
【責任編輯:book TEL:(010)68476606】
點贊 0
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的定位 android8.1.0,8.1.2 实现Android定位(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android java广播,[原]An
- 下一篇: eclipse开发android的好处,