Route between two locations with waypoints in Google Map Android API V2

March 14, 2013
By

This article is an extension to the article titled “Drawing driving route directions between two locations using Google Directions in Google Map Android API V2“.



In this application, the first two touched positions in the Map is start point and end point respectively. Also user is allowed to input upto 8 waypoints which is the maximum limit allowed to the non-business users of the Google Map.

After entering the required waypoints, on clicking the button “Draw Route”, a route from start location to end location including the waypoints will be drawn in the Google Map Android API V2. A screenshot of the application is available in the Figure 7.

This application makes use of Google Map Android API V2 and Google Directions API.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) and tested in a real Android device (Android 2.3.6  -  GingerBread ).


1. Create a new Android application project namely “LocationWaypointMapV2″

Create new Android application project

Figure 1 : Create new Android application project


2. Configure the project

Configure the Android project

Figure 2 : Configure the Android project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity Details

Figure 5 : Enter MainActivity Details


6. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

Please follow the given below link to setup Google Play Service library in Eclipse.

http://developer.android.com/google/play-services/setup.html


7. Add Google Play Services Library to this project

Link Google Play Services Library

Figure 6 : Link Google Play Services Library


8. Get the API key for Google Maps Android API V2

We need to get an API key from Google to use Google Maps in Android application.

Please follow the given below link to get the API key for Google Maps Android API v2.

https://developers.google.com/maps/documentation/android/start


9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

10. Update the file res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocationWaypointMapV2</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="str_btn_draw">Draw Route</string>
</resources>


11. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_draw"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_draw"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <fragment
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/btn_draw" />

</RelativeLayout>


12. Create a new class namely “DirectionsJSONParser” in the file src/in/wptrafficanalyzer/locationwaypointmapv2/DirectionsJSONParser.java


package in.wptrafficanalyzer.locationwaypointmapv2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

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 path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        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;
    }

    /**
    * Method to decode polyline points
    * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
    * */
    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 & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                        (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}


13. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationwaypointmapv2/MainActivity.java


package in.wptrafficanalyzer.locationwaypointmapv2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap map;
    ArrayList<LatLng> markerPoints;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initializing
        markerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting reference to Button
        Button btnDraw = (Button)findViewById(R.id.btn_draw);

        // Getting Map for the SupportMapFragment
        map = fm.getMap();

        // Enable MyLocation Button in the Map
        map.setMyLocationEnabled(true);

        // Setting onclick event listener for the map
        map.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already 10 locations with 8 waypoints and 1 start location and 1 end location.
                // Upto 8 waypoints are allowed in a query for non-business users
                if(markerPoints.size()>=10){
                    return;
                }

                // Adding new item to the ArrayList
                markerPoints.add(point);

                // Creating MarkerOptions
                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker
                options.position(point);

                /**
                * For the start location, the color of marker is GREEN and
                * for the end location, the color of marker is RED and
                * for the rest of markers, the color is AZURE
                */
                if(markerPoints.size()==1){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                }else if(markerPoints.size()==2){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                }else{
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
                }

                // Add new marker to the Google Map Android API V2
                map.addMarker(options);
            }
        });

        // The map will be cleared on long click
        map.setOnMapLongClickListener(new OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng point) {
                // Removes all the points from Google Map
                map.clear();

                // Removes all the points in the ArrayList
                markerPoints.clear();
            }
        });

        // Click event handler for Button btn_draw
        btnDraw.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Checks, whether start and end locations are captured
                if(markerPoints.size() >= 2){
                    LatLng origin = markerPoints.get(0);
                    LatLng dest = markerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    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=false";

        // Waypoints
        String waypoints = "";
        for(int i=2;i<markerPoints.size();i++){
            LatLng point  = (LatLng) markerPoints.get(i);
            if(i==2)
                waypoints = "waypoints=";
            waypoints += point.latitude + "," + point.longitude + "|";
        }

        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;

        // 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;
    }

    /** A method to download json data from 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;

            // 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(2);
                lineOptions.color(Color.RED);
            }

             // Drawing polyline in the Google Map for the i-th route
             map.addPolyline(lineOptions);
         }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


14. Update the file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationwaypointmapv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <permission
        android:name="in.wptrafficanalyzer.locationwaypointmapv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="in.wptrafficanalyzer.locationwaypointmapv2.permission.MAPS_RECEIVE" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationwaypointmapv2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_ANDROID_API_KEY"/>

    </application>

</manifest>

Note :  Replace “YOUR_ANDROID_API_KEY” at the line 46 with the API key obtained in Step 8



15. Screenshot of the application

Route between two locations with waypoints in Google Map Android API V2

Figure 7 : Route between two locations with waypoints in Google Map Android API V2


16. Download Source Code


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , ,

53 Responses to Route between two locations with waypoints in Google Map Android API V2

  1. Basribaz on March 17, 2013 at 2:42 pm

    very nice tutorial, btw
    I want to create applications using the tourism point of a user’s location to the destination location by displaying the distance and travel time, can you help me, thanks for the help

  2. niks on March 19, 2013 at 4:56 pm

    Hello

    I found this tutorial nice. I need one help. I want to add polyline between two points but it should be not straight but should be look like arc like flight route. (it should be like arc for short distance line, i know .geodesic(true) but its only work for long distance polyline.) can you please help me on this.

  3. blue91 on April 23, 2013 at 9:20 am

    how can i create url for json data ? plz help me.

    • george on April 23, 2013 at 9:24 am

      Please see the method getDirectionsUrl() of the class MainActivity in the file src/in/wptrafficanalyzer/locationwaypointmapv2/MainActivity.java

  4. Balamurugan on April 24, 2013 at 4:10 pm

    Hai George

    am only able to create direction with only on straight line. but what i need is same output of yours.

    i downloaded your project.when i run your project it showing only map with current location marker point.draw route button is not working.path is not showing.only marker is been showned

  5. Balamurugan on April 24, 2013 at 4:13 pm

    am waiting for your reply

    • george on April 24, 2013 at 4:20 pm

      Please check your logcat to see any exceptions or error messages

  6. Vishnu on May 6, 2013 at 1:26 pm

    Great dude its working and return result so fa

  7. ANTONIO MANOEL DE OLIVEIRA on May 17, 2013 at 2:05 am

    Dear George

    I found it very interesting and instructive this Article. Congratulations.
    I have a question: please tell me how do I change the color of the line between two points. I tried to change them, but the last color remains for all lines of all points.
    Advance grateful.

  8. Vadorequest on May 23, 2013 at 8:12 pm

    Hi,
    Thx for the tuto, but, when I compile your sources, after add the lib google services, when the program start, fatal error:

    05-23 16:28:57.471: W/dalvikvm(9340): Unable to resolve superclass of Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity; (8)
    05-23 16:28:57.471: W/dalvikvm(9340): Link of class ‘Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity;’ failed
    05-23 16:28:57.471: D/AndroidRuntime(9340): Shutting down VM
    05-23 16:28:57.471: W/dalvikvm(9340): threadid=1: thread exiting with uncaught exception (group=0x40aac210)
    05-23 16:28:57.481: E/AndroidRuntime(9340): FATAL EXCEPTION: main
    05-23 16:28:57.481: E/AndroidRuntime(9340): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationwaypointmapv2/in.wptrafficanalyzer.locationwaypointmapv2.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.access$600(ActivityThread.java:127)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.os.Looper.loop(Looper.java:137)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.main(ActivityThread.java:4441)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.reflect.Method.invokeNative(Native Method)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.reflect.Method.invoke(Method.java:511)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at dalvik.system.NativeStart.main(Native Method)
    05-23 16:28:57.481: E/AndroidRuntime(9340): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
    05-23 16:28:57.481: E/AndroidRuntime(9340): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
    05-23 16:28:57.481: E/AndroidRuntime(9340): … 11 more
    05-23 16:30:38.409: W/dalvikvm(10070): Unable to resolve superclass of Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity; (8)
    05-23 16:30:38.409: W/dalvikvm(10070): Link of class ‘Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity;’ failed
    05-23 16:30:38.409: D/AndroidRuntime(10070): Shutting down VM
    05-23 16:30:38.409: W/dalvikvm(10070): threadid=1: thread exiting with uncaught exception (group=0x40aac210)
    05-23 16:30:38.459: E/AndroidRuntime(10070): FATAL EXCEPTION: main
    05-23 16:30:38.459: E/AndroidRuntime(10070): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationwaypointmapv2/in.wptrafficanalyzer.locationwaypointmapv2.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.access$600(ActivityThread.java:127)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.os.Looper.loop(Looper.java:137)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.main(ActivityThread.java:4441)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.reflect.Method.invokeNative(Native Method)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.reflect.Method.invoke(Method.java:511)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at dalvik.system.NativeStart.main(Native Method)
    05-23 16:30:38.459: E/AndroidRuntime(10070): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
    05-23 16:30:38.459: E/AndroidRuntime(10070): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
    05-23 16:30:38.459: E/AndroidRuntime(10070): … 11 more

    No error is displayed by the IDE (Eclipse ADT v22), all generated sources are available.
    I can’t test, but your source code is very useful, tanks !

  9. Andrei on June 15, 2013 at 7:57 pm

    Hi George!
    Great tutorial, thank you!
    I would like to ask you, if it is possible to add a static destination and calculate the rout from your current position(which is obtained via GPS) to the destination?
    If it is possible, could you please tell me where to set the coordinates of the destination and what coordinate form should i use.
    Thanks in advance!

  10. Samme on June 27, 2013 at 2:13 pm

    Hi George!
    Great tutorial, thank you!
    I want to say thank very much.
    Over many day i can’t do that, i was still got “Couldn’t get connection factory client” error

    then, i see your tutorial

  11. Ekkachai on July 9, 2013 at 6:10 pm

    hi! George,
    I want to create applications using the point first marker (Green marker) as a starting point, and show driving distance and travel time duration all point (all marker),can you please help me on this.

  12. Adrian on July 24, 2013 at 12:20 am

    Hi,
    this code is not working for me :(
    the only difference is that I have compiled with API 17, Android 4.2 and tested in a samsung galaxy note I (with 4.1.2 I think).

    My problem is to draw a route given a vector of waypoints. But I want to learn what are you doing.

    Congratulations for your nice work,
    thanks in advance,

    AdRi.

  13. Niko on September 23, 2013 at 8:39 pm

    Hi George,

    I’m working on a little school project, and I read your tutorial about the map fragment support last week, that’s great!
    Now I’d like to load a simple path froma a KML file on the map but I don’t know can I do it. I wrote a simple class following different tutorials but it doesn’t work. The KML file is in the SD-Card so it’s local.. I can parse it using a JSON script but I don’t know how to show it!

    Can you help me please?!

  14. robert on October 29, 2013 at 11:33 am

    George, can you give mevsome advice or tutorial about waypoints between two places from our coordinate in sqlite database..we choose them from two spinner..

  15. raj on January 31, 2014 at 2:41 pm

    The above demo didnt work for me.
    It ran into infinite loop in ParserTask.

  16. Menna Samy on February 5, 2014 at 2:51 pm

    It’s nice one and working well
    But I need an explanation for the parser and decodePoly functions

    Regards

  17. vivek kumar singh on February 7, 2014 at 11:06 am

    You Always work on Great Concept and write nice tutorial George…Tnks Bro

  18. MUzamil on April 28, 2014 at 4:20 pm

    Hi..Thanks ITs really Working for me

  19. Subhash Prajapati on September 2, 2014 at 12:19 pm

    hello,
    I try this but when i add a 20 or more waypoints then its show circular route at particular position.
    Is there any solution for this ????
    Thanksssss

  20. Mohit on September 22, 2014 at 1:35 pm

    Hi,

    can you tell me how to order the waypoints in the url parameters?

    Thanks.

  21. mukesh on October 8, 2014 at 5:29 pm

    please provide me information google maps when one point is movable and another is rest…

  22. Hemal Adani on November 6, 2014 at 5:56 pm

    Hello George: I am using this but at getSupportMapFragment. It shows error. It can’t that function on both cases. Can i use anything else?

    Regards,
    Hemal Adani

  23. cristopher on November 15, 2014 at 2:42 pm

    My friend
    Great tutorial, thank you!
    I want to say thank very much.
    I searched it for all sites and i needed it for my test of titulation to engineering of informatic

  24. Zhansaya on January 11, 2015 at 11:43 pm

    Hello, thanks for great tutorials. But problem is that i can not find any tutorial how to draw bus route((, exactly route of all buses in my city, i do not have any ideas how to implement that. Could you help me? I am new in android programming..

  25. Alleiny Machado on February 16, 2015 at 10:58 pm

    Thank you very much really helped me a lot…

  26. Alessia Miranda on February 18, 2015 at 10:17 pm

    Great tutorial but I have a question..
    If I want draw all point of waypoint passed through the URL, how I should change the class “DirectionsJSONParser” ?

    Thank you for your help.

  27. abhishek on April 3, 2015 at 1:03 pm

    Hi George
    Thanks for great tutorials.But plz tell me how to find shortest distance between two or more locations form my current location.
    Thank you

  28. bouazzi on April 25, 2015 at 8:58 am

    Could not find class ‘android.app.AppOpsManager ERROR ,i am working with android studio ,i tried the same code here but there is an error …PLZ help

  29. chandan nanda on June 3, 2015 at 12:57 pm

    well done george great tutorial thanks a lot. Dhanyabad(India)

  30. Sujith Kumar on June 15, 2015 at 5:58 pm

    Hi sir,
    can you please help me, how to move a car exactly on that routed map. Because my, my location blue button is not accurate.

  31. Kevin on July 10, 2015 at 5:52 pm

    Hi George,
    Thank you very much for this tutorial – really excellent!

  32. shuhaib on July 11, 2015 at 11:29 am

    I would like to retrieve between place as a Json format for particular application ? How can be done this ?

  33. devs on July 17, 2015 at 7:29 am

    Heya, Great tutorial but when i plot route on map, the route forms loop, as in the source and destination will get connected directly through another route also. Please help me out with it. Thank you for the amazing tutorial

  34. dikshay on July 23, 2015 at 5:03 pm

    can i set first two location according to my choice

  35. Ravikumar on August 12, 2015 at 8:37 pm

    Excellent ! Just a quick question… Can we make the route editable by dragging the route to pass through a different point?

    Your help will be highly appreciated !

    Many Thanks & Regards
    Ravi

  36. Amita on October 12, 2015 at 10:57 am

    best tutorial that found for android … good luck

  37. Amita Jain on October 15, 2015 at 6:22 pm

    Hello George,
    I want to ask you how to draw route on multiple location?
    like i have P1 to p2, p2 to p3 in this way i want to draw markers.
    p1 is my start and p2 is my detination
    again p2 is my start and p3 in my destination in continous manner.
    Hope to get your reply soon.
    Many Thanks and regards,
    Amita Jain

    • George Mathew on October 16, 2015 at 12:12 pm

      Hello Amita ,

      If my understanding about your question is correct, you can use p1 and p3 as source and destination respectively and p2 as a waypoint

  38. shyam on October 16, 2015 at 11:52 am

    In Android
    Draw an Infinite Route With Multiple Locations on Google Maps ?

  39. shyamjisaxena on October 16, 2015 at 12:30 pm

    how to draw infinite route with more than 10 locations on google map in android ?

    • George Mathew on October 16, 2015 at 5:36 pm

      Hello Shyam,

      May i know, what is meant by infinite route?

      • Shashank Bale on July 5, 2016 at 6:50 pm

        How to draw a path for More than 10 way points.

  40. Prasoon on October 23, 2015 at 12:24 am

    Hello George,
    this is really really a nice tutorial. as of now it is not working for me as i am using android studio and getting java.lang.RuntimeException: Unable to start activity ComponentInfo bascially error generated from setContentView(R.layout.activity_main);. I am trying to figure out the mistake. I am looking your suggestion, working on a project to find out the route names using starting and destination latitude & longitude. do we have any method which return names?
    Regards,
    Prasoon

  41. adil on October 23, 2015 at 3:11 pm

    please help me develop app in which user gave source and destination addresses and then click button to coloring line and marks between them.

  42. Amal on November 7, 2015 at 2:46 pm

    Hii sir

    How can we get distance and duration from way point

  43. Aastha on February 23, 2016 at 4:25 am

    - Draw route button is not displayed.
    - How can i add and source and destination

  44. Aastha on February 23, 2016 at 4:26 am

    - Draw route button is not displayed.

    HOw can I resolve this?

    //Aastha

  45. aazam on April 14, 2016 at 4:08 am

    i build this project and i got a R class error in my activity
    and i got error of MANIFEST MERGER

  46. Rocky on May 14, 2016 at 1:45 am

    Hola amigo.
    Gran tutorial pero una pregunta como puedo mas waypoints que sean como unos 18 o hasta 28 para poder hacer una ruta mas larga si me puedes ayudar ya que modifique el tamaño que pones en markerponit de 10 a 20 pero al momento de crear la ruta me cierra la aplicacion. gracias espero tu respuesta.

  47. Rocky on May 14, 2016 at 1:46 am

    Hello Friend.
    Great tutorial but a question like I can more waypoints that are as about 18 or even 28 to make a longer route if I can help as resize you put in markerponit 10 to 20 but when creating the route closes me the application. I hope your answer thanks .

Leave a Reply to devs Cancel reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner