在谷歌地图,android上绘制路线

时间:2011-02-23 10:00:51

标签: android

嘿,我正在尝试将此代码连接到Google地图,方法是将源和目标坐标传递到此URL并接收KML文件。但是,我无法解析或连接到此URL。

有人能看到我出错的地方吗?

public class RoutePath extends MapActivity {
    MapView mapView;
    GeoPoint gp1,gp2;
    MapController mc;

    public class MyOverLay extends Overlay {
        private int mRadius=6;
        private int mode=0;
        private int defaultColor;
        private String text="";
        private Bitmap img = null;

        public MyOverLay() {
        }

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

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

        public void setText(String t) {
            this.text = t;
        }

        public void setBitmap(Bitmap bitmap) {
            this.img = bitmap;
        }

        public int getMode() {
            return mode;
        }

        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);   
            Point screenPts = new Point();
            mapView.getProjection().toPixels(gp1, screenPts);
            Bitmap bmp = BitmapFactory.decodeResource(
            getResources(), R.drawable.pushpin);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null); 
            return true;
        }

        public boolean onTouchEvent(MotionEvent event, MapView mapView) {
            // when user lifts his finger 
            if (event.getAction() == 1) {
                Toast.makeText(getBaseContext(),"Distance", Toast.LENGTH_SHORT).show(); 
                GeoPoint gp2 = mapView.getProjection().fromPixels(
                (int) event.getX(),
                (int) event.getY());

                Toast.makeText(getBaseContext(), gp2.getLatitudeE6() / 1E6 + "," + gp2.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show();

                double src_lat = 19.0552; // the testing source
                double src_long =  72.8308;
                //double dest_lat = 19.0800; // the testing destination
                //double dest_long = 72.8545;
                double dest_lat = gp2.getLatitudeE6()  / 1E6; // the testing destination
                double dest_long = gp2.getLongitudeE6() /1E6;
                GeoPoint gp1 = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
                DrawPath(gp1, gp2, Color.GREEN, mapView);
            }
            return true;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MapView mapView = (MapView) findViewById(R.id.myMapView1);
        LinearLayout zoom = (LinearLayout)findViewById(R.id.myMapView);  
        View zoomView = mapView.getZoomControls();

        double src_lat = 19.0552; // the testing source
        double src_long =  72.8308;
        gp1 = new GeoPoint(
        (int) (src_lat * 1E6), 
        (int) (src_long * 1E6));

        MyOverLay mapOverlay = new MyOverLay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);
        mapView.invalidate();
        mc = mapView.getController();
        mc.animateTo(gp1);
        mc.setZoom(17); 
        mapView.invalidate();

        mapView.getController().animateTo(gp1);
        mapView.getController().setZoom(15);
    }

    private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01) {
        //Toast.makeText(getBaseContext(),"Drawpath initialized", Toast.LENGTH_SHORT).show(); 
        // 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");
        //Toast.makeText(getBaseContext(),urlString, Toast.LENGTH_LONG).show(); 
        Log.d("xxx","URL="+urlString.toString());
        // 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);
            //Toast.makeText(getBaseContext(),"connected", Toast.LENGTH_SHORT).show();
            urlConnection.connect(); 
            //Toast.makeText(getBaseContext(),"connected", Toast.LENGTH_SHORT).show(); 
            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(new MyOverLay(startGP,startGP,1));
                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 MyOverLay(gp1,gp2,2,color));
                    Log.d("xxx","pair:" + pairs[i]);
                }
                mMapView01.getOverlays().add(new MyOverLay(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 true;
    }
}

我已经完成了所有建议的链接n答案并且已经到了这个阶段,我能够计算距离但不能绘制路线,我所能得到的是kml文件的最后两点之间的直线 这是我的代码.....亲切的知道我怎么能克服这一点,因为我必须绘制从源头到目的地的完整旅行路线。

public class RoutePath extends MapActivity {
GeoPoint gp1;
GeoPoint gp2;
GeoPoint srcGeoPoint;
GeoPoint destGeoPoint;
double distance;

public class MyOverLay extends com.google.android.maps.Overlay
{

    private int mRadius=6;
    private int mode=0;
    private int defaultColor;
    public MyOverLay()
    {

    }

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

    public MyOverLay(GeoPoint p1,GeoPoint p2,int mode, int defaultColor)
    {
        gp1 = p1;
        gp2 = p2;
        this.mode = mode;
        this.defaultColor = defaultColor ;

    }

    public int getMode()
    {
        return mode;
    }

    @Override
    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);
            // mode=1&#65306;start
            if(mode==1)
            {
                if(defaultColor==999)
                    paint.setColor(Color.RED);
                //Toast.makeText(getBaseContext(), "mode1", Toast.LENGTH_SHORT).show();
                else
                    paint.setColor(defaultColor);
                RectF oval=new RectF(point.x - mRadius, point.y - mRadius,point.x + mRadius, point.y + mRadius);
                // start point
                canvas.drawOval(oval, paint);

            }
            // mode=2&#65306;path
            if(mode==2)
            {
                if(defaultColor==999)
                    paint.setColor(Color.RED);
                //Toast.makeText(getBaseContext(), "mode2", Toast.LENGTH_SHORT).show();
                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);

            }
            /* mode=3&#65306;end */
            else if(mode==3)
            {
                //the last path 

                if(defaultColor==999)
                    {paint.setColor(Color.BLUE);
                Toast.makeText(getBaseContext(), "mode3", Toast.LENGTH_SHORT).show();}
                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);
                RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,point2.x + mRadius,point2.y + mRadius);                      
                paint.setAlpha(255);
                canvas.drawOval(oval, paint);

            }
        }

        return super.draw(canvas, mapView, shadow, when);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView) 
    {   
        //---when user lifts his finger---
        if (event.getAction() == 1)
        {                
            GeoPoint destGeoPoint = mapView.getProjection().fromPixels(
                (int) event.getX(),
                (int) event.getY());

            Toast.makeText(getBaseContext(), 
                    destGeoPoint.getLatitudeE6() / 1E6 + "," + 
                    destGeoPoint.getLongitudeE6() /1E6 , 
                    Toast.LENGTH_SHORT).show();


           double src_lat = 19.0552; // the testing source
            double src_long =  72.8308;

            double dest_lat = destGeoPoint.getLatitudeE6()  / 1E6; // the testing destination
            double dest_long = destGeoPoint.getLongitudeE6() /1E6;
            gp1 = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
            gp2 = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));

            Geocoder geoCoder = new Geocoder(
                    getBaseContext(), Locale.getDefault());
                try {
                    List<Address> addresses = geoCoder.getFromLocation(
                        gp2.getLatitudeE6()  / 1E6, 
                        gp2.getLongitudeE6() / 1E6, 1);

                    String add = "";
                    if (addresses.size() > 0) 
                    {
                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                             i++)
                           add += addresses.get(0).getAddressLine(i) + "\n";
                    }

                    Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();

                   DrawPath(gp1, gp2 , Color.GREEN, mapView); 
                }
                catch (IOException e) {                
                    e.printStackTrace();
                }   
                return true;
        }
        else                          
                return false;
    }  




}




/** Called when the activity is first created. */

MapView mapView;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MapView mapView = (MapView) findViewById(R.id.myMapView1);
    mapView.setBuiltInZoomControls(true);
    double src_lat = 19.0552; // the testing source
    double src_long =  72.8308;

    gp1 = new GeoPoint(
            (int) (src_lat * 1E6), 
            (int) (src_long * 1E6));

    MyOverLay mapOverlay = new MyOverLay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);

    mapView.invalidate();
    mapView.setSatellite(true);

    mapView.getController().animateTo(gp1);
    mapView.getController().setZoom(15);

}

@Override
protected boolean isRouteDisplayed() 
{
// TODO Auto-generated method stub
    return true;
}



private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
{
    double distance1=0;
    // 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());
    // 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);
        // Toast.makeText(getBaseContext(), "Before Connection", Toast.LENGTH_SHORT).show();
        urlConnection.connect(); 
        // Toast.makeText(getBaseContext(), "After Connection", Toast.LENGTH_SHORT).show();

        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().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(new MyOverLay(src,src,1));
            GeoPoint gp1;
            GeoPoint gp2 = startGP;



            //Toast.makeText(getBaseContext(), "Before Connection", Toast.LENGTH_SHORT).show();
            for(int i=1;i<pairs.length;i++) // the last one would be crash
            {
                Location locationA = new Location("Point A");
                locationA.setLatitude(startGP.getLatitudeE6()/1E6);
                locationA.setLongitude(startGP.getLongitudeE6()/1E6);

                lngLat = pairs[i].split(",");
                gp1 = gp2;

                gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
                mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));


                mMapView01.invalidate();
                Location locationB = new Location("Point B");
                locationB.setLatitude(gp2.getLatitudeE6()/1E6);
                locationB.setLongitude(gp2.getLongitudeE6()/1E6);

               distance1 = + locationA.distanceTo(locationB);

                Log.d("xxx","pair:" + pairs[i]);

            }


            distance = distance1/1000;
            if(distance<= 5.00)
            {Toast.makeText(getBaseContext(), "DISTANCE = "+ distance, Toast.LENGTH_SHORT).show();}
            else
            {Toast.makeText(getBaseContext(), "Location out of range",Toast.LENGTH_SHORT).show();}
        } 
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (ParserConfigurationException e)
    {
        e.printStackTrace();
    }
    catch (SAXException e)
    {
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:3)

你必须查看以下帖子可能解决你的问题

http://www.anddev.org/the_friend_finder_-_mapactivity_using_gps_-_part_i_-_ii-t93.html

修改: J2ME/Android/BlackBerry - driving directions, route between two locations

这是非常具有描述性的帖子,解决了您的问题,尝试解决方案发布在那里