我正在尝试构建一个 GPS 应用程序,它可以显示两个地方之间的方向。为了解码折线,我使用了这里的代码:Decoding Polylines from Google Maps Direction API with Java。我想比这更准确地显示我的路线,我可以通过 kml 做到这一点,但它仅在文件大小达到限制之后才适用于非常小的距离。这是波士顿-西雅图的屏幕截图,其中地图上的线条不沿着道路而是与道路相交
这是我使用方向 API 的方式
public void drawRoute(String source, String destination)
{
String strURL = "http://maps.google.com/maps/api/directions/xml?origin=" + source +
"&destination=" + destination + "&sensor=false&mode=driving";
String url = strURL.replace(" ", "%20");
HttpGet get = new HttpGet(url);
String strResult = "";
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
httpResponse = httpClient.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == 200){
strResult = EntityUtils.toString(httpResponse.getEntity());
}
}
catch (Exception e){ }
if (-1 == strResult.indexOf("<status>OK</status>")){
this.finish();
return;
}
int pos = strResult.indexOf("<overview_polyline>");
pos = strResult.indexOf("<points>", pos + 1);
int pos2 = strResult.indexOf("</points>", pos);
strResult = strResult.substring(pos + 8, pos2);
List<GeoPoint> points = decodePoly(strResult);
RouteOverlay mOverlay = new RouteOverlay(points);
overlayList.add(mOverlay);
if (points.size() >= 2){
controller.animateTo(points.get(0));
}
map.invalidate();
}
这是我的 RouteOverlay 课程:
public class RouteOverlay extends Overlay{
private List<GeoPoint> points;
private Paint paint;
public RouteOverlay(List<GeoPoint> points) {
this.points = points;
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAlpha(150);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4);
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
if (!shadow)
{
Projection projection = mapView.getProjection();
if (points != null && points.size() >= 2)
{
Point start = new Point();
projection.toPixels(points.get(0), start);
for (int i = 1; i < points.size(); i++)
{
Point end = new Point();
projection.toPixels(points.get(i), end);
canvas.drawLine(start.x, start.y, end.x, end.y, paint);
start = end;
}
}
}
}
}