Get direction between two points google maps android

The Google Directions API is a service that calculates directions between locations using an HTTP request. You can search for directions for several modes of transportation, include transit, driving, walking or cycling.

Directions may specify origins, destinations and way points either as text strings (e.g. “Chicago, IL” or “Darwin, NT, Australia”) or as latitude/longitude coordinates. The Directions API can return multi-part directions using a series of way points.

This service is generally designed for calculating directions for static (known in advance) addresses for placement of application content on a map. This service is not designed to respond in real time to user input, for example.

For dynamic directions calculations (for example, within a user interface element), consult the documentation for the JavaScript API V3 Directions Service.

Calculating directions is a time and resource intensive task. Whenever possible, calculate known addresses ahead of time (using the service described here) and store your results in a temporary cache of your own design.

API KEY

All Directions API applications should use an API key. Including a key in your request:

  • Allows you to monitor your application’s API usage in the APIs Console.
  • Enables per-key instead of per-IP-address quota limits.
  • Ensures that Google can contact you about your application if necessary.

The Directions API uses an API key to identify your application. API keys are managed through the Google APIs console. To create your key:

  1. Visit the APIs console at https://code.google.com/apis/console and log in to your Google Account.
  2. Click the Services link from the left-hand menu in the APIs Console, then activate the Directions API service.
  3. Once the service has been activated, your API key is available from the API Access page, in the Simple API Access section. Directions API applications use the Key for server apps.

To specify a key in your request, include it as the value of a key parameter.


Related Post

How to get current latitude and longitude in android example

Get current speed using GPS android

Google Places Autocomplete Android Example [Updated]


Usage Limits

The Directions API has the following limits in place.

Users of the free API

  • 2,500 directions requests per 24 hour period.
  • Up to 8 waypoints allowed in each request. Waypoints are not available for transit directions.
  • 10 requests per second.

Google Maps API for Business customers

  • 100,000 directions requests per 24 hour period.
  • 23 waypoints allowed in each request. Waypoints are not available for transit directions.
  • 10 requests per second.

Directions API URLs are restricted to approximately 2000 characters, after URL Encoding. As some Directions, API URLs may involve many locations along a path, be aware of this limit when constructing your URLs.

The Directions API may only be used in conjunction with displaying results on a Google map using Directions data without displaying a map for which directions data was requested is prohibited. Additionally, calculation of directions generates copyrights and warnings which must be displayed to the user in some fashion. For complete details on allowed usage, consult the Maps API Terms of Service License Restrictions.

 Example direction request

The below example direction request for Chennai to Mumbai. http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Munbai&sensor=false

Readmore: Get directions google maps android

Steps to Get direction between two points google maps

  • Create class extends FragmentActivity.
  • Create get two Latitude and Longitude variables that are origin and destination.
  • Generate URL for JSON parsing using origin and destination.
  • Parse needed values from the result.
  • Drew the path to the destination.
  • Add the markers to the needed places like origin and destinations.

Checkout my example,

Getdirection.Java

public class Getdirection extends FragmentActivity {
   
   ListView map_list;
   GoogleMap map;
   ArrayList<LatLng> markerPoints;
   LatLng origin,dest;
   TextView distance,duration;
   Context context;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(R.layout.activity_main);
      context=this;
      map_list=(ListView)findViewById(R.id.map_list);
      origin = new LatLng(Dec.my_lat,Dec.my_long);
      dest=new LatLng(Dec.item_lat, Dec.item_long);
      SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
      map = fm.getMap();    
       map.moveCamera(CameraUpdateFactory.newLatLngZoom(origin, 4));
       map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
      if(map!=null){
          map.addMarker(new MarkerOptions().position(origin).title("You're here") .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
          Marker marker= map.addMarker(new MarkerOptions().position(dest).title("Items location").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
          marker.showInfoWindow();
      }     
      String url = getDirectionsUrl(origin, dest);            
      Log.d("DIR URL", url);
      DownloadTask downloadTask = new DownloadTask();
      downloadTask.execute(url);
   }
   
   private String getDirectionsUrl(LatLng origin,LatLng dest){
      // Origin of route
      String str_origin = "origin="+origin.latitude+","+origin.longitude;
      // Destination of route
      String str_dest = "destination="+dest.latitude+","+dest.longitude;
      // Sensor enabled
      String sensor = "sensor=true";
      // Building the parameters to the web service
      String parameters = str_origin+"&amp;"+str_dest+"&amp;"+sensor;
      // Output format
      String 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);
                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();
                // Connecting to url 
                urlConnection.connect();
                // Reading data from url 
                iStream = urlConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                StringBuffer sb  = new StringBuffer();
                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }
                data = sb.toString();
                br.close();
        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }
        return data;
     }
   // Fetches data from url passed
   private class DownloadTask extends AsyncTask<String, Void, String>{
      // Downloading data in non-ui thread
      @Override
      protected String doInBackground(String... url) {
         // For storing data from web service
         String data = "";
         try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
         }catch(Exception e){
            Log.d("Background Task",e.toString());
         }
         return data;      
      }
      // Executes in UI thread, after the execution of
      // doInBackground()
      @Override
      protected void onPostExecute(String result) {        
         super.onPostExecute(result);
         ParserTask parserTask = new ParserTask();
         // Invokes the thread for parsing the JSON data
         parserTask.execute(result);
      }     
   }
   /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
       // Parsing the data in non-ui thread       
      @Override
      protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
         JSONObject jObject;    
         List<List<HashMap<String, String>>> routes = null;
            try{
               jObject = new JSONObject(jsonData[0]);
               DirectionsJSONParser parser = new DirectionsJSONParser();
               // Starts parsing data
               routes = parser.parse(jObject);    
            }catch(Exception e){
               e.printStackTrace();
            }
            return routes;
      }
      // Executes in UI thread, after the parsing process
      @Override
      protected void onPostExecute(List<List<HashMap<String, String>>> result) {
         ArrayList<LatLng> points = null;
         PolylineOptions lineOptions = null;
         MarkerOptions markerOptions = new MarkerOptions();
         // Traversing through all the routes
         for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();
            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);
            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
               HashMap<String,String> point = path.get(j);
               double lat = Double.parseDouble(point.get("lat"));
               double lng = Double.parseDouble(point.get("lng"));
               LatLng position = new LatLng(lat, lng);
               points.add(position);                 
            }
            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(5);
            lineOptions.color(Color.BLUE);
         }
         // Drawing polyline in the Google Map for the i-th route
         map.addPolyline(lineOptions);  
         for(int i=0;i<Dec.starting_lat.size();i++)
         {
            LatLng latlng=new LatLng(Dec.starting_lat.get(i), Dec.starting_long.get(i));
            map.addMarker(new MarkerOptions().position(latlng).title(Dec.html_instructions.get(i)) .icon(BitmapDescriptorFactory.defaultMarker()));
         }
         map_list.setAdapter(new dataListAdapter());
         Toast.makeText(context, Dec.distance, 4).show();
         Toast.makeText(context, Dec.duration, 4).show();
      }        
    }       
class dataListAdapter extends BaseAdapter {
      public dataListAdapter() {
      }
      public int getCount() {
         // TODO Auto-generated method stub
         return Dec.html_instructions.size();
      }
      public Object getItem(int arg0) {
         // TODO Auto-generated method stub
         return null;
      }
      public long getItemId(int position) {
         // TODO Auto-generated method stub
         return position;
      }
      public View getView(int position, View convertView, ViewGroup parent) {
         LayoutInflater inflater = getLayoutInflater();
         convertView = inflater.inflate(R.layout.path_adapter, parent, false);
         TextView txtcontent = (TextView) convertView
               .findViewById(R.id.place_name_tv);
         TextView txtcontent2=(TextView)convertView.findViewById(R.id.place_address_tv);
         TextView txttime=(TextView)convertView.findViewById(R.id.time);
         txtcontent.setText(Dec.html_instructions.get(position));
         txtcontent2.setText(Dec.maneuver.get(position));
         txttime.setText(Dec.dis.get(position)+Dec.dur.get(position));
         return convertView;
      }
   }
}

Create another class DirectionJSONparser.java
//Here you can parse all the values you need.

public class DirectionsJSONParser {
   /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
   public List<List<HashMap<String,String>>> parse(JSONObject jObject){
      List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
      JSONArray jRoutes = null;
      JSONArray jLegs = null;
      JSONArray jSteps = null;
      try {
         jRoutes = jObject.getJSONArray("routes");
         /** Traversing all routes */
         for(int i=0;i<jRoutes.length();i++){         
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
            /** Traversing all legs */
            for(int j=0;j<jLegs.length();j++){
               Dec.distance=((JSONObject) ((JSONObject)jLegs.get(j)).get("distance")).get("text").toString();
               Dec.duration=((JSONObject) ((JSONObject)jLegs.get(j)).get("duration")).get("text").toString();
               Log.d("Distance",Dec.distance.toString());
               jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
               /** Traversing all steps */
               for(int k=0;k<jSteps.length();k++){
                  String polyline = "";
                  if((boolean)(((JSONObject)jSteps.get(k)).has("html_instructions")))
                  {
                     String html=(String)(((JSONObject)jSteps.get(k)).get("html_instructions"));
                     html=html.replaceAll("\\<.*?>","");
                     Dec.html_instructions.add(html);
                     Log.d("html_instructions", html);
                  }
                  else
                  {
                     Dec.html_instructions.add("no html");
                     Log.d("SIDE", "NO Side");
                  }
                  if((boolean)(((JSONObject)jSteps.get(k)).has("maneuver")))
                  {
                     String side=(String)(((JSONObject)jSteps.get(k)).get("maneuver"));
                     Dec.maneuver.add(side);
                     Log.d("SIDE", side);
                  }
                  else
                  {
                     Dec.maneuver.add("No side");
                     Log.d("SIDE", "NO Side");
                  }
                  Dec.dis.add((String)((JSONObject)((JSONObject)jSteps.get(k)).get("distance")).get("text"));
                  Log.d("DIS", (String)((JSONObject)((JSONObject)jSteps.get(k)).get("distance")).get("text"));
                  Dec.dur.add((String)((JSONObject)((JSONObject)jSteps.get(k)).get("duration")).get("text"));
                  Dec.starting_lat.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("start_location")).get("lat"));
                  Dec.starting_long.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("start_location")).get("lng"));
                  Dec.ending_lat.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("end_location")).get("lat"));
                  Dec.ending_long.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("end_location")).get("lng"));
                  
                  polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                  List<LatLng> list = decodePoly(polyline);
                  /** Traversing all points */
                  for(int l=0;l<list.size();l++){
                     HashMap<String, String> hm = new HashMap<String, String>();
                     hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                     hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                     path.add(hm);                 
                  }                       
               }
               routes.add(path);
            }
         }
      } catch (JSONException e) {          
         e.printStackTrace();
      }catch (Exception e){        
      }
      return routes;
   }  

    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 &amp; 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result &amp; 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b &amp; 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result &amp; 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;
            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

Dec.java

public class Dec {
   static public String distance;
   static public String duration;
   static public double my_lat=13.0685875;
   static public double my_long=80.2582827;
   static public double item_lat=13.064704;
   static public double item_long=80.266145;
   static public ArrayList<String> html_instructions=new ArrayList<String>();
   static public double last_lat;
   static public double last_long;
   static public ArrayList<String> maneuver=new ArrayList<String>();
   static public ArrayList<String> dis=new ArrayList<String>();
   static public ArrayList<String> dur=new ArrayList<String>();
   static public ArrayList<Double> starting_lat=new ArrayList<Double>();
   static public ArrayList<Double> starting_long=new ArrayList<Double>();
   static public ArrayList<Double> ending_lat=new ArrayList<Double>();
   static public ArrayList<Double> ending_long=new ArrayList<Double>();
   
}

Conclusion

I hop, This example help you to implement the direction between two points. Thanks for the reading. Conclusion

Download

3 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top