Advertisement
georgemathewk

Android Driving Route Directions - MainActivity.java

Sep 10th, 2013
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.82 KB | None | 0 0
  1. package in.wptrafficanalyzer.locationroutemylocationv2;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. import java.util.List;
  12.  
  13. import org.json.JSONObject;
  14.  
  15. import android.app.Dialog;
  16. import android.graphics.Color;
  17. import android.location.Criteria;
  18. import android.location.Location;
  19. import android.location.LocationListener;
  20. import android.location.LocationManager;
  21. import android.os.AsyncTask;
  22. import android.os.Bundle;
  23. import android.support.v4.app.FragmentActivity;
  24. import android.support.v4.app.FragmentManager;
  25. import android.util.Log;
  26. import android.view.Menu;
  27.  
  28. import com.google.android.gms.common.ConnectionResult;
  29. import com.google.android.gms.common.GooglePlayServicesUtil;
  30. import com.google.android.gms.maps.CameraUpdateFactory;
  31. import com.google.android.gms.maps.GoogleMap;
  32. import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
  33. import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
  34. import com.google.android.gms.maps.SupportMapFragment;
  35. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  36. import com.google.android.gms.maps.model.CameraPosition;
  37. import com.google.android.gms.maps.model.LatLng;
  38. import com.google.android.gms.maps.model.MarkerOptions;
  39. import com.google.android.gms.maps.model.PolylineOptions;
  40.  
  41.  
  42. public class MainActivity extends FragmentActivity implements LocationListener {
  43.  
  44.     GoogleMap mGoogleMap;
  45.     ArrayList<LatLng> mMarkerPoints;
  46.     double mLatitude=0;
  47.     double mLongitude=0;
  48.    
  49.     @Override
  50.     protected void onCreate(Bundle savedInstanceState) {
  51.         super.onCreate(savedInstanceState);
  52.         setContentView(R.layout.activity_main);
  53.        
  54.         // Getting Google Play availability status
  55.         int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
  56.  
  57.         if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
  58.  
  59.             int requestCode = 10;
  60.             Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
  61.             dialog.show();
  62.  
  63.         }else { // Google Play Services are available
  64.        
  65.             // Initializing
  66.             mMarkerPoints = new ArrayList<LatLng>();
  67.            
  68.             // Getting reference to SupportMapFragment of the activity_main
  69.             SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
  70.            
  71.             // Getting Map for the SupportMapFragment
  72.             mGoogleMap = fm.getMap();          
  73.            
  74.             // Enable MyLocation Button in the Map
  75.             mGoogleMap.setMyLocationEnabled(true);
  76.            
  77.            
  78.             // Getting LocationManager object from System Service LOCATION_SERVICE
  79.             LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  80.    
  81.             // Creating a criteria object to retrieve provider
  82.             Criteria criteria = new Criteria();
  83.    
  84.             // Getting the name of the best provider
  85.             String provider = locationManager.getBestProvider(criteria, true);
  86.    
  87.             // Getting Current Location From GPS
  88.             Location location = locationManager.getLastKnownLocation(provider);
  89.            
  90.             if(location!=null){
  91.                 onLocationChanged(location);
  92.             }
  93.  
  94.             locationManager.requestLocationUpdates(provider, 20000, 0, this);          
  95.            
  96.             // Setting onclick event listener for the map
  97.             mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
  98.                
  99.                 @Override
  100.                 public void onMapClick(LatLng point) {
  101.                    
  102.                     // Already map contain destination location
  103. //                  if(mMarkerPoints.size()>1){
  104. //                     
  105. //                      FragmentManager fm = getSupportFragmentManager();  
  106. //                      mMarkerPoints.clear();
  107. //                      mGoogleMap.clear();
  108. //                      LatLng startPoint = new LatLng(mLatitude, mLongitude);
  109. //                      drawMarker(startPoint);
  110. //                  }
  111.                    
  112.                     drawMarker(point);
  113.                    
  114.                     // Checks, whether start and end locations are captured
  115.                     if(mMarkerPoints.size() >= 2){                 
  116.                         LatLng origin = mMarkerPoints.get(0);
  117.                         LatLng dest = mMarkerPoints.get(mMarkerPoints.size()-1);
  118.                        
  119.                         // Getting URL to the Google Directions API
  120.                         String url = getDirectionsUrl(origin, dest);               
  121.                        
  122.                         DownloadTask downloadTask = new DownloadTask();
  123.                        
  124.                         // Start downloading json data from Google Directions API
  125.                         downloadTask.execute(url);
  126.                     }                  
  127.                 }
  128.             });        
  129.         }      
  130.     }
  131.    
  132.     private String getDirectionsUrl(LatLng origin,LatLng dest){
  133.                    
  134.         // Origin of route
  135.         String str_origin = "origin="+origin.latitude+","+origin.longitude;
  136.        
  137.         // Destination of route
  138.         String str_dest = "destination="+dest.latitude+","+dest.longitude;         
  139.                    
  140.         // Sensor enabled
  141.         String sensor = "sensor=false";        
  142.                    
  143.         // Building the parameters to the web service
  144.         String parameters = str_origin+"&"+str_dest+"&"+sensor;
  145.                    
  146.         // Output format
  147.         String output = "json";
  148.        
  149.         // Building the url to the web service
  150.         String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;     
  151.        
  152.         return url;
  153.     }
  154.    
  155.     /** A method to download json data from url */
  156.     private String downloadUrl(String strUrl) throws IOException{
  157.         String data = "";
  158.         InputStream iStream = null;
  159.         HttpURLConnection urlConnection = null;
  160.         try{
  161.                 URL url = new URL(strUrl);
  162.  
  163.                 // Creating an http connection to communicate with url
  164.                 urlConnection = (HttpURLConnection) url.openConnection();
  165.  
  166.                 // Connecting to url
  167.                 urlConnection.connect();
  168.  
  169.                 // Reading data from url
  170.                 iStream = urlConnection.getInputStream();
  171.  
  172.                 BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  173.  
  174.                 StringBuffer sb  = new StringBuffer();
  175.  
  176.                 String line = "";
  177.                 while( ( line = br.readLine())  != null){
  178.                         sb.append(line);
  179.                 }
  180.                
  181.                 data = sb.toString();
  182.  
  183.                 br.close();
  184.  
  185.         }catch(Exception e){
  186.                 Log.d("Exception while downloading url", e.toString());
  187.         }finally{
  188.                 iStream.close();
  189.                 urlConnection.disconnect();
  190.         }
  191.         return data;
  192.      }
  193.  
  194.    
  195.    
  196.     /** A class to download data from Google Directions URL */
  197.     private class DownloadTask extends AsyncTask<String, Void, String>{        
  198.                
  199.         // Downloading data in non-ui thread
  200.         @Override
  201.         protected String doInBackground(String... url) {
  202.                
  203.             // For storing data from web service
  204.             String data = "";
  205.                    
  206.             try{
  207.                 // Fetching the data from web service
  208.                 data = downloadUrl(url[0]);
  209.             }catch(Exception e){
  210.                 Log.d("Background Task",e.toString());
  211.             }
  212.             return data;       
  213.         }
  214.        
  215.         // Executes in UI thread, after the execution of
  216.         // doInBackground()
  217.         @Override
  218.         protected void onPostExecute(String result) {          
  219.             super.onPostExecute(result);       
  220.            
  221.                    
  222.             ParserTask parserTask = new ParserTask();
  223.            
  224.             // Invokes the thread for parsing the JSON data
  225.             parserTask.execute(result);
  226.                
  227.         }      
  228.     }
  229.    
  230.     /** A class to parse the Google Directions in JSON format */
  231.     private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
  232.        
  233.         // Parsing the data in non-ui thread       
  234.         @Override
  235.         protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
  236.            
  237.             JSONObject jObject;
  238.             List<List<HashMap<String, String>>> routes = null;                     
  239.            
  240.             try{
  241.                 jObject = new JSONObject(jsonData[0]);
  242.                 DirectionsJSONParser parser = new DirectionsJSONParser();
  243.                
  244.                 // Starts parsing data
  245.                 routes = parser.parse(jObject);    
  246.             }catch(Exception e){
  247.                 e.printStackTrace();
  248.             }
  249.             return routes;
  250.         }
  251.        
  252.         // Executes in UI thread, after the parsing process
  253.         @Override
  254.         protected void onPostExecute(List<List<HashMap<String, String>>> result) {
  255.             ArrayList<LatLng> points = null;
  256.             PolylineOptions lineOptions = null;
  257.            
  258.             // Traversing through all the routes
  259.             for(int i=0;i<result.size();i++){
  260.                 points = new ArrayList<LatLng>();
  261.                 lineOptions = new PolylineOptions();
  262.                
  263.                 // Fetching i-th route
  264.                 List<HashMap<String, String>> path = result.get(i);
  265.                
  266.                 // Fetching all the points in i-th route
  267.                 for(int j=0;j<path.size();j++){
  268.                     HashMap<String,String> point = path.get(j);                
  269.                    
  270.                     double lat = Double.parseDouble(point.get("lat"));
  271.                     double lng = Double.parseDouble(point.get("lng"));
  272.                     LatLng position = new LatLng(lat, lng);
  273.                    
  274.                     points.add(position);                      
  275.                 }
  276.                
  277.                 // Adding all the points in the route to LineOptions
  278.                 lineOptions.addAll(points);
  279.                 lineOptions.width(2);
  280.                 lineOptions.color(Color.RED);  
  281.                
  282.             }
  283.            
  284.             // Drawing polyline in the Google Map for the i-th route
  285.             mGoogleMap.addPolyline(lineOptions);                           
  286.         }          
  287.     }  
  288.    
  289.    
  290.     @Override
  291.     public boolean onCreateOptionsMenu(Menu menu) {
  292.         // Inflate the menu; this adds items to the action bar if it is present.
  293.         getMenuInflater().inflate(R.menu.main, menu);
  294.         return true;
  295.     }
  296.    
  297.     private void drawMarker(LatLng point){
  298.         mMarkerPoints.add(point);
  299.        
  300.         // Creating MarkerOptions
  301.         MarkerOptions options = new MarkerOptions();
  302.        
  303.         // Setting the position of the marker
  304.         options.position(point);
  305.        
  306.         /**
  307.          * For the start location, the color of marker is GREEN and
  308.          * for the end location, the color of marker is RED.
  309.          */
  310.         if(mMarkerPoints.size()==1){
  311.             options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
  312.         }else{
  313.             options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
  314.         }
  315.        
  316.         // Add new marker to the Google Map Android API V2
  317.         mGoogleMap.addMarker(options);     
  318.     }
  319.  
  320.     @Override
  321.     public void onLocationChanged(Location location) {
  322.         // Draw the marker, if destination location is not set
  323.         if(mMarkerPoints.size() < 2){
  324.            
  325.             mLatitude = location.getLatitude();
  326.             mLongitude = location.getLongitude();
  327.             LatLng point = new LatLng(mLatitude, mLongitude);
  328.    
  329.             mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
  330.             mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));        
  331.        
  332.             drawMarker(point);         
  333.         }
  334.        
  335.     }
  336.  
  337.     @Override
  338.     public void onProviderDisabled(String provider) {
  339.         // TODO Auto-generated method stub     
  340.     }
  341.  
  342.     @Override
  343.     public void onProviderEnabled(String provider) {
  344.         // TODO Auto-generated method stub     
  345.     }
  346.  
  347.     @Override
  348.     public void onStatusChanged(String provider, int status, Bundle extras) {
  349.         // TODO Auto-generated method stub     
  350.     }  
  351. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement