我在 onLocationChanged() 时绘制路线时遇到问题。
所以我想做的是: 我在 map 上有一个图钉(基于 carOverlayItem),MyLocationOverlay 显示我的当前位置。我想在这两点之间画一条路线。 因此,每次当用户移动时(我们收到位置信息并触发 MyLocationOverlay.onLocationChanged() 方法),我都会在 klm 文件中从 Google 获取坐标,解析它并用 GeoPoint 对象填充一个数组。在我尝试遍历该 GeoPoint 数组并使用 Overwritten draw() 方法将 Overlays 添加到 MapView 之后
public class GMapMyLocationOverlay extends MyLocationOverlay {
private MapView mapView;
private CarOverlayItem carOverlayItem = null;
private GeoPoint routeNodes[];
public GMapMyLocationOverlay(Context context, MapView mapView, CarOverlayItem carOverlayItem) {
super(context, mapView);
this.mapView = mapView;
this.carOverlayItem = carOverlayItem;
}
@Override
public void onLocationChanged(Location location) {
// redraw route to the car point
if (!carOverlayItem.isEmpty()) {
GeoPoint fromLocation = new GeoPoint((int)(location.getLatitude() * 1e6), (int)(location.getLongitude() * 1e6));
GMapRouteHttpRequest pointsRequest = new GMapRouteHttpRequest(fromLocation, carOverlayItem.getOverlayItem().getPoint());
routeNodes = pointsRequest.getRoutePoints();
// if the point is not set to be on the road, google can return empty points array
// in this case we will be drawing straight line between car position and current
// user's position on map
if (routeNodes != null && routeNodes.length > 0) {
for (int i = 1; i < routeNodes.length; i ++) {
mapView.getOverlays().add(new GMapRouteOverlay(routeNodes[i-1], routeNodes[i]));
}
}
}
super.onLocationChanged(location);
}
}
这是我的 GMapRouteOverlay 类
public class GMapRouteOverlay extends Overlay {
private GeoPoint fromPoint;
private GeoPoint toPoint;
public GMapRouteOverlay(GeoPoint fromPoint, GeoPoint toPoint) {
this.fromPoint = fromPoint;
this.toPoint = toPoint;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Projection projection = mapView.getProjection();
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
paint.setAntiAlias(true);
Point from = new Point();
projection.toPixels(fromPoint, from);
Point to = new Point();
projection.toPixels(toPoint, to);
Path path = new Path();
path.moveTo(from.x, from.y);
path.lineTo(to.x, to.y);
canvas.drawPath(path, paint);
super.draw(canvas, mapView, shadow);
}
}
我已经阅读了一些互联网并提出了我需要在 onLocationChanged() 时填充 routeNodes 变量然后调用 mapView.invalidate() 以在 onDraw() MapView 方法中绘制路线的想法,但遇到了一个问题,我不知道如何传输 routeNodes 变量,据我所知,这里的 intents 不是一个选项。
另外,可能是带有 onLocationChanged() 方法的 MyLocationOverlay 在非 UI 线程中运行,这就是我无法在 map 上绘制的原因,但在这种情况下,我认为我应该得到一个错误,这是没有扔。我很困惑,可以找到任何解决方案。
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
在 UI 线程上使用网络数据时要小心,这在 android 4.0 及更高版本中不起作用。
你需要使用AsyncTask
关于android - 从 onLocationChanged() 更新 MapView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7400191/