andyshon

Android Google Map – Drawing Route Between two points

Oct 13th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.64 KB | None | 0 0
  1. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
  2.  
  3.     private GoogleMap mMap;
  4.     ArrayList markerPoints= new ArrayList();
  5.  
  6.     @Override
  7.     protected void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.activity_maps);
  10.         // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  11.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  12.                 .findFragmentById(R.id.map);
  13.         mapFragment.getMapAsync(this);
  14.     }
  15.  
  16.     @Override
  17.     public void onMapReady(GoogleMap googleMap) {
  18.         mMap = googleMap;
  19.         LatLng sydney = new LatLng(-34, 151);
  20.         //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
  21.         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));
  22.  
  23.         mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
  24.             @Override
  25.             public void onMapClick(LatLng latLng) {
  26.  
  27.                 if (markerPoints.size() > 1) {
  28.                     markerPoints.clear();
  29.                     mMap.clear();
  30.                 }
  31.  
  32.                 // Adding new item to the ArrayList
  33.                 markerPoints.add(latLng);
  34.  
  35.                 // Creating MarkerOptions
  36.                 MarkerOptions options = new MarkerOptions();
  37.  
  38.                 // Setting the position of the marker
  39.                 options.position(latLng);
  40.  
  41.                 if (markerPoints.size() == 1) {
  42.                     options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
  43.                 } else if (markerPoints.size() == 2) {
  44.                     options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
  45.                 }
  46.  
  47.                 // Add new marker to the Google Map Android API V2
  48.                 mMap.addMarker(options);
  49.  
  50.                 // Checks, whether start and end locations are captured
  51.                 if (markerPoints.size() >= 2) {
  52.                     LatLng origin = (LatLng) markerPoints.get(0);
  53.                     LatLng dest = (LatLng) markerPoints.get(1);
  54.  
  55.                     // Getting URL to the Google Directions API
  56.                     String url = getDirectionsUrl(origin, dest);
  57.  
  58.                     DownloadTask downloadTask = new DownloadTask();
  59.  
  60.                     // Start downloading json data from Google Directions API
  61.                     downloadTask.execute(url);
  62.                 }
  63.  
  64.             }
  65.         });
  66.  
  67.     }
  68.  
  69.     private class DownloadTask extends AsyncTask {
  70.  
  71.         @Override
  72.         protected String doInBackground(String... url) {
  73.  
  74.             String data = "";
  75.  
  76.             try {
  77.                 data = downloadUrl(url[0]);
  78.             } catch (Exception e) {
  79.                 Log.d("Background Task", e.toString());
  80.             }
  81.             return data;
  82.         }
  83.  
  84.         @Override
  85.         protected void onPostExecute(String result) {
  86.             super.onPostExecute(result);
  87.  
  88.             ParserTask parserTask = new ParserTask();
  89.  
  90.  
  91.             parserTask.execute(result);
  92.  
  93.         }
  94.     }
  95.  
  96.     private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap>>> {
  97.  
  98.         // Parsing the data in non-ui thread
  99.         @Override
  100.         protected List<List<HashMap>> doInBackground(String... jsonData) {
  101.  
  102.             JSONObject jObject;
  103.             List<List<HashMap>> routes = null;
  104.  
  105.             try {
  106.                 jObject = new JSONObject(jsonData[0]);
  107.                 DirectionsJSONParser parser = new DirectionsJSONParser();
  108.  
  109.                 routes = parser.parse(jObject);
  110.             } catch (Exception e) {
  111.                 e.printStackTrace();
  112.             }
  113.             return routes;
  114.         }
  115.  
  116.         @Override
  117.         protected void onPostExecute(List<List<HashMap>> result) {
  118.             ArrayList points = null;
  119.             PolylineOptions lineOptions = null;
  120.             MarkerOptions markerOptions = new MarkerOptions();
  121.  
  122.             for (int i = 0; i < result.size(); i++) {
  123.                 points = new ArrayList();
  124.                 lineOptions = new PolylineOptions();
  125.  
  126.                 List<HashMap> path = result.get(i);
  127.  
  128.                 for (int j = 0; j < path.size(); j++) {
  129.                     HashMap point = path.get(j);
  130.  
  131.                     double lat = Double.parseDouble(point.get("lat"));
  132.                     double lng = Double.parseDouble(point.get("lng"));
  133.                     LatLng position = new LatLng(lat, lng);
  134.  
  135.                     points.add(position);
  136.                 }
  137.  
  138.                 lineOptions.addAll(points);
  139.                 lineOptions.width(12);
  140.                 lineOptions.color(Color.RED);
  141.                 lineOptions.geodesic(true);
  142.  
  143.             }
  144.  
  145. // Drawing polyline in the Google Map for the i-th route
  146.             mMap.addPolyline(lineOptions);
  147.         }
  148.     }
  149.  
  150.     private String getDirectionsUrl(LatLng origin, LatLng dest) {
  151.  
  152.         // Origin of route
  153.         String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
  154.  
  155.         // Destination of route
  156.         String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
  157.  
  158.         // Sensor enabled
  159.         String sensor = "sensor=false";
  160.         String mode = "mode=driving";
  161.  
  162.         // Building the parameters to the web service
  163.         String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
  164.  
  165.         // Output format
  166.         String output = "json";
  167.  
  168.         // Building the url to the web service
  169.         String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
  170.        
  171.  
  172.         return url;
  173.     }
  174.  
  175.     private String downloadUrl(String strUrl) throws IOException {
  176.         String data = "";
  177.         InputStream iStream = null;
  178.         HttpURLConnection urlConnection = null;
  179.         try {
  180.             URL url = new URL(strUrl);
  181.  
  182.             urlConnection = (HttpURLConnection) url.openConnection();
  183.  
  184.             urlConnection.connect();
  185.  
  186.             iStream = urlConnection.getInputStream();
  187.  
  188.             BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  189.  
  190.             StringBuffer sb = new StringBuffer();
  191.  
  192.             String line = "";
  193.             while ((line = br.readLine()) != null) {
  194.                 sb.append(line);
  195.             }
  196.  
  197.             data = sb.toString();
  198.  
  199.             br.close();
  200.  
  201.         } catch (Exception e) {
  202.             Log.d("Exception", e.toString());
  203.         } finally {
  204.             iStream.close();
  205.             urlConnection.disconnect();
  206.         }
  207.         return data;
  208.     }
  209. }
Add Comment
Please, Sign In to add comment