banner



How To Draw Distance On Google Maps

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

Android Google Map – Drawing Route

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

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

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

Android Google Maps Drawing Path Project Construction

drawing path between two points in google maps android

The DirectionsJSONParser.java file is the one that parses the locations and returns the route. decodePoly() method is so invoked to get the polyline information that's later drawn on the map.

Android Google Maps Drawing Route Code

The MainActivity.coffee code is given below.

                                  public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {      private GoogleMap mMap;     ArrayList markerPoints= new ArrayList();      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_maps);         // Obtain the SupportMapFragment and become notified when the map is ready to be used.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()                 .findFragmentById(R.id.map);         mapFragment.getMapAsync(this);     }      @Override     public void onMapReady(GoogleMap googleMap) {         mMap = googleMap;         LatLng sydney = new LatLng(-34, 151);         //mMap.addMarker(new MarkerOptions().position(sydney).title("Marking in Sydney"));         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, xvi));          mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {             @Override             public void onMapClick(LatLng latLng) {                  if (markerPoints.size() > 1) {                     markerPoints.clear();                     mMap.articulate();                 }                  // Adding new item to the ArrayList                 markerPoints.add(latLng);                  // Creating MarkerOptions                 MarkerOptions options = new MarkerOptions();                  // Setting the position of the mark                 options.position(latLng);                  if (markerPoints.size() == 1) {                     options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));                 } else if (markerPoints.size() == ii) {                     options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));                 }                  // Add new marking to the Google Map Android API V2                 mMap.addMarker(options);                  // Checks, whether start and end locations are captured                 if (markerPoints.size() >= 2) {                     LatLng origin = (LatLng) markerPoints.become(0);                     LatLng dest = (LatLng) markerPoints.get(1);                      // Getting URL to the Google Directions API                     String url = getDirectionsUrl(origin, dest);                      DownloadTask downloadTask = new DownloadTask();                      // Start downloading json information from Google Directions API                     downloadTask.execute(url);                 }              }         });      }      individual class DownloadTask extends AsyncTask {          @Override         protected String doInBackground(String... url) {              String data = "";              attempt {                 data = downloadUrl(url[0]);             } catch (Exception due east) {                 Log.d("Background Task", e.toString());             }             return data;         }          @Override         protected void onPostExecute(String result) {             super.onPostExecute(outcome);              ParserTask parserTask = new ParserTask();               parserTask.execute(effect);          }     }      private class ParserTask extends AsyncTask<String, Integer, List<Listing<HashMap>>> {          // Parsing the information in not-ui thread         @Override         protected List<List<HashMap>> doInBackground(String... jsonData) {              JSONObject jObject;             List<List<HashMap>> routes = null;              attempt {                 jObject = new JSONObject(jsonData[0]);                 DirectionsJSONParser parser = new DirectionsJSONParser();                  routes = parser.parse(jObject);             } grab (Exception e) {                 e.printStackTrace();             }             render routes;         }          @Override         protected void onPostExecute(Listing<Listing<HashMap>> result) {             ArrayList points = null;             PolylineOptions lineOptions = null;             MarkerOptions markerOptions = new MarkerOptions();              for (int i = 0; i < result.size(); i++) {                 points = new ArrayList();                 lineOptions = new PolylineOptions();                  Listing<HashMap> path = result.get(i);                  for (int j = 0; j < path.size(); j++) {                     HashMap point = path.go(j);                      double lat = Double.parseDouble(point.get("lat"));                     double lng = Double.parseDouble(point.get("lng"));                     LatLng position = new LatLng(lat, lng);                      points.add(position);                 }                  lineOptions.addAll(points);                 lineOptions.width(12);                 lineOptions.color(Color.RED);                 lineOptions.geodesic(true);              }  // Drawing polyline in the Google Map for the i-th route             mMap.addPolyline(lineOptions);         }     }      private String getDirectionsUrl(LatLng origin, LatLng dest) {          // Origin of route         String str_origin = "origin=" + origin.breadth + "," + origin.longitude;          // Destination of road         Cord str_dest = "destination=" + dest.latitude + "," + dest.longitude;          // Sensor enabled         String sensor = "sensor=false";         Cord mode = "mode=driving";          // Building the parameters to the web service         String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;          // Output format         Cord output = "json";          // Building the url to the web service         String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;                   return url;     }      private String downloadUrl(String strUrl) throws IOException {         String data = "";         InputStream iStream = null;         HttpURLConnection urlConnection = null;         try {             URL url = new URL(strUrl);              urlConnection = (HttpURLConnection) url.openConnection();              urlConnection.connect();              iStream = urlConnection.getInputStream();              BufferedReader br = new BufferedReader(new InputStreamReader(iStream));              StringBuffer sb = new StringBuffer();              String line = "";             while ((line = br.readLine()) != zippo) {                 sb.suspend(line);             }              data = sb.toString();              br.close();          } catch (Exception due east) {             Log.d("Exception", due east.toString());         } finally {             iStream.close();             urlConnection.disconnect();         }         render data;     } }                              

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

"https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

The output variable holds a "json" string and the parameter string is created as:
Cord parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + manner;

Nosotros've set up the mode=driving in the current application.
The other modes of transport are:

  • driving (default)
  • walking
  • bicycling
  • transit

The output of the application is given below:

android google maps draw path

This brings an finish to this tutorial. You tin can download the final project from the link beneath, add your own Google Map API cardinal.

Source: https://www.journaldev.com/13373/android-google-map-drawing-route-two-points

Posted by: tranwastookey.blogspot.com

0 Response to "How To Draw Distance On Google Maps"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel