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.


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 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.

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,


public class Getdirection extends FragmentActivity {
   ListView map_list;
   GoogleMap map;
   ArrayList<LatLng> markerPoints;
   LatLng origin,dest;
   TextView distance,duration;
   Context context;
   protected void onCreate(Bundle savedInstanceState) {
      origin = new LatLng(Dec.my_lat,Dec.my_long);
      dest=new LatLng(Dec.item_lat, Dec.item_long);
      SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(;
      map = fm.getMap();    
       map.moveCamera(CameraUpdateFactory.newLatLngZoom(origin, 4));
       map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, 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)));
      String url = getDirectionsUrl(origin, dest);            
      Log.d("DIR URL", url);
      DownloadTask downloadTask = new DownloadTask();
   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 = ""+output+"?"+parameters;
      return url;
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
                URL url = new URL(strUrl);
                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();
                // Connecting to url 
                // 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){
                data = sb.toString();
        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        return data;
   // Fetches data from url passed
   private class DownloadTask extends AsyncTask<String, Void, String>{
      // Downloading data in non-ui thread
      protected String doInBackground(String... url) {
         // For storing data from web service
         String data = "";
            // 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()
      protected void onPostExecute(String result) {        
         ParserTask parserTask = new ParserTask();
         // Invokes the thread for parsing the JSON data
   /** 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       
      protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
         JSONObject jObject;    
         List<List<HashMap<String, String>>> routes = null;
               jObject = new JSONObject(jsonData[0]);
               DirectionsJSONParser parser = new DirectionsJSONParser();
               // Starts parsing data
               routes = parser.parse(jObject);    
            }catch(Exception e){
            return routes;
      // Executes in UI thread, after the parsing process
      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);
            // Adding all the points in the route to LineOptions
         // Drawing polyline in the Google Map for the i-th route
         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
         TextView txtcontent2=(TextView)convertView.findViewById(;
         TextView txttime=(TextView)convertView.findViewById(;
         return convertView;

Create another class
//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();
               jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
               /** Traversing all steps */
               for(int k=0;k<jSteps.length();k++){
                  String polyline = "";
                     String html=(String)(((JSONObject)jSteps.get(k)).get("html_instructions"));
                     Log.d("html_instructions", html);
                     Dec.html_instructions.add("no html");
                     Log.d("SIDE", "NO Side");
                     String side=(String)(((JSONObject)jSteps.get(k)).get("maneuver"));
                     Log.d("SIDE", side);
                     Dec.maneuver.add("No side");
                     Log.d("SIDE", "NO Side");
                  Log.d("DIS", (String)((JSONObject)((JSONObject)jSteps.get(k)).get("distance")).get("text"));
                  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) );
      } catch (JSONException e) {          
      }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)));

        return poly;

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>();


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


3 thoughts on - Get direction between two points google maps android

Leave a Reply

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