在 onLocationChanged() 时绘制路线时遇到问题。
所以我要做的是:我在地图上有一个图钉(基于 carOverlayItem),MyLocationOverlay 显示了我当前的位置。我想在这两点之间画一条路线。因此,每次当用户移动时(我们接收到位置并触发 MyLocationOverlay.onLocationChanged() 方法),我都会在 klm 文件中从 Google 获取坐标,对其进行解析并用 GeoPoint 对象填充数组。在我尝试遍历该 GeoPoint 数组并将使用 Overwritten draw() 方法添加到 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 变量和意图不是一个选项。
另外,可能是带有 onLocationChanged() 方法的 MyLocationOverlay 不是在 UI 线程中运行的,这就是我无法在地图上绘制的原因,但在这种情况下,我认为我应该得到一个错误,它不会被抛出。我很困惑,可以找到任何解决方案。
任何帮助,将不胜感激。
谢谢。