Driving route from my location to destination in Google Maps Android API V2

May 10, 2013
By

In this article, we will develop an Android application which demonstrates how to draw a driving route from my location ( current location ) to a destination location in Google Maps Android API V2.



On taping a location in the Google Maps, a driving route will be drawn from my current location to the taped location. The route direction is obtained from 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 device (Android 2.3.6  -  GingerBread ).



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

Create new Android application Project

Figure 1 : Create new Android application Project


2. Configure the project

Configure the application project

Figure 2 : Configure the application 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

Note : Please ensure that, the latest version of Google Play Service Library is installed


7. Add Google Play Services Library to this project

Link Google Play Services library to this project

Figure 6 : Link Google Play Services library to this project


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

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

</RelativeLayout>


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


package in.wptrafficanalyzer.locationroutedirectionmapv2;

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


12. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationroutemylocationv2/MainActivity.java


package in.wptrafficanalyzer.locationroutemylocationv2;

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.app.Dialog;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Menu;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
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 implements LocationListener {

    GoogleMap mGoogleMap;
    ArrayList<LatLng> mMarkerPoints;
    double mLatitude=0;
    double mLongitude=0;

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

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

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

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

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

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

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);

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

                @Override
                public void onMapClick(LatLng point) {

                    // Already map contain destination location
                    if(mMarkerPoints.size()>1){

                        FragmentManager fm = getSupportFragmentManager();
                        mMarkerPoints.clear();
                        mGoogleMap.clear();
                        LatLng startPoint = new LatLng(mLatitude, mLongitude);

                        // draw the marker at the current position
                        drawMarker(startPoint);
                    }

                    // draws the marker at the currently touched location
                    drawMarker(point);

                    // Checks, whether start and end locations are captured
                    if(mMarkerPoints.size() >= 2){
                        LatLng origin = mMarkerPoints.get(0);
                        LatLng dest = mMarkerPoints.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";

        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+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;
    }

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

    /** A class to download data from Google Directions URL */
    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 Directions 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
            mGoogleMap.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;
    }

    private void drawMarker(LatLng point){
        mMarkerPoints.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.
        */
        if(mMarkerPoints.size()==1){
            options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        }else if(mMarkerPoints.size()==2){
            options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }

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

    @Override
    public void onLocationChanged(Location location) {
        // Draw the marker, if destination location is not set
        if(mMarkerPoints.size() < 2){

            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            LatLng point = new LatLng(mLatitude, mLongitude);

            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
            mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

            drawMarker(point);
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}


13. 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.locationroutemylocationv2"
    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.locationroutemylocationv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="in.wptrafficanalyzer.locationroutemylocationv2.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.locationroutemylocationv2.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 : Please ensure that “YOUR_ANDROID_API_KEY” at line 46 is replaced with the api key obtained in Step 8.


14. Screenshot of the application

Showing route from my location to a destination location

Figure 7 : Showing route from my location to a destination location


15. 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: , , , , , , ,

66 Responses to Driving route from my location to destination in Google Maps Android API V2

  1. ages on May 11, 2013 at 11:57 am

    hii george :)
    thanks for your tutorial, it’s very help me,
    but i want to ask question,
    how to add custom marked manualy, i try to input mw custom marked but after twice we tab, the custom marked has gone,
    this my custom source:

    static final LatLng PBS = new LatLng(5.175783,97.140950);
    static final LatLng PC = new LatLng(5.172767,97.131161);
    static final LatLng PM2 = new LatLng(5.163928,97.136822);
    static final LatLng PL = new LatLng(5.180353,97.122297);
    ……
    Marker pbs= mGoogleMap.addMarker(new MarkerOptions()
    .position(PBS)
    .title(“Polsek Banda Sakti”)
    .snippet(“Kantor Polisi Banda Sakti”)
    .icon(BitmapDescriptorFactory
    .fromResource(R.drawable.marker)));

    Marker pbs= mGoogleMap.addMarker(new MarkerOptions()
    .position(PBS)
    .title(“Polsek Banda Sakti”)
    .snippet(“Kantor Polisi Banda Sakti”)
    .icon(BitmapDescriptorFactory
    .fromResource(R.drawable.marker)));

    Marker pc = mGoogleMap.addMarker(new MarkerOptions()
    .position(PC)
    .title(“Polantas Cunda”)
    .snippet(“Kantor Polisi Lalu Lintas”)
    .icon(BitmapDescriptorFactory
    .fromResource(R.drawable.marker)));

    Marker pm2 = mGoogleMap.addMarker(new MarkerOptions()
    .position(PM2)
    .title(“Polsek Muara 2″)
    .snippet(“Kantor Polisi Muara 2″)
    .icon(BitmapDescriptorFactory
    .fromResource(R.drawable.marker)));

    Marker pl = mGoogleMap.addMarker(new MarkerOptions()
    .position(PL)
    .title(“Polres Lhokseumawe”)
    .snippet(“Kantor Polisi Pusat Lhokseumawe”)
    .icon(BitmapDescriptorFactory
    .fromResource(R.drawable.marker)));

  2. wandi on May 12, 2013 at 5:05 pm

    how to makeDriving route from my location to multiple destinations in Google Maps API V2 Android, remains his goal made ​​in a list view

  3. ages on May 13, 2013 at 5:34 am

    hi george,,
    can you help me how to draw a driving route from my location ( current location ) to a some locations which we manually enter in the program, so when we taped a marked location, a driving route will be drawn from my current location to the marked location, but the marked location not just one,
    pliss help me :(

    • js on May 27, 2013 at 7:14 pm

      hi ages,
      will you have any solution about the project above? Can I ask some programming about this project?

  4. Scott E. Smith on May 17, 2013 at 9:15 am

    Is getting the Google Maps API Key as crazy complicated as it sounds (to a noob), got your code loaded and compiled OK, but it dies. I put a breakpoint at setContentView of activity_main and it dies on first step (F6) – LayoutInflater Class I can’t help thinking the Maps API key isn’t right though, The Google API’s Console didn’t seam like it had any finality to it and I didn’t see a real relationship to my package “com.virtualbs.directions_loc_v2″ for the key ????

  5. Adeel Ehsan on May 21, 2013 at 6:43 pm

    I run this code but i am getting error
    here Is LogCat Error…..!!
    FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.locationroutedirectionmapv2/com.exapmle.locationroutedirectionmapv2.MainActivity}: java.lang.ClassNotFoundException: Didn’t find class “com.exapmle.locationroutedirectionmapv2.MainActivity” on path: /data/app/com.example.locationroutedirectionmapv2-1.apk

    Plz tell me where i am doing mistake

    • David Ladapo on June 28, 2013 at 10:22 pm

      Check your manifest file and check to see that google play is installed. Also ensure you have a google maps key

      • GG on July 4, 2013 at 2:49 am

        I am facing similar issue. I have google play installed else it would not compile. I have key as well. Do I need to have different key for different projects? Still I am getting same error. I know there is some basic mistake. I am new and thus trying to learn. Any pointers where I might be going wrong?

        • amateur on July 17, 2013 at 1:51 pm

          one key for one package…
          you can use key in many projects, but make sure the projects has same package name

          try make your own new project from this tutorial

  6. dom on June 8, 2013 at 12:33 pm

    it is possible to get driving directions depends on my marker. which i have added in map..?? in sort custom deriving directions???

  7. malindu on June 15, 2013 at 10:38 am

    Hi,
    This is excellent.
    So, I store more latitude and longitude value in mysql database,I got that value into an app using the json array code same as : http://stackoverflow.com/questions/17067018/android-search-in-listview-using-baseadapter?noredirect=1#comment24681010_17067018 ,
    My problem is How it Map on google map v2 ????

    Help me !!
    Thanks

  8. bak change seon on July 4, 2013 at 1:39 pm

    Hi,
    I am from Korea.
    it didn’t work.
    it is below.
    https://maps.googleapis.com/maps/api/directions/jason&orgin=location&destination&region=kr&sensor=false

    please help me.
    teach me url address in korea.

  9. Andre on July 8, 2013 at 5:58 pm

    Hello, I would like to know how can I be the first point my location. thank you

    • george on July 8, 2013 at 6:12 pm

      Hi,
      In this application, the first point is always my location.

  10. newbie on July 17, 2013 at 2:04 pm

    Hi, George…
    Thanks for the tutorial :D

    I have problem with the first point, its was not my current location, the first point still declared on Map Click..
    And when i moving the device, the route didn’t follow my current location..

    What must i do?
    ps: i’m still noob

  11. Dominick on July 21, 2013 at 10:47 pm

    hi george thanks for your tutorial. really helped i think every 1 here is trying to make the driving route to the markers that they had put in personally. can you shows us some example or give us some advice on how to do that? (if any 1 know please help me really do appreciate.) thank you!

  12. Jacks on July 22, 2013 at 10:39 am

    Hi george thanks for tutor

    but i cant draw my direction.
    is the google directions doesnt working anymore?
    how to get direction from my loaction(GPS position) to marker that i’ve be made?

    • Jacks on July 22, 2013 at 6:55 pm

      after i running that application then the apllication closed.

      • george on July 22, 2013 at 7:36 pm

        Are you getting any error message in logcat?

  13. Jacks on July 22, 2013 at 7:48 pm

    heres my logcat

    07-22 21:15:55.920: E/AndroidRuntime(10937): FATAL EXCEPTION: main
    07-22 21:15:55.920: E/AndroidRuntime(10937): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.petasemarang/com.petasemarang.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread.access$600(ActivityThread.java:123)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.os.Handler.dispatchMessage(Handler.java:99)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.os.Looper.loop(Looper.java:137)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread.main(ActivityThread.java:4424)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.reflect.Method.invokeNative(Native Method)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.reflect.Method.invoke(Method.java:511)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at dalvik.system.NativeStart.main(Native Method)
    07-22 21:15:55.920: E/AndroidRuntime(10937): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:268)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.Activity.setContentView(Activity.java:1835)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at com.petasemarang.MainActivity.onCreate(MainActivity.java:49)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.Activity.performCreate(Activity.java:4465)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    07-22 21:15:55.920: E/AndroidRuntime(10937): … 11 more
    07-22 21:15:55.920: E/AndroidRuntime(10937): Caused by: java.lang.NullPointerException: name == null
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.VMClassLoader.findLoadedClass(Native Method)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:354)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.ClassLoader.loadClass(ClassLoader.java:491)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.support.v4.app.Fragment.instantiate(Fragment.java:391)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
    07-22 21:15:55.920: E/AndroidRuntime(10937): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
    07-22 21:15:55.920: E/AndroidRuntime(10937): … 21 more

    is there something wrong??

    • george on July 22, 2013 at 7:58 pm

      Please ensure that, your activity class is extending FragmentActivity.

      • Jacks on July 22, 2013 at 8:06 pm

        this one right?
        public class MainActivity extends FragmentActivity implements LocationListener

        i following that tutor above.

        • george on July 22, 2013 at 8:29 pm

          When the application is getting closed? Is it on loading the application or after entering the destination point?

          • Jacks on July 22, 2013 at 8:40 pm

            when i build it.when it launched . i tried to build not on AVD but on my device IceCream Sandwich .

            maybe would you mind to make that tutor into APK file. so i can easily checking it. i tried to using your code by downloading it.

          • Jacks on July 31, 2013 at 6:05 pm

            Thanks George i got this solutions, i have one question. how to get direction from my location to marker ( many marker on map). any clue pls

          • Winnie on April 26, 2014 at 8:26 pm

            I also have the same question when i build it.when it launched. How to fix this problem?

          • Akbar on May 4, 2014 at 11:56 am

            Don’t make emulator, but launch from your device phone.

  14. Jacks on July 24, 2013 at 3:11 pm

    any solutions george? im waiting for this tutorial . would you mind to make a video tutorial for this? or?

  15. Student on July 25, 2013 at 3:29 pm

    Since one week, i did not test using google map in our map. while using downloadUrl(String strUrl) hrows an exception : java.net.SocketException: Socket is closed. After trying to download the json data. any idea

  16. RAMESH BABU on August 6, 2013 at 1:26 pm

    Hi Sir , i drawed a line from hyderabad to Uk .. one error occured Out of memory enhaused .. with in the country working fine

    please help to me sir ,, ur project submition postponed sir

    Waiting for ur response

    • george on August 6, 2013 at 3:02 pm

      Please try this way.

      Instead of parsing the the json data in a single stretch, parse data in multiple stages.

      • RAMESH BABU on August 7, 2013 at 4:59 pm
        • RAMESH BABU on August 7, 2013 at 5:01 pm

          waiting for ur response sir please sir

          project dead very little time am seaching for this error last two months onwords sir ………

          • george on August 7, 2013 at 5:06 pm

            Hi,
            Please try to split the parsing task into multiple small tasks.

          • RAMESH BABU on August 7, 2013 at 5:36 pm

            small example sir please

        • RAMESH BABU on August 7, 2013 at 5:30 pm

          waiting for ur response sir please sir

          project dead line very little time am seaching for this error last two months onwords sir ………

  17. student on August 13, 2013 at 4:54 pm

    I am writing for the 2nd time. Line // Connecting to url
    urlConnection.connect();
    throws an exception. Socket closed. It worked fine but now I do now know what happened. waiting for your reponse.

    thnx

  18. prabhurajas on August 13, 2013 at 6:19 pm

    hai sir,

    i need to calculate a distance of find a route in google maps v2, so i need source code , and that paths are shortest path, longest path route sir, so send me code sir, kindly i hope u,,,,,,

  19. osig on August 17, 2013 at 9:47 pm

    hi sir my source pointer is not its always on turkey plz help

  20. akhwan on August 19, 2013 at 2:45 pm

    how to use it ?
    it’s didn’t function

  21. Scisor on August 20, 2013 at 1:42 am

    Hi george!!
    I tried just to parse the “overview polyline” tag and decode the “points” and i managed to create the polyline.
    But now i want to be able to click on this polyline and make it show info like distance and duration on click of every point.How could i do this??
    Thx your work is awesome

  22. Aleksandar on August 29, 2013 at 5:51 pm

    Hi George,
    I am having problems with your codes. When I right click on your project and go to properties, and in Library I try to put google-play-services-lib, it won’t accept it. I dont know why. I add google-play-services-lib, click apply, then ok, but when i go back I have let’s say negative sign next to the reference and project is marked with question mark. Any idea why?

  23. Jacks on September 9, 2013 at 8:56 pm

    Hi GEORGE, i have a question?

    how to add marker here. im alr tried it but i cant find the solutions

    would you mind to help me to show marker in this project?

    • George Mathew on September 9, 2013 at 10:05 pm

      Hi Jacks,

      Actually, can you please tell me, what do you meant by showing marker ! Because, already it is showing two markers, one at the starting position and the other at the destination.

      • Jacks on September 10, 2013 at 7:27 am

        hi george, i wanted to make a destination marker on another mareker based on latitutde and logitute.

        so when i click another marker then the path will routing to place with marker.
        like this
        Name lat longi
        marker place one (-6.12334, 11.0123123)
        marker place two (-6.32244, 12.213423)
        marker place three(-5.8212, 10.86435)

        nah, when marker place one clicked then directions will showing from my locations ( current position) to marker place one.

        Please help for this george

        • George Mathew on September 10, 2013 at 9:11 am

          Hi Jacks,

          I think you need to draw route from mylocation to multiple destination locations. If this is the case, you just need to do some minor modification in the click listener of the map and in the drawMarker method. These minor modifications are listed below :

          1. Remove the code to clear the map

          2. Set destination location to the currently touched location

          3. Display the marker color as RED for all the markers except for first marker.

          • Jacks on September 10, 2013 at 12:28 pm

            alr tried to remove code clear map.

            i can show marker on map, but when i clciked that marker, the 2nd destination marker wont placeable with place marker.

            this one right

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

            @Override
            public void onMapClick(LatLng point) {

            // Already map contain destination location
            if(mMarkerPoints.size()>1){

            FragmentManager fm = getSupportFragmentManager();
            mMarkerPoints.clear();
            mGoogleMap.clear();
            LatLng startPoint = new LatLng(mLatitude, mLongitude);

            // draw the marker at the current position
            drawMarker(startPoint);
            }

            // draws the marker at the currently touched location
            drawMarker(point);

            could u pls to show me which to modif

          • George Mathew on September 10, 2013 at 3:12 pm

            Please check the updated code here

  24. Salvador on November 18, 2013 at 3:38 am

    Hi GEORGE, i have a question?

    How to add a marker with the destination already in the map.
    if i start the aplication. it will show the marker with my location and the marker with my default destination already and the route.

  25. Miguel on November 18, 2013 at 7:12 am

    Hi, George…
    Thanks for the tutorial :D

    I’m Mexican. i want to make the second marker static with default coordenates. when i lunch the aplication it will show mi current location and the default location with the route. can you help me plz. I for my final project in the university. sorry for the bad english.

  26. Shinu Peter on February 20, 2014 at 4:23 pm

    Hi George
    Good tutorial.
    But I am not getting lines between source and destination. I am getting this Error “/GooglePlayServicesUtil(23403): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.”. I added Google play service library.And in manifest file

  27. akbar on February 27, 2014 at 10:10 pm

    how to remove just polilyne without marker?

  28. Daniel Strickland on March 4, 2014 at 5:19 pm

    Hi George,

    Fist, I appreciate the effort your making in helping all of us. I do have one problem though. I’m getting a “warning” message in regards to “FragmentManager fm =”. Eclipse is telling me that the “local variable fm is not used”. I’ve gone over the coding for several days now and can’t figure out what the problem is. I’ve essentially just copied and pasted your code into my project so I know it’s not typographical errors. Any ideas?

    • Akbar on March 4, 2014 at 6:33 pm

      Maybe i can help you, can you send to me your project?

      • Daniel Strickland on March 5, 2014 at 8:13 pm

        I’ve updated the Java to the one mentioned above found at this address: http://pastebin.com/8tVHCqWb. Now the warnings I’m getting are three: unused FragmentManager, OnCameraChangeListener, and CameraPosition imports. Being a noob, I’m not sure which I should use…the first with the one warning about the local variable “fm” or the present one with the three warning about unused imports.

      • Daniel Strickland on March 5, 2014 at 8:15 pm

        I’ve updated the Java to the one mentioned above found at this address: http://pastebin.com/8tVHCqWb. Now the warnings I’m getting are three: unused FragmentManager, OnCameraChangeListener, and CameraPosition imports. Being a noob, I’m not sure which I should use…the first with the one warning about the local variable “fm” or the present one with the three warning about unused imports. As requested Akbar, I’ll be sending my entire package for your scrutiny. Any other suggestions you may have would be greatly appreciated.

        • Akbar on April 6, 2014 at 8:58 pm

          i try your project but nothing wrong with your code. Maybe you don’t include google play service.

    • Akbar on March 4, 2014 at 6:34 pm
      • Daniel Strickland on March 7, 2014 at 3:43 pm

        Been a few days since I sent that app to you, have you had a chance to take a look at it? Any suggestions?

        • Akbar on March 15, 2014 at 9:58 pm

          Sorry your email inside spam mail.Do you have import google play service into your workplace? I think nothing wrong with your code.

  29. Jasmine on April 4, 2014 at 2:25 pm

    Hi George,
    Thank you for this helpful tutorial in helping us, I’ve tried your demo code as above, got Error on android.view.InflateException: Binary XML file line #7: Error inflating class fragment…
    It’s confirmed that I generated Map API v2 key for this package, the lib project was fine, support library was added, but it can not work on physical device, could you please help it? thank you very much.
    btw, I’ve tried some suggestion on SOF, like remove fragment XML class=”com.google.android.gms.maps.SupportMapFragment”

  30. Nursultan on May 27, 2014 at 8:28 pm

    Hi, very helpfull tutorial, thanks!!!

    But I have some errors like
    android.view.InflateException: Binary XML file line #7: Error inflating class fragment.
    The application is getting closed when it’s on loading.
    I spend much time to solve it, but unsuccessfully. Can you help me, please?

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner