java - How to get LatLng data from Google Geocoding API json? -
i creating application map , faced problem. have mapview in fragment , autocompletetextview. when pick city autocomplete, should appear marker on map.
here code , working on real samsung galaxy s3 , galaxy s6 emulator, not work on meizu mx5. found, geocoder not work on every device, there solution google geocoding api. got json answer, don't know how latlang , featurename json.
example of json: http://maps.google.com/maps/api/geocode/json?address=london&sensor=true
i new android, sorry if not clear.
atvfrom.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { locationfrom = atvfrom.gettext().tostring(); list<address> addresslistfrom = null; geocoder geocoder = new geocoder(getactivity()); try { if (markerfrom[0] != null) {markerfrom[0].remove();} addresslistfrom = geocoder.getfromlocationname(locationfrom, 1); if (addresslistfrom != null) { address addressfrom = addresslistfrom.get(0); latlngfrom[0] = new latlng(addressfrom.getlatitude(), addressfrom.getlongitude()); tripfrom = addresslistfrom.get(0).getfeaturename(); markerfrom[0] = googlemap.addmarker(new markeroptions().position(latlngfrom[0]).title("from")); googlemap.animatecamera(cameraupdatefactory.newlatlng(latlngfrom[0])); if (markerto[0]!=null) { if (line[0] !=null) {line[0].remove();} line[0] = googlemap.addpolyline(new polylineoptions().add(latlngfrom[0], latlngto[0]).width(5).color(color.blue)); } } else { mygeocoder mygeocoder = new mygeocoder(fragmentmap.this); mygeocoder.execute(locationfrom); try { jsonobject jobj = new jsonobject(mygeocoder.jsonresult); string status = jobj.getstring("status"); if (status.equalsignorecase("ok")) { jsonarray results = jobj.getjsonarray("results"); // how latlng , featurename json? // dont know here } } catch (jsonexception e) { e.printstacktrace(); } } } catch (ioexception e) { //e.printstacktrace(); toast.maketext(getactivity(), "error", toast.length_short).show(); } } });
you need navigate through json objects reach location
. how need do
try { jsonobject jobj = new jsonobject(mygeocoder.jsonresult); string status = jobj.getstring("status"); if (status.equalsignorecase("ok")) { jsonarray results = jobj.getjsonarray("results"); jsonobject item = results.getjsonobject(0);//read first item of results jsonobject geometry = item.getjsonobject("geometry");//location inside geometry object jsonobject location = geometry.getjsonobject("location"); double latitude = location.getdouble("lat"); double longitude = location.getdouble("lng"); //or latlng latlng = new latlng(latitude, longitude); } } catch (jsonexception e) { e.printstacktrace(); }
and check geocoder existance on devices, call below method
use ispresent() method determine whether geocoder implementation exists.
if(geocoder.ispresent()){ //exists }
happycoding;
Comments
Post a Comment