Prayaim
Prayaim

Reputation: 19

Find route from one place to another place in Google map in android?

When I run this code, it shows error. Please, help me out. I'm trying to find route from one place to another in Google map in android operating system.

I've submitted all my code. I think I don't need to submit my xml code of layout. Let's say, it's simply map view.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screenfive);
    coder = new Geocoder(this);
    EditText startedit =(EditText) findViewById(R.id.startedit);
    EditText finishedit =(EditText) findViewById(R.id.finishedit);
    Button go=(Button) findViewById(R.id.go);
    Spinner spinnercategory = (Spinner) findViewById (R.id.spinnercategory);
    Category =(TextView) findViewById(R.id.category);


    mapView = (MapView) findViewById(R.id.mymapview2);
    mapView.setBuiltInZoomControls(true);
    mMapController = mapView.getController();
    //          mMapController.setZoom(18);
    // Two points in Mexico about 1km apart

            //Take any two points

    GeoPoint point1 = new GeoPoint(19240000,-99120000);
    GeoPoint point2 = new GeoPoint(19241000,-99121000);

    mMapController.setCenter(point2);
    // Pass the geopoints to the overlay class
    mapOvlay = new MapOverlay(point1, point2);
    mapView.getOverlays().add(mapOvlay);
    spinnercategory.setOnItemSelectedListener(this);

    ArrayAdapter aa=new ArrayAdapter(this, android.R.layout.simple_spinner_item,category);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnercategory.setAdapter(aa);
    go.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            new GetLatLong().execute();


        }
    });

}

public void onItemSelected(AdapterView<?> parent, View v, int position,
        long id) {
    //          Category.setText(category[position]);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}
public class MapOverlay extends com.google.android.maps.Overlay {

    private GeoPoint mGpt1;
    private GeoPoint mGpt2;

    protected MapOverlay(GeoPoint gp1, GeoPoint gp2 ) {
        mGpt1 = gp1;
        mGpt2 = gp2;
    }
    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
            long when) {
        super.draw(canvas, mapView, shadow);
        Paint paint;
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setAntiAlias(true);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        Point pt1 = new Point();
        Point pt2 = new Point();
        Projection projection = mapView.getProjection();
        projection.toPixels(mGpt1, pt1);
        projection.toPixels(mGpt2, pt2);
        canvas.drawLine(pt1.x, pt1.y, pt2.x, pt2.y, paint);
        return true;
    }


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


class GetLatLong extends AsyncTask<String, Void, String>
{


protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    ProgressDialog=new ProgressDialog(MapActivityForScreen5.this);
    ProgressDialog.setTitle("Loading");
    ProgressDialog.show();
}

    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try{
            addressgone = coder.getFromLocationName(startedit.getText().toString(),5);
            if (addressgone == null) {

            }
            Address locationgone = addressgone.get(0);
            locationgone.getLatitude();
            locationgone.getLongitude();

            pone = new GeoPoint((int) (locationgone.getLatitude() * 1E6),
                    (int) (locationgone.getLongitude() * 1E6));
        }
        catch(Exception e)
        {

        }

        try{
            addressgtwo = coder.getFromLocationName(startedit.getText().toString(),5);
            if (addressgtwo == null) {

            }
            Address locationgtwo = addressgtwo.get(0);
            locationgtwo.getLatitude();
            locationgtwo.getLongitude();

            ptwo = new GeoPoint((int) (locationgtwo.getLatitude() * 1E6),
                    (int) (locationgtwo.getLongitude() * 1E6));
        }
        catch(Exception e)
        {

        }

        return null;
    }
    @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            ProgressDialog.cancel();

            mMapController.setCenter(ptwo);
            // Pass the geopoints to the overlay class
            mapOvlay = new MapOverlay(pone, ptwo);
            mapView.getOverlays().add(mapOvlay);
        }
}

}

Upvotes: 0

Views: 2400

Answers (2)

Prayaim
Prayaim

Reputation: 19

Finally I did it. I'm posting this answer so that it can be useful for you. I did it by using JSON(fetched latitude and longitude in the EditText) and drew the route between 2 places using Google map services.

Here's the code:

    JSONObject jsonObjectto = getLocationInfo(ToEditTextt.getText().toString());
                JSONObject jsonObjectfrom = getLocationInfo(FromEditTextt.getText().toString());
                Log.v("P1 Value",jsonObjectto+"");
                getLatLongto(jsonObjectto);
                getLatLongfrom(jsonObjectfrom);
                try{
                    gp1 = new GeoPoint((int) (latittudefrom * 1E6),
                            (int) (longittutefrom * 1E6));

                    gp2 = new GeoPoint((int) (latittudeto * 1E6),
                            (int) (longittuteto * 1E6));


                    Log.v("To Value",gp2+"");

                    Log.v("From Value",gp1+"");
                    try{
                        mode=Modes.drivingmode;
                        if(routeoverlayy!=null){
                            mapView.getOverlays().remove(routeoverlayy);
                        }


                        if(gp1!=null && gp2!=null){
                            Route route = directions(gp1, gp2,mode);

                            routeoverlayy = new RouteOverlay(route, Color.BLUE);
                            mapView.postInvalidate();
                            //                                      routeOverlay.redrawPath(mMapView);
                            mapView.postInvalidate();
                            mapcontrol.setCenter(gp1);
                            mapcontrol.setZoom(10);

                            mapcontrol.animateTo(gp1);
                            mapView.getOverlays().add(routeoverlayy);
                            pw.dismiss();
                        }
                    }
                    catch(Exception e){

                    }
                }
                catch(Exception e)
                {

                }


                // search pressed and perform your functionality.  
                return true;
            } 
            /*InputMethodManager
              imm=(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);

              imm.hideSoftInputFromWindow(.getWindowToken(), 0); */
            return false; 
        }


    });
}

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}
public static boolean getLatLongto(JSONObject jsonObject) {

    try {

        longittuteto = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

        Log.v("Longitude", longittuteto+"");

        latittudeto = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        Log.v("Latitude", latittudeto+"");

    } catch (JSONException e) {
        return false;

    }

    return true;
}

public static boolean getLatLongfrom(JSONObject jsonObject) {

    try {

        longittutefrom = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

        Log.v("Longitude", longittutefrom+"");

        latittudefrom = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        Log.v("Latitude", latittudefrom+"");

    } catch (JSONException e) {
        return false;

    }

    return true;
}

public class RouteOverlay extends Overlay{

    /** GeoPoints representing this routePoints. **/
    private final List<GeoPoint> routePoints;
    /** Colour to paint routePoints. **/
    private int colour;
    /** Alpha setting for route overlay. **/
    private static final int ALPHA = 120;
    /** Stroke width. **/
    private static final float STROKE = 4.5f;
    /** Route path. **/
    private final Path path;
    /** Point to draw with. **/
    private final Point p;
    /** Paint for path. **/
    private final Paint paint;


    /**
     * Public constructor.
     * 
     * @param route Route object representing the route.
     * @param defaultColour default colour to draw route in.
     */

    public RouteOverlay(final Route route, final int defaultColour) {
        super();
        routePoints = route.getPoints();
        colour = defaultColour;
        path = new Path();
        p = new Point();
        paint = new Paint();
    }

    @Override
    public final void draw(final Canvas c, final MapView mv,
            final boolean shadow) {
        super.draw(c, mv, shadow);

        paint.setColor(colour);
        paint.setAlpha(ALPHA);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(STROKE);
        paint.setStyle(Paint.Style.STROKE);

        redrawPath(mv);
        c.drawPath(path, paint);
    }

    /**
     * Set the colour to draw this route's overlay with.
     * 
     * @param c  Int representing colour.
     */
    public final void setColour(final int c) {
        colour = c;
    }

    /**
     * Clear the route overlay.
     */
    public final void clear() {
        routePoints.clear();
    }

    /**
     * Recalculate the path accounting for changes to
     * the projection and routePoints.
     * @param mv MapView the path is drawn to.
     */

    private void redrawPath(final MapView mv) {
        final Projection prj = mv.getProjection();
        path.rewind();
        final Iterator<GeoPoint> it = routePoints.iterator();
        prj.toPixels(it.next(), p);
        path.moveTo(p.x, p.y);
        while (it.hasNext()) {
            prj.toPixels(it.next(), p);
            path.lineTo(p.x, p.y);
        }
        path.setLastPoint(p.x, p.y);
    }

}
private  Route directions(final GeoPoint start, final GeoPoint dest,int mode) {

    Parser parser;
    String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
    final StringBuffer sBuf = new StringBuffer(jsonURL);
    sBuf.append("origin=");
    sBuf.append(start.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(start.getLongitudeE6()/1E6);
    sBuf.append("&destination=");
    sBuf.append(dest.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(dest.getLongitudeE6()/1E6);
    if(mode==1){
        sBuf.append("&sensor=true&mode=driving");
    }
    if(mode==3){
        System.currentTimeMillis();

        try{
            sBuf.append("&sensor=true&departure_time=1343605500&mode=google.maps.TravelMode.TRANSIT&vehicle.type=VehicleType.BUS");
        }catch(Exception e){
            Toast.makeText(ScreenOfOnMyWay.this, "Route not available", Toast.LENGTH_SHORT).show();
        }
    }
    if(mode==2){
        sBuf.append("&sensor=true&mode=walking");
    }
    parser = new GoogleParser(sBuf.toString());
    Route r =  parser.parse();
    return r;
}   

Upvotes: 0

cyn0
cyn0

Reputation: 522

Its a bad programming practice to access UI components from worker thread. AsyncTask worker thread runs independent of UI thread, they may not be able to access textView and hence startedit.getText().toString() returns null.

Good style is that you pass those values in execute() method, so try

`new GetLatLong().execute(startedit.getText().toString());`

and in doInBackground(String... params), correct implementation will be

    String value=params[0];
try{
        addressgone = coder.getFromLocationName(value,5);
        if (addressgone == null) {

 }`...

Upvotes: 1

Related Questions