欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > Android >内容正文

Android

定位 android8.1.0,8.1.2 实现Android定位(2)

发布时间:2024/10/14 Android 59 豆豆
生活随笔 收集整理的这篇文章主要介绍了 定位 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)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。