Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在谷歌地图上找到两点之间的最佳路线,然后突出显示?_Android_Google Maps_Gps - Fatal编程技术网

Android 如何在谷歌地图上找到两点之间的最佳路线,然后突出显示?

Android 如何在谷歌地图上找到两点之间的最佳路线,然后突出显示?,android,google-maps,gps,Android,Google Maps,Gps,假设我在谷歌地图上有两个地理位置(点),现在我想突出显示这两个点之间通过不同城市的最佳路线。我怎么做?我在网上搜索了一下,发现了,但这解释了在两点之间画一条直线的原因。我需要找到连接不同城市的路线,至少是在两点之间的地方。不是一条直线。有人能给我一些好的指导或一些方法吗 回答:如果其他人也面临同样的问题,请查看已接受的答案。要实现最佳路线,请参阅这是一个具有工作代码的优秀教程。您可以根据需要修改它们。还有一件事,在测试时,请仅给出可能的路径坐标(我犯的错误).其余的都很好。继续写代码。谢谢。检查

假设我在谷歌地图上有两个地理位置(点),现在我想突出显示这两个点之间通过不同城市的最佳路线。我怎么做?我在网上搜索了一下,发现了,但这解释了在两点之间画一条直线的原因。我需要找到连接不同城市的路线,至少是在两点之间的地方。不是一条直线。有人能给我一些好的指导或一些方法吗


回答:如果其他人也面临同样的问题,请查看已接受的答案。要实现最佳路线,请参阅这是一个具有工作代码的优秀教程。您可以根据需要修改它们。还有一件事,在测试时,请仅给出可能的路径坐标(我犯的错误).其余的都很好。继续写代码。谢谢。

检查一下这些代码。根据您的要求修改代码

//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);
}
}
//mapdirection.java
公共类mapdirection扩展了MapActivity{
地图视图;
地图路线覆盖地图覆盖;
语境(Context)语境;;
列表映射列表覆盖;
可拉伸,可拉伸2;
mapoverlay2、mapoverlay3;
地质点;
叠加项;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Picture);
setContentView(R.layout.map\U方向);
注册表活动。注册表活动(此);
mapview=(mapview)this.findViewById(R.id.mapview);
callMap();
}
私有void callMap(){
srcpoint=新的地质点((int)(Data.src_lat_date*1E6),(int)(Data.src_long_Data*1E6));
maplistoverlay=mapview.getOverlays();
drawable=this.getResources().getDrawable(R.drawable.green_a);
mapoverlay2=新的MapOverlay(可绘制);
OverlayItem OverlayItem=新的OverlayItem(srcpoint,“,”);
mapoverlay2.addOverlay(overlayitem);
添加(mapoverlay2);
destpoint=新的地质点((int)(Data.dest_lat_Data*1E6),(int)(Data.dest_long_Data*1E6));
drawable2=this.getResources().getDrawable(R.drawable.green_b);
mapoverlay3=新的MapOverlay(可绘制2);
OverlayItem overlayitem3=新的OverlayItem(destpoint,“,”);
mapoverlay3.addOverlay(overlayitem3);
添加(mapoverlay3);
double dest_lat=Data.dest_lat_Data;
double dest_long=Data.dest_long_Data;
地质点SRCEOPINT=新的地质点((int)(Data.src_lat_date*1E6),
(int)(Data.src_long_Data*1E6));
地质点destGeoPoint=新的地质点((int)(dest_lat*1E6),
(国际)(目的地长*1E6));
绘图路径(srcGeoPoint、destGeoPoint、Color.BLUE、mapview);
mapview.getController().animateTo(srcGeoPoint);
getController().setZoom(13);
//mapview.setStreetView(真);
mapview.SetBuilTinZoomControl(真);
mapview.invalidate();
}
专用空心绘制路径(地质点src、地质点dest、int color、,
地图视图(mMapView01){
//连接到地图web服务
StringBuilder urlString=新的StringBuilder();
urlString.append(“http://maps.google.com/maps?f=d&hl=en");
urlString.append(“&saddr=”);//来自
append(Double.toString((Double)src.getLatitudeE6()/1.0E6));
urlString.append(“,”);
append(Double.toString((Double)src.getLongitudeE6()/1.0E6));
urlString.append(“&daddr=”);//到
append(Double.toString((Double)dest.getLatitudeE6()/1.0E6));
urlString.append(“,”);
append(Double.toString((Double)dest.getLongitudeE6()/1.0E6));
追加(“&ie=UTF8&0&om=0&output=kml”);
Log.d(“xxx”,“URL=“+urlString.toString());
//System.out.println(urlString);
//获取kml(XML)文档,并对其进行解析以获得坐标(方向路线)。
单据单据=空;
HttpURLConnection-urlConnection=null;
URL=null;
尝试
{
url=新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)
{
//字符串路径=doc.getElementsByTagName(“GeometryCollection”).item(0).getFirstChild().getFirstChild().getNodeName();
字符串路径=doc.getElementsByTagName(“GeometryCollection”).item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue();
Log.d(“xxx”,“path=“+path”);
String[]pairs=path.split(“”);
字符串[]lngLat=pairs[0]。拆分(“,”;//lngLat[0]=经度lngLat[1]=纬度lngLat[2]=高度
//src
GeoPoint startGP=新的地质点((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
//mMapView01.getOverlays().add(overlayitem);
地质点gp1;
地质点gp2=startGP;

对于(inti=1;i是的,很长一段时间后我回答这个问题是正确的。但我认为这可以帮助其他任何人

将此代码放入
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();
    }
MapView mv=(MapView)findviewbyd(R.id.mvGoogle);
mv.SetBuiltinzoomControl(真);
MapController mc=mv.getController();
//获取方向(lat1、lon2、lat2、lon2);
ArrayList all_geo_points=getDirections(10.154929,76.390316,10.015861,76.341867);
如果(所有地理点.size()>0){
地理点移动到=所有地理点。获取(0);
动画师(moveTo);;
mc.setZoom(12);
mv.getOverlays().add(新的MyOverlay(所有地理点));
}否则{
Toast.makeText(getApplicationContext(),“无法显示路由!!”,Toast.LENGTH\u 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;
        }
    }
}
公共类MyOverlay扩展覆盖{
私人Arr
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;
}