Android Google Map – Drawing Route Between two points

Filed Under: Android

In this tutorial, we’ll be creating an android application that draws a possible google map route between two points. We’ll be using Google Maps Directions API in our application.

Android Google Map – Drawing Route

Create a new Google Map API Key from the API console using the steps demonstrated in this tutorial.

Create a New Android Studio Project and select the template as Google Maps Activity. Add the API key inside the google_maps_api.xml file that resides inside debug->res->values folder

This is how the application should look if you’re using the latest Android Studio.
android google maps drawing route between two points

Android Google Maps Drawing Path Project Structure

drawing path between two points in google maps android

The file is the one that parses the locations and returns the route. decodePoly() method is then invoked to get the polyline data that’s later drawn on the map.

Android Google Maps Drawing Route Code

The code is given below.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    ArrayList markerPoints= new ArrayList();

    protected void onCreate(Bundle savedInstanceState) {
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng sydney = new LatLng(-34, 151);
        //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            public void onMapClick(LatLng latLng) {

                if (markerPoints.size() > 1) {

                // Adding new item to the ArrayList

                // Creating MarkerOptions
                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker

                if (markerPoints.size() == 1) {
                } else if (markerPoints.size() == 2) {

                // Add new marker to the Google Map Android API V2

                // Checks, whether start and end locations are captured
                if (markerPoints.size() >= 2) {
                    LatLng origin = (LatLng) markerPoints.get(0);
                    LatLng dest = (LatLng) markerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API



    private class DownloadTask extends AsyncTask {

        protected String doInBackground(String... url) {

            String data = "";

            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            return data;

        protected void onPostExecute(String result) {

            ParserTask parserTask = new ParserTask();



    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap>>> {

        // Parsing the data in non-ui thread
        protected List<List<HashMap>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();

                routes = parser.parse(jObject);
            } catch (Exception e) {
            return routes;

        protected void onPostExecute(List<List<HashMap>> result) {
            ArrayList points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList();
                lineOptions = new PolylineOptions();

                List<HashMap> path = result.get(i);

                for (int j = 0; j < path.size(); j++) {
                    HashMap point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);




// Drawing polyline in the Google Map for the i-th route

    private String getDirectionsUrl(LatLng origin, LatLng dest) {

        // Origin of route
        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

        // Destination of route
        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

        // Sensor enabled
        String sensor = "sensor=false";
        String mode = "mode=driving";

        // Building the parameters to the web service
        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "" + output + "?" + parameters;

        return url;

    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            urlConnection = (HttpURLConnection) url.openConnection();


            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {

            data = sb.toString();


        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
        return data;

We’ve called an onMapClickListener on the google map object. It’s used to set a marker on the clicked location and store that location in an ArrayList. The ArrayList is used to store the source and destination markers only.
The getDirectionsUrl() is called the Directions API URL with the output and parameters as shown below.

"" + output + "?" + parameters;

The output variable holds a “json” string and the parameter string is created as:
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

We’ve set the mode=driving in the current application.
The other modes of transport are:

  • driving (default)
  • walking
  • bicycling
  • transit

The output of the application is given below:

android google maps draw path

This brings an end to this tutorial. You can download the final project from the link below, add your own Google Map API key.


  1. khurseed ansari says:

    i am facing this error.. how to resolved please help of this

    { “error_message” : “You must enable Billing on the Google Cloud Project at Learn more at“,

    1. Ahmad Baraka says:

      The Same here

  2. Purushotham says:

    Is it mandatory to add billing for Google api
    Am facing error on that

  3. Sitansu says:

    hello sir,i want to draw the route between two place from edit text which we enter pick location and drop location.How can i show this from edit text and draw route between two place?Please reply

  4. Nishit Gajjar says:

    Please refactor the code because we are facing a MAP API KEY issue so add this in your code so that we can save our time

    1. Anupam says:

      Hi Nishit,
      Please follow the mentioned steps to generate your own API key from Google Developers Console. For privacy reasons, I can’t share my API keys.

    2. Anupam says:

      Hi Nishit,
      You can generate your own API keys from Google Console. We avoid sharing API keys here due to privacy reasons.

  5. Ahmed Raza says:

    Hey Anupam,
    I hope you will be fine. I have an issue in android related to maps.
    Can you help me?

  6. Thomas Tsuma says:

    Hi , Im trying to understand your code since I am a beginner.
    Why do I keep getting this runtime error:
    java.lang.NullPointerException: Attempt to invoke interface method ‘int java.util.List.size()’ on a null object reference

    it has something to do with result being null

    1. Pankaj says:

      Yes, you can’t call methods on a “null” object. Check if the object is initialized properly.

      1. soard raspi says:

        And how exactly to initialize it??
        I am a beginner too and am getting the same issue. Some help would be greatly appreciated and thanked.

  7. Prabeesh P says:

    I want to draw route between two points in map.But as per the above code I could only select two points in map, the direction doesn’t came.
    Is there any suggestions for me to solve .

  8. Vinod Kadiyan says:


    I have gone through your tutorials of google map android. I am stuck to show journey route of train covered and remaining in two different colors. Second color overlapping on 1st one…

    2nd issue it is showing alternative route which I coded alternatives=false also but still showing extra lines…

    Please visit URL to have more information about issue…

    I want little help to sort these small issues…

  9. survey says:

    polylineOptions = null

    why is it empty?

  10. Syed Reazul Elahee says:

    I want to draw route between more than two points. How can i do that ? Is it possible with a single call ?

  11. Bhavya Shah says:

    Any help with this?

    java.lang.NullPointerException: PolylineOptions cannot be null.
    at (040700-211705629):32)
    at (040700-211705629):6)
    at (040700-211705629):80)
    at (040700-211705629):501)
    at fh.onTransact( (040700-211705629):10)
    at android.os.Binder.transact(
    at Source:7)
    at Source:9)
    at Source:4)
    at com.example.hb.navdrawerapp.SecondFragment$ParserTask.onPostExecute(
    at com.example.hb.navdrawerapp.SecondFragment$ParserTask.onPostExecute(
    at android.os.AsyncTask.finish(
    at android.os.AsyncTask.access$600(
    at android.os.AsyncTask$InternalHandler.handleMessage(
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invoke(Native Method)

    1. Vishal Singh says:

      Add your api key to url as mentioned below

      String url = “” + output + “?” + parameters +”&key=” +”YOUR KEY”;

  12. Bhavya Shah says:

    I want to use this inside fragment. I did this in my OnCreateView()-

    View rootView=inflater.inflate(R.layout.image1,container,false);
    mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(;
    return rootView;

    And I am getting this error-
    java.lang.NullPointerException: Attempt to invoke virtual method ‘void’ on a null object reference

  13. Bhavya Shah says:

    I am not getting an output. It just shows a map, that’s all.

  14. Vinod Singh says:

    Hi Anupam Chugh,

    Could you tell me after drawing a map between two locations,how to update a user position with respect to his moment? Can you help me please…….. Thank you!

  15. Benson says:

    DirectionsJSONParser is missing.

  16. Gift says:


    when i run the app it crashes and the error points to this String str_dest = “destination=” + dest.latitude + “,” + dest.longitude;

  17. Alexander says:

    Hi, you are really helped me, but I’m getting errors:
    java.lang.NullPointerException: PolylineOptions cannot be null.
    why is this error?

    1. Anupam says:

      Please make sure that the class object is initialised properly.

    2. Tigran says:

      Hi, Did you solved the problem?

      1. Varun says:

        I am also facing the same issue. I Just downloaded and code, added my key and ran it.

        1. Ghadi says:

          hello did you solve the problem? I opened the code and put my key(direction API enabled) and still telling me that I am using null objects

    3. Felipe Marinho Maia says:

      API Google now requires KEY for routes.

      1. Jacito Duarte says:

        this route key is free??

  18. Andŕes Guachun says:

    Hi, the google directions have a cost?

  19. kritesh kabariya says:

    if i can 8 or 9 time in add point in polylineoption then give error you can try

    first get spinner and add 2 value driving and walking
    that add in mode value
    after select to change route

    that selection 7 or 8 time i sure give the error

  20. LeizaR says:

    i am here just to say i love it, work on the first time
    is there any way to get the distance from the route?

    1. Anupam says:

      Use the Google Distance API

  21. Keshav says:

    Where is code?

  22. Amrut says:

    For me the route is not getting drawn, what could be the issue?

    1. Asmit Adak says:

      same here brother

    2. amila says:

      same here did you solved iT?

  23. erfan says:

    nice and clean . thanks

  24. Sjhivani says:

    Cant see a directional route between my marker points…getting a straight line instead..
    Please help me fix the issue

  25. fajarra says:

    i found error here,

    Error:Execution failed for task ‘:app:transformClassesWithDexForDebug’.
    > java.util.concurrent.ExecutionException: method ID not in [0, 0xffff]: 65536

    what must i do ..?

    1. fajarra says:

      i solve my problem after migrate compileSdkVersion from 25 to 26. Thanks Anupam, its great….

      1. sudarsana says:

        please tell me i got same error how to solve it

        1. Debasish Ghosh says:

          firstly import this gradle :
          compile ‘’

          then write
          defaultConfig {

          multiDexEnabled true

          it should be help for you…..

  26. Emil says:

    Hi, Can we mark for more than one locations?

  27. Amin says:

    Hello. thx for your great post. How can i add more than one location and add polyline for it ?

    1. harshit says:

      sir,did you got the solution for adding more than one marker

  28. kana says:

    Every thing is great, but it doesnt zooms at current location.. How to do that?? Please reply ASAP !

  29. lathiya bhautik says:

    i didn’t find DirectionsJSONParser file

  30. Anirudh Kaluri says:

    the for loop in onPostExecute isnt getting executed. Please tell me how.

    1. Anupam says:

      Perhaps the direction result isn’t being returned. Maybe you haven’t enabled the Direction API

      1. anonymous says:

        hello sir i use this code but result retrun 0 i also enable direction api but still polyline not draw

    2. Akhilesh Kumar Shukla says:

      have u solved the issues

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content