Advertisement
rachmadi

Waypoint

Jun 22nd, 2016
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.71 KB | None | 0 0
  1. package com.d4mdp.plesir.activity;
  2.  
  3. import android.Manifest;
  4. import android.content.pm.PackageManager;
  5. import android.graphics.Color;
  6. import android.os.AsyncTask;
  7. import android.os.Bundle;
  8. import android.support.v4.app.FragmentActivity;
  9. import android.util.Log;
  10.  
  11. import com.d4mdp.plesir.R;
  12. import com.d4mdp.plesir.util.DirectionsJSONParser;
  13. import com.google.android.gms.maps.CameraUpdateFactory;
  14. import com.google.android.gms.maps.GoogleMap;
  15. import com.google.android.gms.maps.SupportMapFragment;
  16. import com.google.android.gms.maps.model.LatLng;
  17. import com.google.android.gms.maps.model.MarkerOptions;
  18. import com.google.android.gms.maps.model.PolylineOptions;
  19.  
  20. import org.json.JSONObject;
  21.  
  22. import java.io.BufferedReader;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.InputStreamReader;
  26. import java.net.HttpURLConnection;
  27. import java.net.URL;
  28. import java.util.ArrayList;
  29. import java.util.HashMap;
  30. import java.util.List;
  31.  
  32. /**
  33.  * Created by Achmad Siddik on 18/04/2016.
  34.  */
  35. public class WayPointMapActivity extends FragmentActivity {
  36.     GoogleMap map;
  37.     public static ArrayList<HashMap<String,String>> markerPoints=new ArrayList<>();
  38.  
  39.     @Override
  40.     protected void onCreate(Bundle savedInstanceState) {
  41.         super.onCreate(savedInstanceState);
  42.         setContentView(R.layout.activity_maps);
  43.  
  44.         // Getting reference to SupportMapFragment of the activity_main
  45.         SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  46.         map = fm.getMap();
  47.  
  48.         map.setMyLocationEnabled(true);
  49.         addingMap();
  50.     }
  51.  
  52.     public void addingMap(){
  53.         if(markerPoints.size() >= 2){
  54.             double latitudeOrigin=Double.parseDouble(markerPoints.get(0).get("latitude"));
  55.             double longitudeOrigin=Double.parseDouble(markerPoints.get(0).get("longitude"));
  56.             LatLng origin = new LatLng(latitudeOrigin,longitudeOrigin);
  57.             double latitudeDest=Double.parseDouble(markerPoints.get(markerPoints.size()-1).get("latitude"));
  58.             double longitudeDest=Double.parseDouble(markerPoints.get(markerPoints.size()-1).get("longitude"));
  59.             LatLng dest = new LatLng(latitudeDest,longitudeDest);
  60.             MarkerOptions options=new MarkerOptions();
  61.             options.title(markerPoints.get(0).get("location_name"));
  62.             MarkerOptions options2=new MarkerOptions();
  63.             options2.title(markerPoints.get(markerPoints.size()-1).get("location_name"));
  64.             options.position(origin);
  65.             options2.position(dest);
  66.             map.addMarker(options);
  67.             map.addMarker(options2);
  68.             map.animateCamera(CameraUpdateFactory.newLatLngZoom(origin,13));
  69.             // Getting URL to the Google Directions API
  70.             String url = getDirectionsUrl(origin, dest);
  71.  
  72.             DownloadTask downloadTask = new DownloadTask();
  73.  
  74.             // Start downloading json data from Google Directions API
  75.             downloadTask.execute(url);
  76.         }
  77.     }
  78.  
  79.     private String getDirectionsUrl(LatLng origin,LatLng dest){
  80.  
  81.         // Origin of route
  82.         String str_origin = "origin="+origin.latitude+","+origin.longitude;
  83.  
  84.         // Destination of route
  85.         String str_dest = "destination="+dest.latitude+","+dest.longitude;
  86.  
  87.         // Sensor enabled
  88.         String sensor = "sensor=false";
  89.  
  90.         // Waypoints
  91.         String waypoints = "";
  92.         for(int i=1;i<markerPoints.size();i++){
  93.             HashMap<String,String> pecahData=markerPoints.get(i);
  94.             String getLocationName=pecahData.get("location_name");
  95.             double getLatitude=Double.parseDouble(pecahData.get("latitude"));
  96.             double getLongitude=Double.parseDouble(pecahData.get("longitude"));
  97.             MarkerOptions options=new MarkerOptions();
  98.             LatLng point  = new LatLng(getLatitude,getLongitude);
  99.             options.title(getLocationName);
  100.             options.position(point);
  101.             map.addMarker(options);
  102.  
  103.             if(i==1)
  104.                 waypoints = "waypoints=";
  105.             waypoints += point.latitude + "," + point.longitude + "|";
  106.         }
  107.  
  108.         // Building the parameters to the web service
  109.         String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
  110.  
  111.         // Output format
  112.         String output = "json";
  113.  
  114.         // Building the url to the web service
  115.         String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
  116.  
  117.         return url;
  118.     }
  119.  
  120.  
  121.     /** A method to download json data from url */
  122.     private String downloadUrl(String strUrl) throws IOException {
  123.         String data = "";
  124.         InputStream iStream = null;
  125.         HttpURLConnection urlConnection = null;
  126.         try{
  127.             URL url = new URL(strUrl);
  128.  
  129.             // Creating an http connection to communicate with url
  130.             urlConnection = (HttpURLConnection) url.openConnection();
  131.  
  132.             // Connecting to url
  133.             urlConnection.connect();
  134.  
  135.             // Reading data from url
  136.             iStream = urlConnection.getInputStream();
  137.  
  138.             BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  139.  
  140.             StringBuffer sb  = new StringBuffer();
  141.  
  142.             String line = "";
  143.             while( ( line = br.readLine())  != null){
  144.                 sb.append(line);
  145.             }
  146.  
  147.             data = sb.toString();
  148.  
  149.             br.close();
  150.  
  151.         }catch(Exception e){
  152.             Log.d("Exception while downloading url", e.toString());
  153.         }finally{
  154.             iStream.close();
  155.             urlConnection.disconnect();
  156.         }
  157.         return data;
  158.     }
  159.  
  160.     // Fetches data from url passed
  161.     private class DownloadTask extends AsyncTask<String, Void, String> {
  162.  
  163.         // Downloading data in non-ui thread
  164.         @Override
  165.         protected String doInBackground(String... url) {
  166.  
  167.             // For storing data from web service
  168.  
  169.             String data = "";
  170.  
  171.             try{
  172.                 // Fetching the data from web service
  173.                 data = downloadUrl(url[0]);
  174.             }catch(Exception e){
  175.                 Log.d("Background Task",e.toString());
  176.             }
  177.             return data;
  178.         }
  179.  
  180.         // Executes in UI thread, after the execution of
  181.         // doInBackground()
  182.         @Override
  183.         protected void onPostExecute(String result) {
  184.             super.onPostExecute(result);
  185.  
  186.             ParserTask parserTask = new ParserTask();
  187.  
  188.             // Invokes the thread for parsing the JSON data
  189.             parserTask.execute(result);
  190.         }
  191.     }
  192.  
  193.  
  194.     /** A class to parse the Google Places in JSON format */
  195.     private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
  196.  
  197.         // Parsing the data in non-ui thread
  198.         @Override
  199.         protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
  200.  
  201.             JSONObject jObject;
  202.             List<List<HashMap<String, String>>> routes = null;
  203.  
  204.             try{
  205.                 jObject = new JSONObject(jsonData[0]);
  206.                 DirectionsJSONParser parser = new DirectionsJSONParser();
  207.  
  208.                 // Starts parsing data
  209.                 routes = parser.parse(jObject);
  210.             }catch(Exception e){
  211.                 e.printStackTrace();
  212.             }
  213.             return routes;
  214.         }
  215.  
  216.         // Executes in UI thread, after the parsing process
  217.         @Override
  218.         protected void onPostExecute(List<List<HashMap<String, String>>> result) {
  219.  
  220.             ArrayList<LatLng> points = null;
  221.             PolylineOptions lineOptions = null;
  222.  
  223.             // Traversing through all the routes
  224.             for(int i=0;i<result.size();i++){
  225.                 points = new ArrayList<LatLng>();
  226.                 lineOptions = new PolylineOptions();
  227.  
  228.                 // Fetching i-th route
  229.                 List<HashMap<String, String>> path = result.get(i);
  230.  
  231.                 // Fetching all the points in i-th route
  232.                 for(int j=0;j<path.size();j++){
  233.                     HashMap<String,String> point = path.get(j);
  234.  
  235.                     double lat = Double.parseDouble(point.get("lat"));
  236.                     double lng = Double.parseDouble(point.get("lng"));
  237.                     LatLng position = new LatLng(lat, lng);
  238.  
  239.                     points.add(position);
  240.                 }
  241.  
  242.                 // Adding all the points in the route to LineOptions
  243.                 lineOptions.addAll(points);
  244.                 lineOptions.width(5);
  245.                 lineOptions.color(Color.RED);
  246.             }
  247.  
  248.             // Drawing polyline in the Google Map for the i-th route
  249.             map.addPolyline(lineOptions);
  250.         }
  251.     }
  252. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement