Driving direction between two locations in Android

Here, I am explaining the driving direction between two locations in google map. It is an utility function. Here we are passing two locations to a method called "showMapFromLocation", first convert the location to corresponding latitude and longitude. Then using launch google map using intent. Here I just hard coded the package and launcher activity of google map. It is better to check the application (google map) is already there in the device using packagemanager.

The utility function is as follows,

 private void showMapFromLocation(String src, String dest) {  
           double srcLat = 0, srcLng = 0, destLat = 0, destLng = 0;  
           Geocoder geocoder = new Geocoder(this, Locale.getDefault());  
           try {  
                if (isOnline()) {  
                     List<Address> srcAddresses = geocoder.getFromLocationName(src,  
                     if (srcAddresses.size() > 0) {  
                          Address location = srcAddresses.get(0);  
                          srcLat = location.getLatitude();  
                          srcLng = location.getLongitude();  
                     List<Address> destAddresses = geocoder.getFromLocationName(  
                               dest, 1);  
                     if (destAddresses.size() > 0) {  
                          Address location = destAddresses.get(0);  
                          destLat = location.getLatitude();  
                          destLng = location.getLongitude();  
                     String desLocation = "&daddr=" + Double.toString(destLat) + ","  
                               + Double.toString(destLng);  
                     String currLocation = "saddr=" + Double.toString(srcLat) + ","  
                               + Double.toString(srcLng);  
                     // "d" means driving car, "w" means walking "r" means by bus  
                     Intent intent = new Intent(android.content.Intent.ACTION_VIEW,  
                               Uri.parse("http://maps.google.com/maps?" + currLocation  
                                         + desLocation + "&dirflg=d"));  
                               & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);  
           } catch (IOException e) {  
                Log.e(TAG, "Error when showing google map directions, E: " + e);  
           } catch (Exception e) {  
                Log.e(TAG, "Error when showing google map directions, E: " + e);  

We can select which mode of driving direction we need according to the flag "dirflg".
    - dirflg = d, means driving by car
    - dirflg = w, means by walking and
    - dirflg = r, means by bus

The screenshots are like,

One last thing is we have to add google play services library to show the google maps.


Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android