如何更改谷歌地图中 MyLocationOverlay 的默认蓝色动画标记?
2 回答
谢谢@CommonsWare,你把我引向了正确的方向。花了相当多的时间玩弄这个。http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/MyLocationOverlay.html上的 Javadoc是错误的(或过时的),并且会混淆您的大脑说:
drawMyLocation
此外,如果用户的位置移动到屏幕边缘附近,并且我们在构造函数中获得了 MapController,我们将滚动以使新读数居中。
这是完全错误的。首先,类中没有这样的构造函数。其次,drawMyLocation 仅在当前位置在视界内或屏幕移动时才被调用。因此,如果您收到一个新位置并且此时您没有看到该标记,则它不会被重绘。一般来说,这是一件好事,但如果您想在方法中实现 mc.animateTo 以保持位置居中,则这是一件坏事。
第三,您不需要传递 MapController 来启用 currentLocation,因为您已经拥有 mapView 并从中获取控制器。
所以我最终编写了我自己的类,一旦位置到达 mapView 的边界或不在屏幕上,它就会一直以当前位置为中心:
public class CurrentLocationOverlay extends MyLocationOverlay {
// TODO: use dynamic calculation?
private final static int PADDING_ACTIVE_ZOOM = 50;
private MapController mc;
private Bitmap marker;
private Point currentPoint = new Point();
private boolean centerOnCurrentLocation = true;
private int height;
private int width;
/**
* By default this CurrentLocationOverlay will center on the current location, if the currentLocation is near the
* edge, or off the screen. To dynamically enable/disable this, use {@link #setCenterOnCurrentLocation(boolean)}.
*
* @param context
* @param mapView
*/
public CurrentLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
this.mc = mapView.getController();
this.marker = BitmapFactory.decodeResource(context.getResources(), R.drawable.position);
}
@Override
protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {
// TODO: find a better way to get height/width once the mapView is layed out correctly
if (this.height == 0) {
this.height = mapView.getHeight();
this.width = mapView.getWidth();
}
mapView.getProjection().toPixels(myLocation, currentPoint);
canvas.drawBitmap(marker, currentPoint.x, currentPoint.y - 40, null);
}
@Override
public synchronized void onLocationChanged(Location location) {
super.onLocationChanged(location);
// only move to new position if enabled and we are in an border-area
if (mc != null && centerOnCurrentLocation && inZoomActiveArea(currentPoint)) {
mc.animateTo(getMyLocation());
}
}
private boolean inZoomActiveArea(Point currentPoint) {
if ((currentPoint.x > PADDING_ACTIVE_ZOOM && currentPoint.x < width - PADDING_ACTIVE_ZOOM)
&& (currentPoint.y > PADDING_ACTIVE_ZOOM && currentPoint.y < height - PADDING_ACTIVE_ZOOM)) {
return false;
}
return true;
}
public void setCenterOnCurrentLocation(boolean centerOnCurrentLocation) {
this.centerOnCurrentLocation = centerOnCurrentLocation;
}
}
第 1 步:创建MyLocationOverlay
.
步骤#2:覆盖drawMyLocation()
并绘制你喜欢的标记。请记住,此方法不仅绘制标记,而且“如果用户的位置移动到屏幕边缘附近,并且我们MapController
在构造函数中得到了 a,我们将滚动以重新定位新读数”。