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.
[sociallocker id=1372] Google Maps Distance Calculator[/sociallocker]
[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 🙂