android - How to draw path as I move starting from my current location using Google Maps -
i trying draw route move current location. facing big problem in drawing route dynamically please me solve it. having marker @ current location in map. start moving want map start drawing lines in path move. not have 2 fixed points. can 1 please provide me solution on come this. have seen lot of answers in draws path between 2 fixed points. here initial point fixed. able current location in app currently. tried following code getlocationmanager() resulting in error. using android studio.
updated code:
my activity:
import android.content.context; import android.content.sharedpreferences; import android.location.address; import android.location.geocoder; import android.location.location; import android.os.bundle; import android.support.v4.app.fragmentactivity; import android.util.log; import android.util.xml; import android.widget.textview; import android.widget.toast; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.common.api.googleapiclient; import com.google.android.gms.common.api.pendingresult; import com.google.android.gms.common.api.status; import com.google.android.gms.location.locationlistener; import com.google.android.gms.location.locationrequest; import com.google.android.gms.location.locationservices; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; 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.marker; import com.google.android.gms.maps.model.markeroptions; import com.google.maps.android.ui.icongenerator; import org.xmlpull.v1.xmlserializer; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.stringwriter; import java.text.dateformat; import java.util.calendar; import java.util.date; import java.util.list; import java.util.locale; public class mainactivity extends fragmentactivity implements locationlistener, googleapiclient.connectioncallbacks, googleapiclient.onconnectionfailedlistener { private static final string tag = "mainactivity"; private static final long interval = 1000 * 60 * 1; //1 minute private static final long fastest_interval = 1000 * 60 * 1; // 1 minute private locationrequest mlocationrequest; private googleapiclient mgoogleapiclient; private location mcurrentlocation; private string mlastupdatetime; private string city = ""; private string country = ""; private string area = ""; private string title; private string requiredarea = ""; private googlemap googlemap; private list<address> addresses; protected void createlocationrequest() { mlocationrequest = new locationrequest(); mlocationrequest.setinterval(interval); mlocationrequest.setfastestinterval(fastest_interval); mlocationrequest.setpriority(locationrequest.priority_high_accuracy); } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); log.d(tag, "oncreate ..............................."); //show error dialog if goolgleplayservices not available if (!isgoogleplayservicesavailable()) { toast.maketext(this, "google play services not available", toast.length_long).show(); finish(); } createlocationrequest(); mgoogleapiclient = new googleapiclient.builder(this) .addapi(locationservices.api) .addconnectioncallbacks(this) .addonconnectionfailedlistener(this) .build(); setcontentview(r.layout.activity_main); supportmapfragment fm = (supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map); googlemap = fm.getmap(); googlemap.setmylocationenabled(true); googlemap.setonmylocationbuttonclicklistener(new googlemap.onmylocationbuttonclicklistener() { @override public boolean onmylocationbuttonclick() { toast.maketext(getapplicationcontext(), "location button has been clicked", toast.length_long).show(); return true; } }); googlemap.getuisettings().setzoomcontrolsenabled(true); googlemap.getuisettings().setallgesturesenabled(true); } @override public void onstart() { super.onstart(); log.d(tag, "onstart fired .............."); mgoogleapiclient.connect(); } @override public void onstop() { super.onstop(); log.d(tag, "onstop fired .............."); mgoogleapiclient.disconnect(); log.d(tag, "isconnected ...............: " + mgoogleapiclient.isconnected()); } private boolean isgoogleplayservicesavailable() { int status = googleplayservicesutil.isgoogleplayservicesavailable(this); if (connectionresult.success == status) { return true; } else { googleplayservicesutil.geterrordialog(status, this, 0).show(); toast.maketext(getapplicationcontext(), "google play services not available", toast.length_long).show(); return false; } } @override public void onconnected(bundle bundle) { log.d(tag, "onconnected - isconnected ...............: " + mgoogleapiclient.isconnected()); startlocationupdates(); } protected void startlocationupdates() { pendingresult<status> pendingresult = locationservices.fusedlocationapi.requestlocationupdates( mgoogleapiclient, mlocationrequest, this); log.d(tag, "location update started ..............: "); } @override public void onconnectionsuspended(int i) { } @override public void onconnectionfailed(connectionresult connectionresult) { log.d(tag, "connection failed: " + connectionresult.tostring()); } @override public void onlocationchanged(location location) { log.d(tag, "firing onlocationchanged.............................................."); mcurrentlocation = location; mlastupdatetime = dateformat.gettimeinstance().format(new date()); addmarker(); float accuracy = location.getaccuracy(); log.d("ifocus", "the amount of accuracy " + accuracy); double latitude = location.getlatitude(); double longitude = location.getlongitude(); bundle extras = location.getextras(); boolean has = location.hasaccuracy(); string provider = location.getprovider(); long time = location.gettime(); // location locationb = new location("begur"); // double lati = 12.8723; // double longi = 77.6329; // locationb.setlatitude(lati); // locationb.setlongitude(longi); // float distance = location.distanceto(locationb); calendar calendar = calendar.getinstance(); calendar.settimeinmillis(time); int myear = calendar.get(calendar.year); int mmonth = calendar.get(calendar.month) + 1; int mday = calendar.get(calendar.day_of_month); string formattedtime = mday + ":" + mmonth + ":" + myear; log.d("ifocus", "the name of provider " + provider); log.d("ifocus", "the value of has " + has); log.d("ifocus", "the value of extras " + extras); log.d("ifocus", "the value of month " + mmonth); log.d("ifocus", "the value of day " + mday); log.d("ifocus", "the value of year " + myear); log.d("ifocus", "the value of time " + formattedtime); //log.d("ifocus", "the value of distance "+distance); latlng latlng = new latlng(latitude, longitude); geocoder geocoder = new geocoder(this, locale.getdefault()); try { addresses = geocoder.getfromlocation(latitude, longitude, 1); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } string cityname = addresses.get(0).getaddressline(0); string statename = addresses.get(0).getaddressline(1); string countryname = addresses.get(0).getaddressline(2); string[] splittedstatename = statename.split(","); requiredarea = splittedstatename[2]; log.d("ifocus", "the value of required area " + requiredarea); city = addresses.get(0).getlocality(); area = addresses.get(0).getsublocality(); string adminarea = addresses.get(0).getadminarea(); string premises = addresses.get(0).getpremises(); string subadminarea = addresses.get(0).getsubadminarea(); string featurename = addresses.get(0).getfeaturename(); string phone = addresses.get(0).getphone(); country = addresses.get(0).getcountryname(); log.d("ifocus", "the name of city " + city); log.d("ifocus", "the name of area " + area); log.d("ifocus", "the name of country " + country); log.d("ifocus", "the value of cityname " + cityname); log.d("ifocus", "the value of statename " + statename); log.d("ifocus", "the value of countryname " + countryname); toast.maketext(this, cityname + " " + statename + " " + countryname, toast.length_long).show(); sharedpreferences sharedpreferences = getsharedpreferences("myvalues", mode_private); sharedpreferences.editor editor = sharedpreferences.edit(); editor.putstring("city", cityname); editor.putstring("state", statename); editor.putstring("country", countryname); editor.commit(); textview maptitle = (textview) findviewbyid(r.id.textviewtitle); if (requiredarea != "" && city != "" && country != "") { title = mlastupdatetime.concat(", " + requiredarea).concat(", " + city).concat(", " + country); } else { title = mlastupdatetime.concat(", " + area).concat(", " + city).concat(", " + country); } maptitle.settext(title); addmarker();// newly added final string xmlfile = "userdata.xml"; try { // fileoutputstream fos = new fileoutputstream("userdata.xml"); fileoutputstream fos = openfileoutput(xmlfile, context.mode_private); xmlserializer xmlserializer = xml.newserializer(); stringwriter writer = new stringwriter(); xmlserializer.setoutput(writer); xmlserializer.startdocument("utf-8", true); xmlserializer.starttag(null, "userdata"); xmlserializer.starttag(null, "time"); xmlserializer.text(mlastupdatetime); xmlserializer.endtag(null, "time"); xmlserializer.starttag(null, "area"); if (requiredarea != "") { xmlserializer.text(requiredarea); } else { xmlserializer.text(area); } xmlserializer.endtag(null, "area"); xmlserializer.starttag(null, "city"); xmlserializer.text(city); xmlserializer.endtag(null, "city"); xmlserializer.endtag(null, "userdata"); xmlserializer.enddocument(); xmlserializer.flush(); string datawrite = writer.tostring(); fos.write(datawrite.getbytes()); fos.close(); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (illegalargumentexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (illegalstateexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } string dir = getfilesdir().getabsolutepath(); log.d("pana", "the value of dir "+dir); } private void addmarker() { markeroptions options = new markeroptions(); // following 4 lines requires 'google maps android api utility library' // https://developers.google.com/maps/documentation/android/utility/ // have used display time title location markers // can safely comment following 4 lines info icongenerator iconfactory = new icongenerator(this); iconfactory.setstyle(icongenerator.style_purple); // options.icon(bitmapdescriptorfactory.frombitmap(iconfactory.makeicon(mlastupdatetime + requiredarea + city))); options.icon(bitmapdescriptorfactory.frombitmap(iconfactory.makeicon(requiredarea + ", " + city))); options.anchor(iconfactory.getanchoru(), iconfactory.getanchorv()); latlng currentlatlng = new latlng(mcurrentlocation.getlatitude(), mcurrentlocation.getlongitude()); options.position(currentlatlng); marker mapmarker = googlemap.addmarker(options); long attime = mcurrentlocation.gettime(); mlastupdatetime = dateformat.gettimeinstance().format(new date(attime)); string title = mlastupdatetime.concat(", " + requiredarea).concat(", " + city).concat(", " + country); mapmarker.settitle(title); textview maptitle = (textview) findviewbyid(r.id.textviewtitle); maptitle.settext(title); log.d(tag, "marker added............................."); googlemap.movecamera(cameraupdatefactory.newlatlngzoom(currentlatlng, 13)); log.d(tag, "zoom done............................."); } @override protected void onpause() { super.onpause(); stoplocationupdates(); } protected void stoplocationupdates() { locationservices.fusedlocationapi.removelocationupdates( mgoogleapiclient, this); log.d(tag, "location update stopped ......................."); } @override public void onresume() { super.onresume(); if (mgoogleapiclient.isconnected()) { startlocationupdates(); log.d(tag, "location update resumed ....................."); } } }
i trying add method in code draw line giving error in getlocationmanager();
private void addlocationlistener(locationlistener locationlistener) { locationprovider locationprovider = getlocationmanager().getprovider(locationmanager.gps_provider); getlocationmanager().requestlocationupdates(locationprovider.getname(), location_update_interval, location_update_min_distance, locationlistener); } private locationmanager getlocationmanager() { return (locationmanager) context.getsystemservice(context.location_service); } private void startgpslistening(location start) { this.startlocation = start; addlocationlistener(new mylocationlistener()); } private location startlocation = new location(""); private class mylocationlistener extends locationlistener { public void onlocationchanged(location location) { } ... }
it seems best implementation use arraylist<latlng>
store each point given in onlocationchanged()
. then, each time new point, re-draw line.
first, import need drawing lines:
import com.google.android.gms.maps.model.polyline; import com.google.android.gms.maps.model.polylineoptions;
create member variables arraylist , polyline:
private arraylist<latlng> points; //added polyline line; //added
initialize points
in oncreate()
:
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); points = new arraylist<latlng>(); //added //...............
then, in onlocationchanged()
, add each point arraylist:
@override public void onlocationchanged(location location) { double latitude = location.getlatitude(); double longitude = location.getlongitude(); latlng latlng = new latlng(latitude, longitude); //you have points.add(latlng); //added redrawline(); //added }
taking this answer, define redrawline()
method.
remove other calls addmarker()
, since calling clear()
on map, removes markers , polylines.
private void redrawline(){ googlemap.clear(); //clears markers , polylines polylineoptions options = new polylineoptions().width(5).color(color.blue).geodesic(true); (int = 0; < points.size(); i++) { latlng point = points.get(i); options.add(point); } addmarker(); //add marker in current position line = googlemap.addpolyline(options); //add polyline }
edit: want dial in minimum distance in meters between location changed callbacks.
private static final string tag = "mainactivity"; private static final long interval = 1000 * 60 * 1; //1 minute private static final long fastest_interval = 1000 * 60 * 1; // 1 minute private static final float smallest_displacement = 0.25f; //quarter of meter
call setsmallestdisplacement()
:
protected void createlocationrequest() { mlocationrequest = new locationrequest(); mlocationrequest.setinterval(interval); mlocationrequest.setfastestinterval(fastest_interval); mlocationrequest.setsmallestdisplacement(smallest_displacement); //added mlocationrequest.setpriority(locationrequest.priority_high_accuracy); }
that should enough started. may need fine-tune frequency of location changed callbacks desired result. there's more that, can find edge cases , fix them after testing.
Comments
Post a Comment