Driving distance and travel time duration between two locations in Google Map Android API V2

March 25, 2013
By

In this article, we will develop an Android application which displays driving distance and travel time between two locations in Google Map Android API V2. It also draws polyline along driving route from start location to end location.

Screenshot of this application is shown in the Figure 7 below.



This application makes use of Google Map Android API V2 and Google Directions API.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) and tested in a real Android device (Android 2.3.6  -  GingerBread).


1. Create a new Android application project namely “LocationDistanceTimeMapV2″

Create new Android application project

Figure 1 : Create new Android application project


2. Configure the project

Configure the application project

Figure 2 : Configure the application project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity details

Figure 5 : Enter MainActivity details


6. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

Please follow the given below link to setup Google Play Service library in Eclipse.

http://developer.android.com/google/play-services/setup.html


7. Add Google Play Services Library to this project

Linking Google Play Services Library to this project

Figure 6 : Linking Google Play Services Library to this project


8. Get the API key for Google Maps Android API V2

We need to get an API key from Google to use Google Maps in Android application.

Please follow the given below link to get the API key for Google Maps Android API v2.

https://developers.google.com/maps/documentation/android/start


9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

10. Update the file res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocationDistanceTimeMapV2</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Tap two locations in the map</string>
    <string name="str_tv_distance_time">Distance</string>
</resources>

11. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_distance_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_alignParentTop="true" />

    <fragment
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_distance_time" />

</RelativeLayout>


12. Create a new class namely “DirectionsJSONParser” in the file src/in/wptrafficanalyzer/locationdistancetimemapv2/DirectionsJSONParser.java


package in.wptrafficanalyzer.locationdistancetimemapv2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");

                List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                }
                routes.add(path);
            }
        } catch (JSONException e) {
           e.printStackTrace();
        }catch (Exception e){
        }
        return routes;
    }

    /**
    * Method to decode polyline points
    * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
    * */
    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;
    }
}


13. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationdistancemapv2/MainActivity.java


package in.wptrafficanalyzer.locationdistancetimemapv2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap map;
    ArrayList<LatLng> markerPoints;
    TextView tvDistanceDuration;

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

        tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);

        // Initializing
        markerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        map = fm.getMap();

        // Enable MyLocation Button in the Map
        map.setMyLocationEnabled(true);

        // Setting onclick event listener for the map
        map.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already two locations
                if(markerPoints.size()>1){
                    markerPoints.clear();
                    map.clear();
                }

                // Adding new item to the ArrayList
                markerPoints.add(point);

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

                // Setting the position of the marker
                options.position(point);

                /**
                * For the start location, the color of marker is GREEN and
                * for the end location, the color of marker is RED.
                */
                if(markerPoints.size()==1){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                }else if(markerPoints.size()==2){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                }

                // Add new marker to the Google Map Android API V2
                map.addMarker(options);

                // Checks, whether start and end locations are captured
                if(markerPoints.size() >= 2){
                    LatLng origin = markerPoints.get(0);
                    LatLng dest = 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
                    downloadTask.execute(url);
                }
            }
        });
    }

    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";

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

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

        return url;
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

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

            StringBuffer sb  = new StringBuffer();

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

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String>{

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

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

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

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

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

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

                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
            String distance = "";
            String duration = "";

            if(result.size()<1){
                Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    if(j==0){    // Get distance from the list
                        distance = (String)point.get("distance");
                        continue;
                    }else if(j==1){ // Get duration from the list
                        duration = (String)point.get("duration");
                        continue;
                    }

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

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
            }

            tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);

            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


14. Update the file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationdistancetimemapv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <permission
        android:name="in.wptrafficanalyzer.locationdistancetimemapv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="in.wptrafficanalyzer.locationdistancetimemapv2.permission.MAPS_RECEIVE" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationdistancetimemapv2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_ANDROID_API_KEY" />

    </application>

</manifest>

Note : At line 46, replace “YOUR_ANDROID_API_KEY” with the Google API key obtained in Step 8.



15. Screenshot of the application in execution

Showing Drving distance and time between two locations in Google Map Android API V2

Figure 7 : Showing Driving distance and time between two locations in Google Map Android API V2


16. Download Source Code


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , , , , ,

107 Responses to Driving distance and travel time duration between two locations in Google Map Android API V2

  1. bharath on March 25, 2013 at 5:56 pm

    in source it will not showing any error.but when i running it shows “ur project contain error”can u please send exact project with apk to my email.
    thank u.

    • aroma on April 29, 2015 at 9:23 pm

      hi, i am also using this code. I found out one line is missing which is
      (TextView)tv_distance_time=(TextView) getActivity().findViewById(R.id.tv_distance_time);
      I am not sure whether this is your problem.

      • nick75 on April 29, 2015 at 9:25 pm

        that line does not missing dude =)

    • amar on July 25, 2015 at 8:17 am

      In code no errors, but when executing, unfortunately app closing, can u send complete code my email sir, using android studio sir…

  2. imam nur on March 26, 2013 at 7:19 pm

    Wow you’re awesome sir.. big thanks for you.. :)

    I want to ask you again if you wish. in my final project in college, I wanted to create a custom marker with an image that I put in drawable (Local Storage). if the maps V1, I still know how. but if I want to make in V2 maps, why not work?

    sorry if I am asking a lot, but I really appreciate you for your help so far. :)

  3. cyberhagz on March 26, 2013 at 7:31 pm

    how do if I want a custom marker on maps v2?

  4. Basribaz on March 26, 2013 at 8:46 pm

    very good article….
    but how to make a list of places with latitude and longitude when
    the user selects the places to be visited
    thanks…

  5. mete on March 27, 2013 at 3:35 pm

    Google map in android application step by step list of directions such as left and right how can I do traffic direction signs. You can do it this way or example.

  6. mohit on March 29, 2013 at 10:52 am

    sir can you plz upload a app with source code having location tracking of another android device from my android device

  7. imran khan on April 4, 2013 at 3:01 pm

    it`s required googleplay service apk in emulator & device.facing issues in testing will you provide me your solution to run this program over emulator

    • george on April 4, 2013 at 3:20 pm

      Since, Google Play Store is not available in emulator, we can not run Google Map Android API V2 applications in emulator. I tested this application in a real Android device.

      • imran on April 8, 2013 at 4:59 pm

        Thanks, now working fine on device, i am also looking for Android Proximity Alerts in MAP v2. any help.

  8. Nuno Freitas on April 26, 2013 at 6:57 pm

    if the route have more waypoint, what needs to change in the code to get the distance and time for that route.

    Thanks for the tutorials, very helpfull.

  9. steve on April 27, 2013 at 2:41 am

    Quick question…how can i get access to the points from the jason file in their arraylist?

    It drawsa the points on…but i cant do anything with it now :(

  10. steve on April 27, 2013 at 2:44 am

    I worded that badly…it draws the maps…but I want an arraylist of latlng points back in my mainactivity file. Cant for the life of me figure it out.

    Was just trying to use the points array from the bottom but its always null if i try and call it to the top.

    • george on April 27, 2013 at 4:31 am

      Assign the argument variable “result” of the method “onPostExecute()” to a member variable so that we can reuse it in the class “MainActivity”.

  11. ks on May 7, 2013 at 7:39 pm

    Hi George,

    First, thanks for your great tutorial!
    This project is aim to Showing Driving distance and time between two locations.

    Wonder can how can I get the time on ‘walk’ instead of ‘Driving’?

    Thanks!

    • george on May 7, 2013 at 7:56 pm

      Hi,

      Add the parameter “mode=walking” into Google directions url built in the method getDirectionsUrl() of the class MainActivity.

      • ks on May 7, 2013 at 8:09 pm

        pardon me. Is the url like this?

        String url = “https://maps.googleapis.com/maps/api/directions/”+output+”?”+parameters+”mode=walking”;

        after added the mode, the app always show ” No Point”

        • ks on May 7, 2013 at 8:15 pm

          Fixed, a silly mistake made

          • gonzalo on September 17, 2013 at 4:16 am

            How can you fixed?

  12. ks on May 7, 2013 at 8:04 pm

    Thanks!

    I am trying to add the duration information in your another app:
    “Route directions for driving mode, bicycling and walking mode in Google Map Android API V2″

    and got many tips from your blog

  13. ages on May 9, 2013 at 2:29 am

    Hi George,

    First, thanks for your great tutorial!

    Wonder can how to make driving distance, travel time and draws polyline along driving route from my location to custom place which we mark in program??

  14. imam on May 9, 2013 at 1:25 pm

    Hello Sir, I want to ask you.

    how to use the distance and travel time as the data in the calculation?

    because when I use the data directly, application errors and should be forcibly closed.

    please ur help and thank you before..

    Warm Regards,

    Imam

    • ks on May 10, 2013 at 4:17 pm

      = because when I use the data directly, application errors and should be forcibly closed.

      It suddenly happened today! =(

      • sarath on October 16, 2013 at 11:07 am

        Hi i to require same .if you please help me.thank you

  15. ks on May 10, 2013 at 6:00 pm

    Can George test the application can be run success now?

    Thanks!

    • george on May 10, 2013 at 6:37 pm

      Yes, It is working. No issue is found.

      • jhay Q. on May 2, 2016 at 2:59 pm

        how can i show distance and time travel from my location to nearby place such as hospital when i click the marker? any help please?

  16. pratik on May 11, 2013 at 5:18 pm

    Thanks for sharing such a nice code….Have a good day..!

  17. prs on May 14, 2013 at 1:28 pm

    Thanks for the post.Can we add distance and duration as label on the polyline?

  18. zulqarnain on May 22, 2013 at 1:08 pm

    Thanx Sir for such a great tutorial,Sir how i can get direction from my current position to a place,,,,

  19. Akbar on June 15, 2013 at 8:47 am

    Hello Sir, I would like to ask.
    In my final project in college, I wanted to make application directions by car object using Goggle Maps, I’ve tried the tutorial Driving distance and travel time duration between two locations in Android Google Map API V2, but here I was asked to prove the route pointer journey from google maps and Google Map route pointing journey using Hill Climbing. Roughly how to implement it.
    please your help and thank you before sir
    warm regrads,
    Akbar

  20. Ekkachai on July 15, 2013 at 9:24 am

    Hi George,
    Driving distance and travel time duration, Can be int or not? Please help me.

  21. Thoai Nguyen on July 18, 2013 at 7:27 pm

    This site is so helpful, the code is simple and great. Thank you very much!

  22. Jacks on July 30, 2013 at 8:14 pm

    This apps not working, its forced closed

  23. Jacks on July 30, 2013 at 8:17 pm

    this is the logcat

    07-30 21:42:45.709: W/dalvikvm(4864): threadid=1: thread exiting with uncaught exception (group=0x40aeb9f0)
    07-30 21:42:45.739: E/AndroidRuntime(4864): FATAL EXCEPTION: main
    07-30 21:42:45.739: E/AndroidRuntime(4864): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.petadirection/com.petadirection.MainActivity}: android.view.InflateException: Binary XML file line #14: Error inflating class fragment

    07-30 21:42:45.739: E/AndroidRuntime(4864): at dalvik.system.NativeStart.main(Native Method)
    07-30 21:42:45.739: E/AndroidRuntime(4864): Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
    07-30 21:42:45.739: E/AndroidRuntime(4864): … 21 more

    • george on July 30, 2013 at 8:58 pm

      Hello Jacks,

      I think there is some error in your layout file. Please ensure that, the package name for SupportMapFragment class is specified correctly.

      Also please check your class com.petadirection.MainActivity is extending the class FragmentActivity

      • Jacks on July 31, 2013 at 8:21 am

        Hello George which one i should change?
        im stuck with this. Help me pls

      • José De la O on September 14, 2013 at 1:37 am

        i have the same problem with this project, can you help me George?

        • sarath on October 13, 2013 at 4:12 pm

          Hi iam to struck with same problem please help us out

          • Ron on May 26, 2014 at 6:06 pm

            change it to this for anyone getting the same error

          • vineet on October 13, 2014 at 5:55 pm

            add

            in mainfest

  24. Jacks on July 31, 2013 at 8:53 am

    Thx George I found the solutions, sorry for
    heres my solutions,

    “ADDED”

    But george, may i ask you how to make exceptions, so when no internet connections the apps will not crash if users tapping on it. maybe some TRY catch?

    Thanks in advance

    • Jacks on July 31, 2013 at 8:54 am

      add class=”com.google.android.gms.maps.SupportMapFragment” on layout

  25. Miguel on September 30, 2013 at 12:47 pm

    I tried installing it on my phone however no map is displayed. I need help.

    • Miguel on September 30, 2013 at 1:41 pm

      I got it working now. However when I tried to install to my galaxy note 10.1 its not running. Help!

      • claire ann on October 24, 2013 at 6:12 pm

        Hi Miguel. I have the same issue on this: “no map is displayed” how did you fix it?

        • Miguel on October 26, 2013 at 11:00 am

          Probably you need to put the api key from Google API console and you need to test it on the phone

          • claire on October 26, 2013 at 1:16 pm

            I did that already but i just got the white screen & the zoom out zoom it.

        • Miko Pagunuran on November 22, 2013 at 10:07 am

          try going to Project -> Clean then uninstall the application on your device then Run it again.. this one worked for me and what i always do everytime i make changes on my map code

  26. sarath on October 14, 2013 at 10:59 pm

    Hi i am getting white screen while after installing app please could you tell whether i have to use browser api key or android api key .i am able to run your locationnearby app.please help me .thank you in advance

    • George Mathew on October 15, 2013 at 5:30 am

      In AndroidManifest.xml, we have to use Android api key

      • sarath on October 16, 2013 at 11:29 am

        hi mathew thank you for your help great work really awsome.could you please help me in converting that distance to double value actually i want to use it for caluclation.I didnt got clarity using result in main actitvity u poste in earlier comment.please provide me the syntax code it would be really help full thank you

  27. claire ann on October 25, 2013 at 12:12 pm

    Hi guys. Please help me. I am getting white screen while after installing app on my device. I used the android api key. What do you think is my error? Thank you so much!

    • George Mathew on October 25, 2013 at 1:21 pm

      Please ensure that, Google Maps Android API V2 is enabled in Google API Console

      • claire ann on October 25, 2013 at 3:15 pm

        Hi Sir George. Thanks for replying. Google API Console, do you mean here?
        https://code.google.com/apis/console/#project:657116820774:services

        I already enabled that sir. :(

        • claire ann on October 25, 2013 at 3:23 pm

          Sir. George. I send an my project on your gmail account. Can you please check if you have a time? Thanks so much!

          • claire ann on October 25, 2013 at 3:35 pm

            It’s a screen shot Sir. George of what i’ve done. Thanks again!

            * I send my project on your gmail account.

        • sarath on October 28, 2013 at 9:50 pm

          hi
          My issue is resolved by using browser key but not android api key

  28. natesh on December 10, 2013 at 5:56 pm

    Am getting force close. Activity is not open. I done all the steps exactly same. Can u guess whats the fault.
    While debugging this lines shows err
    setContentView(R.layout.activity_main);

  29. irrfan on February 9, 2014 at 5:02 pm

    Thanks for the great tutorial.
    I want to set destination to a specific location, and then from my current location the app will take me to that location.
    how to do that? any help please

  30. Julyan on April 14, 2014 at 9:01 am

    i have error sir can you help me?
    error in:
    SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
    error “The method getSupportFragmentManager() is undefined for the type MainActivity”

  31. Razvan on June 19, 2014 at 6:02 pm

    Is there any possibility to get all intersections from a drawed route? If yes how I can do that?
    Thank you

  32. Kevin on August 19, 2014 at 7:09 am

    Can you know the driving distance and traveling time in a route with waypoints?

  33. kunal on September 1, 2014 at 2:26 am

    really good example helps me allot but if i want duration in traffic.
    Provide me any solution

    Thanks

  34. Mohit on September 22, 2014 at 4:53 pm

    if the route have more waypoint, what needs to change in the code to get the distance and time for that route.

    Thanks for the tutorials, very helpfull.

  35. Nebbs on September 26, 2014 at 5:04 pm

    Hi George,

    With no doubts your tutorials are the best I managed to find on the web. As many others said thank you very much for this.

    Small question however, how can I implement a logic which will display nearby points of interest (which I would store locally within my app, ie: an XML) along the driving route?

    Can you please suggest?

    Thanks and regards

  36. Prakash on October 18, 2014 at 1:00 pm

    Thank you for this tutorial sir..
    Sir, Do you have the code to calculate and show distance between two places in map where the places name are selected from spinner?

  37. Nitin Sangani on October 21, 2014 at 10:50 am

    thanks sir…
    it’s work perfect for my app..
    sir,how can we enable gps in this tutorials which provides arrrow when we start our traveling from source?

  38. Alicia Beltran on October 25, 2014 at 9:11 am

    First I wnto to say thanks for your blog, and your answers.

    I have a problen when i Try to get a route like a bike, its because here is not able that info.

    However I have all the geopoints that can describe the cycle-Path that are designed for bikers.

    I have painted in my map, the cyle-path net, but i want to join those criteria to calculate a route like a bike.

    How can I do it?
    My I will need to create my own algorithm, please if you know how, or have any clue, please letme know.

    Thanks for your time.

    Alicia from Colombia – Bogota

  39. Ankit on November 17, 2014 at 3:45 pm

    11-17 15:41:07.992 27088-27088/com.*.*.*E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.*.*.MyClass}: android.view.InflateException: Binary XML file line #44: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3687)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: android.view.InflateException: Binary XML file line #44: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:587)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:408)

    please help me with this exception. Done all the required changes but this exception is not going and it is force closing my application. Please help!!

  40. Gaurav on December 30, 2014 at 8:12 pm

    Iam able to draw route between two location ,but i want to track it from one location to another with that route…
    can you tell me how to do…

  41. sugan on January 17, 2015 at 11:06 am

    Sir, i have to convert the duration totally in minutes. in this tutorial you have made duration as day,hours and minutes but i have to convert all those into minutes…. Please reply sir.

  42. kartik on March 20, 2015 at 7:31 pm

    sir ,whether this project aims to calculate the distance continuously
    while we are driving or it just give the distance between two locations directly

  43. Danish on April 21, 2015 at 7:12 pm

    Please tell me distance and duration will update with the location changed?

  44. me on June 12, 2015 at 2:53 am

    Your the best! Thank you so much!!!

  45. lala on June 15, 2015 at 9:04 am

    i would like to ask. i tried to create these code in android studio. but, when i run it. the app unfortunately stop

  46. Acero on June 20, 2015 at 4:46 am

    It can be used as taxi drivers?

  47. Nezih on July 2, 2015 at 5:13 pm

    Hi, thanks for this awesome tutorial. But i got an error could you help me?

    Log Cat:

    paste2.org/dV1MUt70

    I did same things with you but failed.
    THank you for help.

  48. Thejaswini M S on September 4, 2015 at 1:35 pm

    Hello Sir,Google documentation says Distance MAtrix api requires API_KEY,Here you are not using api key.Is it ok to publish an app without API_KEY in play store.

  49. Thejaswini M S on September 4, 2015 at 1:39 pm

    Sir,You are not using API_KEY in Distance matrix api,is it ok to publish app without API_KEY

  50. Anmol on September 29, 2015 at 6:16 pm

    getGoogleAppId failed with status: 10
    this is the error i’m getting.

  51. Ryan on October 3, 2015 at 7:54 pm

    Very Nice Tutorial Sir,
    I try calculation between data distance with custom value and it could not be done because of the distance value of a string value.
    How to add information cost of distance calculation with custom value ?

    Thank you so much!

    • Rahul on April 28, 2016 at 4:00 pm

      String distance;
      distance = (String) point.get(“distance”);
      tv_distance.setText(“Distance:” + distance + “, Duration:” + duration);

      distance = distance.replaceAll(“[A-Za-z]“, “”);
      System.out.println(distance);
      tv_distance.setText(“Distance:” + distance + “, Duration:” + duration);

      Remove Alphabets from receiving Distance @rahul

  52. Nofal on October 13, 2015 at 5:08 pm

    Hey George, thanks for the tutorial ,i am having issue when i run the app on my device ,it says the Unfortunately the app have stopped working..
    Also can you provide the apk file of the above project..
    I am building an app which has to calculate distances from pickup location to drop up location.??

  53. Manoj Singh Rawal on October 14, 2015 at 1:28 pm

    Thanks Mathew, Very helpfull…

  54. Raza on November 7, 2015 at 3:14 pm

    Thanks George for such a great tutorial,
    There is a differnce between ETA i get and ETA on google maps between two locations, will you help me to sort this out.

  55. rupert on November 18, 2015 at 10:55 pm

    how do i pss static values for origin lat long and destination latlong???

  56. Alexander on December 1, 2015 at 3:19 am

    Can I use a street address in JSON request (like “1600 Amphitheatre Parkway, Mountain View, CA”)? Not LatLng!

  57. Yogesh Patel on December 10, 2015 at 4:15 pm

    I am following your tutorials since last six months and these are indeed really helpful. Thanks alot sir..!!!

  58. meysam on December 22, 2015 at 3:33 pm

    Good time

    To be able to read the situation in a given time interval and not marked on the map as a place What to do

    Can you help me !?

    Thank you

  59. Saumyajit on December 30, 2015 at 11:02 am

    How to get nearby places with corresponding distances from the current location

  60. Kasun Sampath on January 9, 2016 at 3:45 pm

    Hi George, nice tutorial it worked for me.but I have small issue.I am new user to android.As my knowledge,it marked the path both locations approximately by nearby location which identified by google.That means the starting and end point of the path is nearby location of two locations.Can I add distance from exact location to nearby location as straight line and calculate the distance?

  61. Raiden on February 20, 2016 at 6:27 pm

    If use these codes at Android Studio, does it works?
    Because i having problems using these codes at Android Studio.
    The tap and calculate the duration functions are disappear on the google map when i executed it on Android Studio Emulator.
    Can you help to explain what happen? Plsss… Tqvm.

  62. Varshil on February 21, 2016 at 5:42 pm

    Create Response: {“success”:0,”message”:”Required field(s) is missing.”}

    i getting above response ..i don’t know why..please help me

  63. gokul on February 23, 2016 at 11:30 am

    sir i need one help me i need this codeing as well as apk file
    so please sent to my mail id
    iamgokulraj93@gmail.com

  64. Yoo Kiat Wei on March 8, 2016 at 4:54 pm

    Hi,how to show up the location address as info window on marker?
    Thanks in advanced.

  65. ankita mane on March 8, 2016 at 7:50 pm

    map = fm.getMap(); deprected any solution?

  66. Shiva on March 10, 2016 at 11:46 am

    In my project i found, when compiling JSONObject parentObject = new JSONObject(finalJson); this line it shows unfortunately Application as stop without any error.

    and also.,

    i get a buffer.toStirng(); result started with some XML tags like,

    ….

  67. faty on April 4, 2016 at 4:16 pm

    svp Mr. George; tu peut m’aider à une application android programmé ( code source) pour éviter la cpngestion routière ?
    Merçi

  68. Faheem on April 12, 2016 at 1:45 pm

    It cannot find distance outside the country and it shows “No points” and result size 0; why?Like london(latlong) and new delhi(latlong).

  69. Dhinesh on April 15, 2016 at 8:33 pm

    Thank you sir. Very use full tutorial

  70. jhay Q. on May 1, 2016 at 7:07 pm

    hello? i just want to know if this application shows the current location of the user? thanks a lot! a big help!

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner