我正在尝试构建一个GPS应用程序,可以显示2个地方之间的方向。为了解码折线,我使用的是以下代码: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;
}
}
}
}
}
答案 0 :(得分:1)
请参阅此link以在您的应用程序中绘制驾驶路径。您只需要在项目的链接中添加四个类,并在需要显示路径时调用以下行。
SharedData data = SharedData.getInstance();
data.setAPIKEY("0RUTLH7cqd6yrZ0FdS0NfQMO3lioiCbnH-BpNQQ");//set your map key here
data.setSrc_lat(17);//set your src lat
data.setSrc_lng(78);//set your src lng
data.setDest_lat(18);//set your dest lat
data.setDest_lng(77);//set your dest lng
startActivity(new Intent(YourActivity.this,RoutePath.class));//add RoutePath in your manifeast file
//同时将权限添加到您的表现文件
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>