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.
- Now select your project and click on continue.
- Now go to New Credential and create a Server Key (I am assuming you already have the Android 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.
1 2 3 4 5 6 7 8 9 10 11 12 | dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.google.android.gms:play-services:8.3.0' compile 'com.google.maps.android:android-maps-utils:0.4+' compile 'com.mcxiaoke.volley:library-aar:1.0.0' } |
- Now come to activity_maps.xml and write the following code. It will create our layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <FrameLayout 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=".MapsActivity"> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedcoding.mymapapp.MapsActivity" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#cc3b60a7" android:orientation="horizontal"> <Button android:id="@+id/buttonSetFrom" android:text="Set From" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonSetTo" android:text="Set To" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonCalcDistance" android:text="Calc Distance" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> </FrameLayout> |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener{ //Our Map private GoogleMap mMap; //To store longitude and latitude from map private double longitude; private double latitude; //From -> the first coordinate from where we need to calculate the distance private double fromLongitude; private double fromLatitude; //To -> the second coordinate to where we need to calculate the distance private double toLongitude; private double toLatitude; //Google ApiClient private GoogleApiClient googleApiClient; //Our buttons private Button buttonSetTo; private Button buttonSetFrom; private Button buttonCalcDistance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); //Initializing googleapi client // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(AppIndex.API).build(); buttonSetTo = (Button) findViewById(R.id.buttonSetTo); buttonSetFrom = (Button) findViewById(R.id.buttonSetFrom); buttonCalcDistance = (Button) findViewById(R.id.buttonCalcDistance); buttonSetTo.setOnClickListener(this); buttonSetFrom.setOnClickListener(this); buttonCalcDistance.setOnClickListener(this); } @Override protected void onStart() { googleApiClient.connect(); super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Maps Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path") ); AppIndex.AppIndexApi.start(googleApiClient, viewAction); } @Override protected void onStop() { googleApiClient.disconnect(); super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Maps Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path") ); AppIndex.AppIndexApi.end(googleApiClient, viewAction); } //Getting current location private void getCurrentLocation() { mMap.clear(); //Creating a location object Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (location != null) { //Getting longitude and latitude longitude = location.getLongitude(); latitude = location.getLatitude(); //moving the map to location moveMap(); } } //Function to move the map private void moveMap() { //Creating a LatLng Object to store Coordinates LatLng latLng = new LatLng(latitude, longitude); //Adding marker to map mMap.addMarker(new MarkerOptions() .position(latLng) //setting position .draggable(true) //Making the marker draggable .title("Current Location")); //Adding a title //Moving the camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //Animating the camera mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng latLng = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.setOnMarkerDragListener(this); mMap.setOnMapLongClickListener(this); } @Override public void onConnected(Bundle bundle) { getCurrentLocation(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onMapLongClick(LatLng latLng) { //Clearing all the markers mMap.clear(); //Adding a new marker to the current pressed position mMap.addMarker(new MarkerOptions() .position(latLng) .draggable(true)); latitude = latLng.latitude; longitude = latLng.longitude; } @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { //Getting the coordinates latitude = marker.getPosition().latitude; longitude = marker.getPosition().longitude; //Moving the map moveMap(); } @Override public void onClick(View v) { if(v == buttonSetFrom){ fromLatitude = latitude; fromLongitude = longitude; Toast.makeText(this,"From set",Toast.LENGTH_SHORT).show(); } if(v == buttonSetTo){ toLatitude = latitude; toLongitude = longitude; Toast.makeText(this,"To set",Toast.LENGTH_SHORT).show(); } if(v == buttonCalcDistance){ //This method will show the distance and will also draw the path calculateDistance(); } } } |
- 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.
1 2 3 4 5 6 7 8 9 10 11 | //Getting both the coordinates LatLng from = new LatLng(fromLatitude,fromLongitude); LatLng to = new LatLng(toLatitude,toLongitude); //Calculating the distance in meters Double distance = SphericalUtil.computeDistanceBetween(from, to); //Displaying the distance Toast.makeText(this,String.valueOf(distance+" Meters"),Toast.LENGTH_SHORT).show(); |
- 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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){ StringBuilder urlString = new StringBuilder(); urlString.append("https://maps.googleapis.com/maps/api/directions/json"); urlString.append("?origin=");// from urlString.append(Double.toString(sourcelat)); urlString.append(","); urlString .append(Double.toString( sourcelog)); urlString.append("&destination=");// to urlString .append(Double.toString( destlat)); urlString.append(","); urlString.append(Double.toString(destlog)); urlString.append("&sensor=false&mode=driving&alternatives=true"); urlString.append("&key=SERVER-KEY"); return urlString.toString(); } |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | private void getDirection(){ //Getting the URL String url = makeURL(fromLatitude, fromLongitude, toLatitude, toLongitude); //Showing a dialog till we get the route final ProgressDialog loading = ProgressDialog.show(this, "Getting Route", "Please wait...", false, false); //Creating a string request StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { loading.dismiss(); //Calling the method drawPath to draw the path drawPath(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loading.dismiss(); } }); //Adding the request to request queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } |
- These two methods will draw the route on the map. I got this from Stack Overflow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | //The parameter is the server response public void drawPath(String result) { //Getting both the coordinates LatLng from = new LatLng(fromLatitude,fromLongitude); LatLng to = new LatLng(toLatitude,toLongitude); //Calculating the distance in meters Double distance = SphericalUtil.computeDistanceBetween(from, to); //Displaying the distance 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<LatLng> list = decodePoly(encodedString); Polyline line = mMap.addPolyline(new PolylineOptions() .addAll(list) .width(20) .color(Color.RED) .geodesic(true) ); } catch (JSONException e) { } } 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; } |
- The final code of our MapsActivity.java for this Google Maps Distance Calculator would be.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | package net.simplifiedcoding.googlemapsdistancecalc; import android.app.ProgressDialog; import android.graphics.Color; import android.location.Location; import android.net.Uri; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.maps.android.SphericalUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener{ //Our Map private GoogleMap mMap; //To store longitude and latitude from map private double longitude; private double latitude; //From -> the first coordinate from where we need to calculate the distance private double fromLongitude; private double fromLatitude; //To -> the second coordinate to where we need to calculate the distance private double toLongitude; private double toLatitude; //Google ApiClient private GoogleApiClient googleApiClient; //Our buttons private Button buttonSetTo; private Button buttonSetFrom; private Button buttonCalcDistance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); //Initializing googleapi client // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(AppIndex.API).build(); buttonSetTo = (Button) findViewById(R.id.buttonSetTo); buttonSetFrom = (Button) findViewById(R.id.buttonSetFrom); buttonCalcDistance = (Button) findViewById(R.id.buttonCalcDistance); buttonSetTo.setOnClickListener(this); buttonSetFrom.setOnClickListener(this); buttonCalcDistance.setOnClickListener(this); } @Override protected void onStart() { googleApiClient.connect(); super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Maps Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path") ); AppIndex.AppIndexApi.start(googleApiClient, viewAction); } @Override protected void onStop() { googleApiClient.disconnect(); super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Maps Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path") ); AppIndex.AppIndexApi.end(googleApiClient, viewAction); } //Getting current location private void getCurrentLocation() { mMap.clear(); //Creating a location object Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (location != null) { //Getting longitude and latitude longitude = location.getLongitude(); latitude = location.getLatitude(); //moving the map to location moveMap(); } } //Function to move the map private void moveMap() { //Creating a LatLng Object to store Coordinates LatLng latLng = new LatLng(latitude, longitude); //Adding marker to map mMap.addMarker(new MarkerOptions() .position(latLng) //setting position .draggable(true) //Making the marker draggable .title("Current Location")); //Adding a title //Moving the camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //Animating the camera mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){ StringBuilder urlString = new StringBuilder(); urlString.append("https://maps.googleapis.com/maps/api/directions/json"); urlString.append("?origin=");// from urlString.append(Double.toString(sourcelat)); urlString.append(","); urlString .append(Double.toString( sourcelog)); urlString.append("&destination=");// to urlString .append(Double.toString( destlat)); urlString.append(","); urlString.append(Double.toString(destlog)); urlString.append("&sensor=false&mode=driving&alternatives=true"); urlString.append("&key=SERVER-KEY"); return urlString.toString(); } private void getDirection(){ //Getting the URL String url = makeURL(fromLatitude, fromLongitude, toLatitude, toLongitude); //Showing a dialog till we get the route final ProgressDialog loading = ProgressDialog.show(this, "Getting Route", "Please wait...", false, false); //Creating a string request StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { loading.dismiss(); //Calling the method drawPath to draw the path drawPath(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loading.dismiss(); } }); //Adding the request to request queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } //The parameter is the server response public void drawPath(String result) { //Getting both the coordinates LatLng from = new LatLng(fromLatitude,fromLongitude); LatLng to = new LatLng(toLatitude,toLongitude); //Calculating the distance in meters Double distance = SphericalUtil.computeDistanceBetween(from, to); //Displaying the distance 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<LatLng> list = decodePoly(encodedString); Polyline line = mMap.addPolyline(new PolylineOptions() .addAll(list) .width(20) .color(Color.RED) .geodesic(true) ); } catch (JSONException e) { } } 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; } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng latLng = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.setOnMarkerDragListener(this); mMap.setOnMapLongClickListener(this); } @Override public void onConnected(Bundle bundle) { getCurrentLocation(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onMapLongClick(LatLng latLng) { //Clearing all the markers mMap.clear(); //Adding a new marker to the current pressed position mMap.addMarker(new MarkerOptions() .position(latLng) .draggable(true)); latitude = latLng.latitude; longitude = latLng.longitude; } @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { //Getting the coordinates latitude = marker.getPosition().latitude; longitude = marker.getPosition().longitude; //Moving the map moveMap(); } @Override public void onClick(View v) { if(v == buttonSetFrom){ fromLatitude = latitude; fromLongitude = longitude; Toast.makeText(this,"From set",Toast.LENGTH_SHORT).show(); } if(v == buttonSetTo){ toLatitude = latitude; toLongitude = longitude; Toast.makeText(this,"To set",Toast.LENGTH_SHORT).show(); } if(v == buttonCalcDistance){ getDirection(); } } } |
- Lastly for this Google Maps Distance Calculator you need to add the following permissions to your AndroidManifest.xml
1 2 3 4 5 | <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> |
- Now thats all, just run your Google Maps Distance Calculator(Use a real device).

- 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 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
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.
Oh that is generated automatically.. I just forget to remove it.. It will also work without that.. we need only to connect with the api with googleApiClient.connect(); on onStart and we are disconnecting it in on stop()..
check the previous tutorial
https://www.simplifiedcoding.net/android-google-maps-tutorial-google-maps-android-api/
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.
Check your coordinates are getting initialized properly or not.. you have to use the methods onMarkerDragStart and onMarkerDragEnd
So what should i have to write inside onMarkerDragStart().
I have the same problem can any body help us please ??
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.
thanks, let me try it now 🙂
when I run this app. App crash , no output show. what I do for this?
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?
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)
Bhai my app is running fine but there is one problem that it is not drawing the path from source to destination.
Please! Help.
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
Thank you for the actionable content. Very useful.
Great tutorial, Thank you..
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.
Thanks very much for the tutorial.
we want one program like etaxi
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…………
not functioning
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?
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..
polyline not working otherwise app working help me.. sir!
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
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…………
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…………
hello can i know how to obtain the service key?
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”);
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 .
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
thanks very much for these nice tutorials. keep it up
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