Google Maps Distance Calculator using Google Maps API

Hello guys, welcome to a new Android Tutorial. In this tutorial we will be creating a Google Maps Distance Calculator Android Application.

I have already posted a Google Maps Tutorial. I would suggest you to go through the previous Google Maps Tutorial before following this Google Maps Distance Calculator Tutorial.

So in this app we will calculate the distance between two coordinates of the map. We will also draw a path between the given coordinates. So lets start.

Google Maps Distance Calculator Demo

You can check out this video demo before moving ahead to the tutorial.

Now if you want to create the same then move ahead to this Google Maps Distance Calculator Tutorial.

Creating the Android Project

  • So open Android Studio and create a new project. Now you have to select Maps Activity. I will not be discussing in details. You can check the previous google maps tutorial.
  • You also need your API Key, which you can get from google developer console. I have explained these stuffs on previous post. But one more thing here we need to do. We have the API key for Android. But for Google Maps Distance Calculator App we also need an API Key for Server.
  • Go to Google Maps Direction API. And click on GET A KEY.

google maps direction api

  •  Now select your project and click on continue.

select project

  • Now go to New Credential  and create a Server Key (I am assuming you already have the Android Key).

serverk key

  • Note down your server key and come back to your project in Android Studio.

Adding Google Maps Android API utility and Volley Library

  • In this Google Maps Distance Calculator (It is clear from the name) we need to calculate the distance between two coordinates from the map. And for this I will be using this library. So first we have to add this library to our gradle.build dependencies block.
  • We also need to send an HttpRequest to get the path between two coordinates. For this I will be using Volley Library.
  • So go inside your gradle.build file and add the following dependencies.

  • Now come to activity_maps.xml and write the following code. It will create our layout.

  • As you can see we have only 3 buttons on the layout and a fragment to display maps. The buttons are to set the coordinates and calculate distance. When the user will calculate the distance we will also show the path between the coordinates.
  • Now come to MapsActivity.java and write the following code.

  • The above code is already explained in my previous google maps tutorial. Till here we are able to get the two coordinates from the map. The final things we need to do for our Google Maps Distance Calculator App is:
    • We have to calculate the distance between the coordinates.
    • We have to draw a path between the coordinates.
  • As we are using Google Maps API Utility Library, calculating distance is extremely easy. We can use the following code to calculate the distance between coordinates.

  • To draw the path between the coordinates we need to know the path. This is a little difficult as we need to call the Google Maps Direction API. For this first we will create our request URL.  For this we can use the following code. (Replace SERVER-KEY with your Server Key that you created in your Google Developer’s Account).

  • The above method would give us a URL as a string. We need to send a get request the the URL and in return (if successful) we will get JSON.
  • To send the request we will use volley.

  • These two methods will draw the route on the map. I got this from Stack Overflow.

  • The final code of our MapsActivity.java for this Google Maps Distance Calculator  would be.

  • Lastly for this Google Maps Distance Calculator you need to add the following permissions to your AndroidManifest.xml

  • Now thats all, just run your Google Maps Distance Calculator(Use a real device).
google maps distance calculator
Google Maps Distance Calculator
  • Bingo! Our Google Maps Distance Calculator is Working absolutely fine. You can get my source code from below.

[wp_ad_camp_1]

 Thats all for this Google Maps Distance Calculator.Please share this post if you found it helpful to support us. And also feel free to ask if having any query regarding this Google Maps Distance Calculator. Thank You 🙂

32 thoughts on “Google Maps Distance Calculator using Google Maps API”

  1. Hi Bilal just tell me why you use Uri.parse(“android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path”);

    And when i am running the code then it is not working app gets crash.

    And also this site’s captcha also not work first time.It always shows error and second time works fine.

    Reply
  2. Sorry now the app is working absolutely fine but when i am dragging marker from current location to any other point then it is not calculating distance always showing 0.0 meter And what is the use of set from and set to button?when clicks on both button only showing toast message From Set and To Set.

    Reply
  3. A question, please…How I get a Server-Key from Google Developers Console? I have my Api key, but this error appear “This IP, site or mobile application is not authorized to use this API key”, please help me.

    Reply
  4. How to implement this same thing without maps.
    I mean the app should the distance between the two areas
    It should have two text fields. one is from address and other is to address.
    as the user enters the area names it show the distance between the areas.

    How to implement that?

    Reply
  5. Hey i am facing this error while implementing this task.

    Process: com.example.mayankacharya.dataparsingtutorial, PID: 7553
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mayankacharya.dataparsingtutorial/com.example.mayankacharya.dataparsingtutorial.MapsActivity2}: java.lang.NullPointerException: null reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: null reference
    at com.google.android.gms.common.internal.zzx.zzz(Unknown Source)
    at com.google.android.gms.appindexing.Thing$Builder.setUrl(Unknown Source)
    at com.google.android.gms.appindexing.Action.newAction(Unknown Source)
    at com.google.android.gms.appindexing.Action.newAction(Unknown Source)
    at com.example.mayankacharya.dataparsingtutorial.MapsActivity2.onStart(MapsActivity2.java:129)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
    at android.app.Activity.performStart(Activity.java:6253)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

    Reply
  6. Bhai my app is running fine but there is one problem that it is not drawing the path from source to destination.
    Please! Help.

    Reply
    • Hi @Eduardo Caballero and @Shubham

      April 3, 2016 at ,maybe you have not unable Map Distance API for your project check here Google API Console

      Reply
  7. Hi. grate tutorials!
    i have followed your code but i still get problem like this :

    1. the drawer map not appears
    2. The distance shown 0.0 meters
    3. The marker of destination not appears too.

    where i should set the destination latitude?. On your code just in button SET TO “toLatitude = latitude” it gives toLatitude = current position value. not my destination latitude.

    could you replay my problem and help me, please.

    Reply
  8. Hi i have a one doubt actually google maps user want to click the particular location how to display the that particular latitude and longitude display
    EX
    when I have click the Chennai means it display the latitude and longitude display not hard coded in the value for latitude and longitude how to implement it please help me…………

    Reply
  9. Hey, The app is working almost perfect, the only issue that I have is with the Drawing of the Map, it doesn’t do it.
    The distance is calculated correctly and everything, but the route it just doesn’t show up. Does anyone have this problem too?

    Reply
  10. SphericalUtil.computeDistanceBetween() is used to calculate STRAIGHT LINE distance between two latlng points.. it doesnt calculate actual path distance with legs and turns..however, direction API does return actual path distance in json format, u just need to parse that as well..

    Reply
  11. I am getting these errer :
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dipali.distancecalculationapp/com.example.dipali.distancecalculationapp.MapsActivity}: java.lang.IllegalArgumentException: AppIndex: The android-app URI host must match the package name and follow the format android-app:////. Provided URI: android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    What should i do?Can you please help

    Reply
  12. Polyline not showing on map – Everything else works great.

    Possible Error in Code “try {}”??

    I’ve applied my own API to build & in the code for “urlString.append” (used same API #)

    Program displays the “Toast” msg, goes to “try”, but never completes the “try”, so this is where the problem is,
    it does go into the “catch (JSONException e) {}”:
    Toast.makeText(this,String.valueOf(distance+” Meters”),Toast.LENGTH_SHORT).show();

    try {
    //Parsing json
    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray(“routes”);
    JSONObject routes = routeArray.getJSONObject(0);
    JSONObject overviewPolylines = routes.getJSONObject(“overview_polyline”);
    String encodedString = overviewPolylines.getString(“points”);
    List list = decodePoly(encodedString);
    Polyline line = mMap.addPolyline(new PolylineOptions()
    .addAll(list)
    .width(20)
    .color(Color.RED)
    .geodesic(true)
    );
    }
    catch (JSONException e) {
    }

    Any idea for why the “try{}” is not getting completed and kicks out the “catch () {}”?

    Thanks in advance…….

    P.S.
    Thanks for all your great Tutorials on Google API Maps…………

    Reply
  13. UPDATE – APP IS WORKING 100%

    Service Key Needed To Be Added.

    I seen your comment about the “Service Key” from Google API, but the documentation at Google’s site
    was unclear about how to obtain the Service Key, I had originally just used my API Key. Once I obtained the
    Sevice Key and replaced your Service Key with mine, the “Polyline” showed on the map.

    Thanks again for the tutorials, they’re great…………

    Reply
  14. why you use this
    //Calculating the distance in meters
    Double distance = SphericalUtil.computeDistanceBetween(from, to);
    the above line didn’t give you the exact distance…
    the easiest way is you can get the distance from the api JSON response…

    like this
    JSONArray routeArray = json.getJSONArray(“routes”);
    JSONObject routes = routeArray.getJSONObject(0);
    JSONArray legsArray = routes.getJSONArray(“legs”);
    JSONObject legs = legsArray.getJSONObject(0);
    JSONObject distanceObj = legs.getJSONObject(“distance”);

    //here is your distance
    String parsedDistance=distanceObj.getString(“text”);

    Reply
  15. Your Application is too much Best But I have a One Problem when I am run in my Phone not dragging direction show Set from to Set to .And I want to add search bar in Your Application . so Any user wants to search location one place to another easily. so Please Help me to do this .

    Reply
  16. hello sir,
    will you please provide a demo about finding near by places from current location ,like finding hotels near by current location , finding atm ,banks , theaters e.t.c

    Reply
  17. Friend good afternoon, look use part of your code and it worked well but I am returning the value of the distance as 8131698.5658 meters always, could you help me? thank you

    Reply

Leave a Comment