0

I have gone through all the suggested links and answers and have come to this stage wherein i am able to calculate distance but can not draw route, All i can get is a straight line between the last two points of the kml file here is my code.

Kindly let me know how can I overcome this as i have to draw the complete traveling route from source to destination

Code:

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: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: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: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();
    }
}
Herry
  • 7,037
  • 7
  • 50
  • 80
SAPHIRE
  • 103
  • 1
  • 4
  • 17

1 Answers1

1

1) Don't copy the code blindly from some SO question and paste it back as a wall of code, just because you can't understand it.

2) Parse the KML using a SAX parser to get and ArrayList of Lon, Lat and Alt separated by spaces.

3) Use this snippet. Of course this wont compile, you have to figure out what it does.

if (path != null && path.trim().length() > 0) 
{
    String[] pairs = path.trim().split(" ");

    String[] lngLat = pairs[0].split(","); 

if (lngLat.length < 3)
    lngLat = pairs[1].split(",");

try 
{
    GeoPoint startGP = new GeoPoint( (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

    new MyOverlay(startGP, startGP, 1);


    for (int i = 1; i < pairs.length; i++) 
    {
        lngLat = null;
        lngLat = pairs[i].split(",");
        gp1 = gp2;
        gp2 = new GeoPoint( (int) (Double.parseDouble(lngLat[1]) * 1E6),
        (int) (Double.parseDouble(lngLat[0]) * 1E6));
        new MyOverlay(gp1, gp2, 2, color);

Next time try to make an effort to understand code.

Community
  • 1
  • 1
Reno
  • 33,594
  • 11
  • 89
  • 102