3

Here is my code :

    public class MyGoogleMapActivity extends FragmentActivity {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.googlemap);

            GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            map.setMyLocationEnabled(true);

            LatLng Paris= new LatLng(64.711696, 12.170481);
            map.addMarker(new MarkerOptions().title("LolluSaba").position(Paris));
            LatLng Cinema= new LatLng(34.711696, 2.170481);
            map.addMarker(new MarkerOptions().title("Pseudo").position(Cinema));
       }
    }

And i like to draw a route from Paris to Cinema. How can I do it very simply ?

KingMaker
  • 83
  • 1
  • 1
  • 13

4 Answers4

4

Assuming that you have the coordinates of the two points you want to draw, you can get the route from google using the following methods:

class GetDirection extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MapaAnunciante.this);
        dialog.setMessage("Drawing the route, please wait!");
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    protected String doInBackground(String... args) {
        String stringUrl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin+ "&destination=" + destination+ "&sensor=false";
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(stringUrl);
            HttpURLConnection httpconn = (HttpURLConnection) url
                    .openConnection();
            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpconn.getInputStream()),
                        8192);
                String strLine = null;

                while ((strLine = input.readLine()) != null) {
                    response.append(strLine);
                }
                input.close();
            }

            String jsonOutput = response.toString();

            JSONObject jsonObject = new JSONObject(jsonOutput);

            // routesArray contains ALL routes
            JSONArray routesArray = jsonObject.getJSONArray("routes");
            // Grab the first route
            JSONObject route = routesArray.getJSONObject(0);

            JSONObject poly = route.getJSONObject("overview_polyline");
            String polyline = poly.getString("points");
            pontos = decodePoly(polyline);

        } catch (Exception e) {

        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        for (int i = 0; i < pontos.size() - 1; i++) {
            LatLng src = pontos.get(i);
            LatLng dest = pontos.get(i + 1);
            try{
                //here is where it will draw the polyline in your map
                Polyline line = map.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude,                dest.longitude))
                    .width(2).color(Color.RED).geodesic(true));
            }catch(NullPointerException e){
                Log.e("Error", "NullPointerException onPostExecute: " + e.toString());
            }catch (Exception e2) {
                Log.e("Error", "Exception onPostExecute: " + e2.toString());
            }

        }
        dialog.dismiss();

    }
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

Where origin and destination are two strings containing the lat and lng of the points, formatted like "-1.0,2.0":

 String origin = "64.711696,12.170481";
 String destination = "34.711696,2.170481";

To execute it, just call new GetDirection().execute();

Hope it helps!

Giacomoni
  • 1,468
  • 13
  • 18
  • So i had to create an other class which is Get Direction ? Can I had this to Class MyGoogleMapActivity ? – KingMaker Mar 20 '14 at 14:20
  • Yes, you can create it inside your MyGoogleMapActivity, I created my GetDirection inside my activity too! – Giacomoni Mar 20 '14 at 14:22
  • 1
    I have some errors : dialog cannot be resolved to a variable, MapaAnunciante cannot be resolved to a type, pontos cannot be resolved to a variable and The method decodePoly(String) is undefined for the type GetDirection. What should I do ? – KingMaker Mar 20 '14 at 14:43
  • oh sry... MapaAnunciante is your MyGoogleMapActivity, pontos is defined as private List pontos;, the method decodePoly is just under the class, it should work – Giacomoni Mar 20 '14 at 14:45
  • Just declares a private ProgressDialog dialog;, so there will be a dialog while it draws the route – Giacomoni Mar 20 '14 at 14:53
  • I created this inside of MyGoogleMapActivity and how can i call it because it shows me that -The type GetDirection is never used locally – KingMaker Mar 20 '14 at 14:58
  • It's like I said on the answer, you just call new GetDirection().execute(); when you want to draw the route... but call it after the String origin = "64.711696,12.170481"; String destination = "34.711696,2.170481"; – Giacomoni Mar 20 '14 at 15:00
  • I see this on the LogCat - the google play services resources were not found. check your project configuration to ensure that the resources are included. And we i clic on my app i can see "Drawing the route, please wait!" and after 2 sec it's my app close immediately. – KingMaker Mar 20 '14 at 15:28
  • Oh, that's because you didn't link the google-play-services to your projects. If you don't link it, you cannot use Google Maps in your app. You can check it here: http://stackoverflow.com/questions/14142496/how-to-fix-google-play-services-2-library-install-to-eclipse, here: http://stackoverflow.com/questions/14371725/add-google-play-services-to-eclipse-project, and here: http://stackoverflow.com/questions/13715716/how-to-add-google-play-services-jar-project-dependency-so-my-project-will-run-an – Giacomoni Mar 20 '14 at 16:24
  • Before try to draw the route. I had the possibility of showing the map. And i could mark my current location too. I already linked it. – KingMaker Mar 20 '14 at 18:18
  • No. I still have the same problem. (I see this on the LogCat - the google play services resources were not found. check your project configuration to ensure that the resources are included. And we i clic on my app i can see "Drawing the route, please wait!" and after 2 sec it's my app close immediately.) – KingMaker Mar 21 '14 at 12:09
  • That's because you don't have the google play services linked in your project, so your google maps won't work. You need to follow the 3 tutorials I have sent to you on the previous comments – Giacomoni Mar 21 '14 at 12:12
  • Before I try to do the route, I could see my map and I had already linked google play services in my project. – KingMaker Mar 21 '14 at 17:02
  • And if you doesn't call the asynctask that show the route, does is show the map? or it throws another exception? – Giacomoni Mar 21 '14 at 17:05
  • if I do only class GetDirection { i have an error which is The method onPreExecute() is undefined for the type Object And if I do this : /*protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(MyGoogleMapActivity.this); dialog.setMessage("Drawing the route, please wait!"); dialog.setIndeterminate(false); dialog.setCancelable(false); dialog.show(); }*/ I can see the map as before but i don't see the route ... – KingMaker Mar 23 '14 at 09:59
  • @giacomoni I do exactly like your codes, but it didn't draw anything! – Dr.jacky Aug 02 '14 at 11:33
  • { "error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account", "routes" : [], "status" : "REQUEST_DENIED"} Please suggest for this – Tushar Srivastava Feb 13 '19 at 07:23
2

As you have two points so send it through google json which provides to draw route between two points. See this example.

Route direction between two location

Shadow
  • 6,864
  • 6
  • 44
  • 93
2

You Need to use the Directions API in combination with the Android Maps util Lib

  1. Get the Encoded Polyline String from the Directions Api.
  2. Decode the encoded string using Maps Util Lib into a list of lat/lng's (https://developers.google.com/maps/documentation/android/utility/#poly-encoding)
  3. Draw the Polyline on the map using the lat/lngs!
Parampal Pooni
  • 2,958
  • 8
  • 34
  • 40
0

First a List of LatLng you need

List<LatLng> ls_pos=new ArrayList<>();

After that In OnMapReady

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
   if (ls_pos.size() >= 2) {

 mMap.addPolyline(newPolylineOptions().addAll(ls_pos).width(10).color(Color.RED).visible(true).clickable(true));

     ls_pos.clear

That's Work for me.

H.Fa8
  • 318
  • 3
  • 10