當onLocationChanged()時,我有一個繪製路線的問題。從onLocationChanged更新MapView()
所以我想要做的是: 我有一個pin(基於carOverlayItem)在地圖上和MyLocationOverlay顯示我的當前位置。我想在這兩點之間畫出一條路線。 因此,每當用戶移動時(我們接收到位置並觸發MyLocationOverlay.onLocationChanged()方法),我都會從klm文件中獲取Google的座標,解析它並使用GeoPoint對象填充數組。之後,我試圖通過GeoPoint對象數組進行迭代,並添加疊加與被覆蓋的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變量和intent根據我的理解,這裏不是一種選擇。
此外,可能是,MyLocationOverlay與onLocationChanged()方法在UI線程中運行,這就是爲什麼我不能在地圖上繪製,但在這種情況下,我認爲,我應該得到一個錯誤,這不被拋出。我很困惑,可以找到任何解決方案。
任何幫助,將不勝感激。
謝謝。
您是如何實現GMapRouteHttpRequest類的?請幫助... – scamexdotexe