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″
2. Configure the project
3. Design application launcher icon
4. Create a blank activity
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
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
15. Download Source Code


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
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)));
how to makeDriving route from my location to multiple destinations in Google Maps API V2 Android, remains his goal made in a list view
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
hi ages,
will you have any solution about the project above? Can I ask some programming about this project?
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 ????
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
Check your manifest file and check to see that google play is installed. Also ensure you have a google maps key
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?
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
it is possible to get driving directions depends on my marker. which i have added in map..?? in sort custom deriving directions???
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
Hi,
I am from Korea.
it didn’t work.
it is below.
https://maps.googleapis.com/maps/api/directions/jason&orgin=location&destination®ion=kr&sensor=false
please help me.
teach me url address in korea.
I think, you entered wrong url. Please see that, you entered “jason” for “json”
i am sorry.. json is right.
location is korea.
http://maps.googleapis.com/maps/api/directions/json?origin=36.668419,127.880859&destination=36.049099,128.408203&sensor=false
result is below..
{
“routes” : [],
“status” : “ZERO_RESULTS”
}
please help me..
I checked in web version of Google Directions with the coordinates provided by you. There also i could not find any connecting route.
But routes are available for other parts of Korea like Seoul.
thank you..
please explain for example below url.
http://maps.googleapis.com/maps/api/directions/json?
You should use api key as “key=your key” in the url after destination lat and lng.
Hello, I would like to know how can I be the first point my location. thank you
Hi,
In this application, the first point is always my location.
Hi, George…
Thanks for the tutorial
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
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!
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?
after i running that application then the apllication closed.
Are you getting any error message in logcat?
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??
Please ensure that, your activity class is extending FragmentActivity.
this one right?
public class MainActivity extends FragmentActivity implements LocationListener
i following that tutor above.
When the application is getting closed? Is it on loading the application or after entering the destination point?
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.
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
I also have the same question when i build it.when it launched. How to fix this problem?
Don’t make emulator, but launch from your device phone.
any solutions george? im waiting for this tutorial . would you mind to make a video tutorial for this? or?
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
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
Please try this way.
Instead of parsing the the json data in a single stretch, parse data in multiple stages.
https://maps.googleapis.com/maps/api/directions/json?origin=17.397821,78.485527&destination=51.525834,-0.132752&sensor=true
am getting response this above url
how to write sample program please sir
waiting for ur response sir please sir
project dead very little time am seaching for this error last two months onwords sir ………
Hi,
Please try to split the parsing task into multiple small tasks.
small example sir please
waiting for ur response sir please sir
project dead line very little time am seaching for this error last two months onwords sir ………
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
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,,,,,,
hi sir my source pointer is not its always on turkey plz help
how to use it ?
it’s didn’t function
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
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?
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?
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.
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
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.
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
Please check the updated code here
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.
Hi, George…
Thanks for the tutorial
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.
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
how to remove just polilyne without marker?
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?
Maybe i can help you, can you send to me your project?
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.
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.
i try your project but nothing wrong with your code. Maybe you don’t include google play service.
pripunjawa@gmail.com
Been a few days since I sent that app to you, have you had a chance to take a look at it? Any suggestions?
Sorry your email inside spam mail.Do you have import google play service into your workplace? I think nothing wrong with your code.
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”
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?
hi sir please understand me about json parser?how it works in this application in detail? i will be very thankful to you
Hi..Sir..I want draw a path between source and destination points when i enter the those values at search boxes
Hi sir, can you help me? i got java.lang.nullpointerexception in parsertask class part onpostexecute. but i don’t know why
Hello sir,
I got the following error message,
{ “error_message” : “You have exceeded your daily request quota for this API.”, “routes” : [], “status” : “OVER_QUERY_LIMIT”}
Hi George,
Thank you for this helpful code But plz tell me how to add third marker in this code plz help me.
thnks
Hi sir, i want to ask if i want the current location / starting point will follow my device to moving and then draw the route about it….how can i do it? it is different with this tutorial right? pls help me thank…..
how to add already filled base with markers that they were removed on the card to this example?
Hello sir ,
I want to draw path between my current location and the destination for which I am providing location co-ordinate .I found your post and this is really helpful for me.But, I am getting an error msg while I am executing the code .The part of code where I got this error is “A method to download json data”
Error :{ “error_message” : “This IP, site or mobile application is not authorized to use this API key. Request received from IP address 111.119.199.22, with empty referer”, “routes” : [], “status” : “REQUEST_DENIED”}
Kindly,guide
Hi George,
I need draw from to current location to destination location where exactly the name of the route is provided. How to do this code?
Thanks in advance.
PLZ Tell me how to get user current location on google map in our own application
when adding marker on lollipop device.it unfortunatly stopping…can u help me to fix the bug
till gellybean the working is fine…please help
Please help me
how to draw infinite route with more than 10 locations on google map in android ?
Thanks for your tutorial. In this tutorial only show one way to direction between 2 point location but in GMaps it show 2 ways so can you teach me how to show more than 1 way to direction ? Thanks advanced
Hello Sir George,
I need your help with my app. I use this code of yours to my app but i want to add something in it.
Example:
There is a different marker all over the map and once i tap a marker it will show the direction from my to location to the taped marker. Please help me with this.
Sorry for my English. I’m not that good using english language, hope you understand. Thanks a lot!
In MainActivity, line 286 shows error as:
Error:(285, 41) error: cannot find symbol variable main
Please help to debug this.
put source as magadan russia and destination as cape point south africa. and see if your app can handle this route. please do try and reply.
I George.
Thanks for this tutorial. i created a new arrayList and i added my markers on this arrayList. i’m trying to get the route from my origem point to my markers.
@Override
public boolean onMarkerClick(Marker marker) {
LatLng title = marker.getPosition();
if (title.equals(“Loja Coqueiros”) && markerPoints.size() < 2 ){
LatLng origin = markerPoints.get(0);
LatLng dest = locations.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);
}
return false;
}
dosent work. How can i do it? please help me
It really helped a lot. Thanks.