2011-11-02 111 views
2

假设我在谷歌地图上有两个地理位置(点),现在我想强调这两点之间通过不同城市的最佳路线。我该怎么做?我在互联网上搜索,发现Drawing a line/path on Google Maps,但这解释了在两点之间画一条直线。我需要找到连接不同点的路线,至少是两点之间的点。不是一条直线。任何人都可以给我一些goodd教程或一些想法如何做到这一点?如何在谷歌地图上的两点之间找到最佳路线,然后突出显示它?

回答:如果有其他人遇到同样的问题,请查看接受的答案。要实现最佳路径请参考http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html这是一本很好的工作代码教程,您可以根据自己的需要进行修改。还有一件事,而测试时请只给出那些可能路径的坐标(我在做错误).Rest都很好。请继续提供代码。谢谢。

+0

您是否正在使用Google Maps API来计算路线,或者您是否正在尝试使用某些网络定义来做到这一点? – ViennaMike

回答

1

通过这个代码。修改代码,每UR要求

//mapdirection.java 
public class mapdirection extends MapActivity{ 

MapView mapview; 
MapRouteOverlay mapoverlay; 
Context _context; 
List<Overlay> maplistoverlay; 
Drawable drawable,drawable2; 
MapOverlay mapoverlay2,mapoverlay3; 
GeoPoint srcpoint,destpoint; 
Overlay overlayitem; 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    setContentView(R.layout.map_direction); 
    RegisterActivities.registerActivity(this); 
    mapview=(MapView)this.findViewById(R.id.mapview); 

    callMap(); 
} 
private void callMap() { 
     srcpoint=new GeoPoint((int)(Data.src_lat_date*1E6),(int)(Data.src_long_data*1E6)); 
     maplistoverlay=mapview.getOverlays(); 
     drawable=this.getResources().getDrawable(R.drawable.green_a); 
     mapoverlay2=new MapOverlay(drawable); 
     OverlayItem overlayitem = new OverlayItem(srcpoint, "", ""); 
     mapoverlay2.addOverlay(overlayitem); 
     maplistoverlay.add(mapoverlay2); 

     destpoint=new GeoPoint((int)(Data.dest_lat_data*1E6),(int)(Data.dest_long_data*1E6)); 
     drawable2=this.getResources().getDrawable(R.drawable.green_b); 
     mapoverlay3=new MapOverlay(drawable2); 
     OverlayItem overlayitem3 = new OverlayItem(destpoint, "", ""); 
     mapoverlay3.addOverlay(overlayitem3); 
     maplistoverlay.add(mapoverlay3); 


    double dest_lat = Data.dest_lat_data; 
    double dest_long = Data.dest_long_data; 

    GeoPoint srcGeoPoint = new GeoPoint((int) (Data.src_lat_date* 1E6), 
    (int) (Data.src_long_data * 1E6)); 
    GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6), 
    (int) (dest_long * 1E6)); 

    DrawPath(srcGeoPoint, destGeoPoint, Color.BLUE, mapview); 

    mapview.getController().animateTo(srcGeoPoint); 
    mapview.getController().setZoom(13); 
    //mapview.setStreetView(true); 
    mapview.setBuiltInZoomControls(true); 
    mapview.invalidate(); 


} 
private void DrawPath(GeoPoint src, GeoPoint dest, int color, 
     MapView mMapView01) { 

    // connect to map web service 
    StringBuilder urlString = new StringBuilder(); 
    urlString.append("http://maps.google.com/maps?f=d&hl=en"); 
    urlString.append("&saddr=");//from 
    urlString.append(Double.toString((double)src.getLatitudeE6()/1.0E6)); 
    urlString.append(","); 
    urlString.append(Double.toString((double)src.getLongitudeE6()/1.0E6)); 
    urlString.append("&daddr=");//to 
    urlString.append(Double.toString((double)dest.getLatitudeE6()/1.0E6)); 
    urlString.append(","); 
    urlString.append(Double.toString((double)dest.getLongitudeE6()/1.0E6)); 
    urlString.append("&ie=UTF8&0&om=0&output=kml"); 
    Log.d("xxx","URL="+urlString.toString()); 

    //System.out.println(urlString); 
    // get the kml (XML) doc. And parse it to get the coordinates(direction route). 
    Document doc = null; 
    HttpURLConnection urlConnection= null; 
    URL url = null; 
    try 
    { 
    url = new URL(urlString.toString()); 
    urlConnection=(HttpURLConnection)url.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setDoOutput(true); 
    urlConnection.setDoInput(true); 
    urlConnection.connect(); 

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    doc = db.parse(urlConnection.getInputStream()); 

    if(doc.getElementsByTagName("GeometryCollection").getLength()>0) 
    { 
    //String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName(); 
    String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ; 
    Log.d("xxx","path="+ path); 
    String [] pairs = path.split(" "); 
    String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height 
    // src 
    GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6)); 
    //mMapView01.getOverlays().add(overlayitem); 
    GeoPoint gp1; 
    GeoPoint gp2 = startGP; 
    for(int i=1;i<pairs.length;i++) // the last one would be crash 
    { 
    lngLat = pairs[i].split(","); 
    gp1 = gp2; 
    // watch out! For GeoPoint, first:latitude, second:longitude 
    gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6)); 
    mMapView01.getOverlays().add(new MapRouteOverlay(gp1,gp2,2,color)); 
    Log.d("xxx","pair:" + pairs[i]); 
    } 
    //mMapView01.getOverlays().add(new MapRouteOverlay(dest,dest, 3)); // use the default color 
    } 
    } 
    catch (MalformedURLException e) 
    { 
    e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
    e.printStackTrace(); 
    } 
    catch (ParserConfigurationException e) 
    { 
    e.printStackTrace(); 
    } 
    catch (SAXException e) 
    { 
    e.printStackTrace(); 
    }  
} 
@Override 
protected boolean isRouteDisplayed() { 
    // TODO Auto-generated method stub 
    return false; 
} 
//MapRouteOverlay.java 

public class MapRouteOverlay extends Overlay { 

private GeoPoint gp1; 
private GeoPoint gp2; 

private int mode=0; 
private int defaultColor; 

public MapRouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E) 
{ 
this.gp1 = gp1; 
this.gp2 = gp2; 
this.mode = mode; 
defaultColor = 999; // no defaultColor 

} 

public MapRouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) 
{ 
this.gp1 = gp1; 
this.gp2 = gp2; 
this.mode = mode; 
this.defaultColor = defaultColor; 
} 

public int getMode() 
{ 
return mode; 
} 

public boolean draw 
(Canvas canvas, MapView mapView, boolean shadow, long when) 
{ 
Projection projection = mapView.getProjection(); 
if (shadow == false) 
{ 

Paint paint = new Paint(); 
paint.setAntiAlias(true); 
Point point = new Point(); 
projection.toPixels(gp1, point); 

if(mode==2) 
{ 
if(defaultColor==999) 
paint.setColor(Color.RED); 
else 
paint.setColor(defaultColor); 
Point point2 = new Point(); 
projection.toPixels(gp2, point2); 
paint.setStrokeWidth(5); 
paint.setAlpha(120); 
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint); 
} 
} 
return super.draw(canvas, mapView, shadow, when); 
} 
} 
+0

@ Profete 162:什么是共同发病。即使我在同一时间看相同的代码,你在这里发布它。我想这是原始链接http://csie-tw.blogspot.com /2009/06/android-driving-direction-route-path.html。但我得到这个代码的错误。你能帮我解决这些代码吗?我在mapdirection.java上出现错误:doc = db.parse(urlConnection.getInputStream());你能告诉我什么可能是可能的原因?如果你想我可以发布我的logcat错误,但经过它后,我认为错误来自这一行。此外,我在代理后面,所以我添加了几行: –

+0

System.setProperty(“http.proxyHost”,“my_host” ); \t \t系统。setProperty(“http.proxyPort”,“my_port”); \t \t System.setProperty(“http.proxyUser”,“my_username”); \t \t System.setProperty(“http.proxyPassword”,“My_password”);在openconnection()之前,但无法弄清楚prblem.Please help me。 –

+0

Logcat当然会有很多帮助! –

0
+0

@ Profete 162:您提供的链接解释了使用一些不再可用的谷歌库的路径图。DrivingDirection包(com.google.googlenav.DrivingDirection)自Android SDK 1.1以来被删除。所以我请你提供一些最新的链接,这些链接可以帮助我绘制路径(使用可用的库)。谢谢。 –

+0

我的不好,错误的链接...刚更新我的帖子与http://blog.synyx.de/2010/06/routing-driving-directions-on-android-%E2%80%93-part-2-draw -the-route/ –

1

呀其正确的,我很长一段时间后,回答这个问题,但我认为这可以帮助任何其他。

将此代码放入onCreate或以您自己的方法。

MapView mv = (MapView)findViewById(R.id.mvGoogle); 
    mv.setBuiltInZoomControls(true); 
    MapController mc = mv.getController(); 
    //getDirections(lat1,lon2,lat2,lon2); 
    ArrayList<GeoPoint> all_geo_points = getDirections(10.154929, 76.390316, 10.015861, 76.341867); 
    if(all_geo_points.size()>0){ 
    GeoPoint moveTo = all_geo_points.get(0); 
    mc.animateTo(moveTo); 
    mc.setZoom(12); 
    mv.getOverlays().add(new MyOverlay(all_geo_points)); 
    }else { 
     Toast.makeText(getApplicationContext(), "Not able to show route !!", Toast.LENGTH_LONG).show(); 
    } 

现在制作您自己的自定义覆盖图类。

public class MyOverlay extends Overlay { 
    private ArrayList<GeoPoint> all_geo_points; 

    public MyOverlay(ArrayList<GeoPoint> allGeoPoints) { 
     super(); 
     this.all_geo_points = allGeoPoints; 
    } 

    @Override 
    public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) { 
     super.draw(canvas, mv, shadow); 
     drawPath(mv, canvas); 
     return true; 
    } 

    public void drawPath(MapView mv, Canvas canvas) { 
     int xPrev = -1, yPrev = -1, xNow = -1, yNow = -1; 
     Paint paint = new Paint(); 
     paint.setColor(Color.BLUE); 
     paint.setStyle(Paint.Style.FILL_AND_STROKE); 
     paint.setStrokeWidth(4); 
     paint.setAlpha(100); 
     if (all_geo_points != null) for (int i = 0; i < all_geo_points.size() - 4; i++) { 
      GeoPoint gp = all_geo_points.get(i); 
      Point point = new Point(); 
      mv.getProjection().toPixels(gp, point); 
      xNow = point.x; 
      yNow = point.y; 
      if (xPrev != -1) { 
       canvas.drawLine(xPrev, yPrev, xNow, yNow, paint); 
      } 
      xPrev = xNow; 
      yPrev = yNow; 
     } 
    } 
} 

现在这种方法会给你所有GeoPoints绘制route.I'll更喜欢把这个代码在不同的AsyncTask。

public static ArrayList<GeoPoint> getDirections(double lat1, double lon1, double lat2, double lon2) { 
    String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 
      + "&sensor=false&units=metric"; 
    String tag[] = {"lat", "lng"}; 
    ArrayList<GeoPoint> list_of_geopoints = new ArrayList<GeoPoint>(); 
    HttpResponse response = null; 
    try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpPost httpPost = new HttpPost(url); 
     response = httpClient.execute(httpPost, localContext); 
     InputStream in = response.getEntity().getContent(); 
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = builder.parse(in); 
     if (doc != null) { 
      NodeList nl1, nl2; 
      nl1 = doc.getElementsByTagName(tag[0]); 
      nl2 = doc.getElementsByTagName(tag[1]); 
      if (nl1.getLength() > 0) { 
       list_of_geopoints = new ArrayList<GeoPoint>(); 
       for (int i = 0; i < nl1.getLength(); i++) { 
        Node node1 = nl1.item(i); 
        Node node2 = nl2.item(i); 
        double lat = Double.parseDouble(node1.getTextContent()); 
        double lng = Double.parseDouble(node2.getTextContent()); 
        list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6))); 
       } 
      } else { 
       // No points found 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return list_of_geopoints; 
} 
相关问题