Android Google Maps V2 get nearby gas stations and get longitude and latitude of station then draw route to it -
i developing android app google maps v2, nearest gas stations status of them if have gas or not, reached current location , draw route between current location , given longitude , latitude , distance , duration in driving mode location.
my question how nearby gas stations, there way them , longitude , latitude of them, because want execute nearest 1 smallest distance , have status "have gas in it" draw route location.
i thing scenario execute longitude , latitude , store them database status of them, , when user go location, nearest gas station go database search status , calculate distance draw route "shortest path" of nearby station, suitable way execute or can way , if how can that.
please find code used below , testing on samsung galaxy s duos s7562
map.java
package com.banzina; public class map extends activity implements locationlistener{ googlemap map; arraylist<latlng> markerpoints; latlng myposition; latlng position2; float[] results = new float[1]; textview tvdistanceduration; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.show_map); tvdistanceduration = (textview) findviewbyid(r.id.tv_dis); mapfragment fm=(mapfragment) getfragmentmanager().findfragmentbyid(r.id.map); map=fm.getmap(); map.setmylocationenabled(true); locationmanager locationmanager=(locationmanager) getsystemservice(location_service); criteria criteria=new criteria(); // object retrieve provider string provider = locationmanager.getbestprovider(criteria, true); location location=locationmanager.getlastknownlocation(provider); if(location!=null){ onlocationchanged(location); } locationmanager.requestlocationupdates(provider, 20000, 0, this); markerpoints = new arraylist<latlng>(); map = fm.getmap(); map.setmylocationenabled(true); map.setonmapclicklistener(new onmapclicklistener() { @override public void onmapclick(latlng point){ if(markerpoints.size()>1) { markerpoints.clear(); map.clear(); } markerpoints.add(point); markeroptions options = new markeroptions(); options.position(point); if(markerpoints.size()==1) { options.icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_green)); } else if(markerpoints.size()==2) { options.icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_red)); } map.addmarker(options); position2 = new latlng(30.08393, 31.24225); if(markerpoints.size() >= 2) { latlng origin = markerpoints.get(0); latlng dest = markerpoints.get(1); string url = getdirectionsurl(myposition, position2); downloadtask downloadtask = new downloadtask(); downloadtask.execute(url); location.distancebetween(myposition.latitude, myposition.longitude, position2.latitude, position2.longitude, results); map.addmarker(new markeroptions().position(position2).title("end")); } } }); } public void distanceto (location dest){} public static void distancebetween (double startlatitude, double startlongitude, double endlatitude, double endlongitude, float[] results){ } public void onlocationchanged(location location) { double latitude = location.getlatitude(); double longitude = location.getlongitude(); latlng latlng = new latlng(latitude, longitude); myposition = new latlng(latitude, longitude); map.addmarker(new markeroptions().position(myposition).title("start")); map.movecamera(cameraupdatefactory.newlatlng(latlng)); map.animatecamera(cameraupdatefactory.zoomto(17)); textview t=(textview) findviewbyid(r.id.tv_location); t.settext("latitude:" + latitude + ", longitude:"+ longitude ); } private string getdirectionsurl(latlng origin,latlng dest){ string str_origin = "origin="+origin.latitude+","+origin.longitude; string str_dest = "destination="+dest.latitude+","+dest.longitude; string sensor = "sensor=false"; string parameters = str_origin+"&"+str_dest+"&"+sensor; // output format string output = "json"; // building url web service string url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters; return url; } /** method download json data url */ private string downloadurl(string strurl) throws ioexception{ string data = ""; inputstream istream = null; httpurlconnection urlconnection = null; try{ url url = new url(strurl); // creating http connection communicate url urlconnection = (httpurlconnection) url.openconnection(); // connecting url urlconnection.connect(); // reading data url istream = urlconnection.getinputstream(); bufferedreader br = new bufferedreader(new inputstreamreader(istream)); stringbuffer sb = new stringbuffer(); string line = ""; while( ( line = br.readline()) != null){ sb.append(line); } data = sb.tostring(); br.close(); }catch(exception e){ log.d("exception while downloading url", e.tostring()); }finally{ istream.close(); urlconnection.disconnect(); } return data; } // fetches data url passed private class downloadtask extends asynctask<string, void, string>{ // downloading data in non-ui thread @override protected string doinbackground(string... url) { // storing data web service string data = ""; try{ // fetching data web service data = downloadurl(url[0]); }catch(exception e){ log.d("background task",e.tostring()); } return data; } // executes in ui thread, after execution of // doinbackground() @override protected void onpostexecute(string result) { super.onpostexecute(result); parsertask parsertask = new parsertask(); // invokes thread parsing json data parsertask.execute(result); } } /** class parse google places in json format */ private class parsertask extends asynctask<string, integer, list<list<hashmap<string,string>>> >{ // parsing 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 parsing process @override protected void onpostexecute(list<list<hashmap<string, string>>> result) { arraylist<latlng> points = null; polylineoptions lineoptions = null; markeroptions markeroptions = new markeroptions(); string distance = ""; string duration = ""; // traversing through 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 points in i-th route for(int j=0;j<path.size();j++){ hashmap<string,string> point = path.get(j); if(j==0){ // distance list distance = (string)point.get("distance"); continue; }else if(j==1){ // duration list duration = (string)point.get("duration"); continue; } double lat = double.parsedouble(point.get("lat")); double lng = double.parsedouble(point.get("lng")); latlng position = new latlng(lat, lng); points.add(position); } // adding points in route lineoptions lineoptions.addall(points); lineoptions.width(2); lineoptions.color(color.red); } tvdistanceduration.settext("distance:"+distance + ", duration:"+duration); // drawing polyline in google map i-th route map.addpolyline(lineoptions); } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.map, menu); return true; }}
layout sho_map.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=".showmap" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.mapfragment" /> <textview android:id="@+id/tv_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/map" android:layout_aligntop="@+id/map" android:layout_marginleft="83dp" android:text="textview" /> <textview android:id="@+id/tv_dis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_alignparentleft="true" android:layout_marginbottom="15dp" android:layout_marginleft="14dp" android:text="textview" /> </relativelayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.banzina" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="15" android:targetsdkversion="15" /> <permission android:name="com.banzina.permission.maps_receive" android:protectionlevel="signature" /> <uses-feature android:glesversion="0x00020000" android:required="true" /> <uses-permission android:name="com.banzina.permission.maps_receive" /> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.access_wifi_state" /> <uses-permission android:name="android.permission.access_network_state"/> <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.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:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location.network" android:required="false" /> <uses-feature android:name="android.hardware.location.gps" /> <uses-feature android:name="android.hardware.wifi" android:required="false" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.banzina.map" 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="*********my key********" /> </application> </manifest>
directionsjsonparser.java
package com.banzina; 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 jsonobject , returns list of lists containing latitude , 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; jsonobject jdistance = null; jsonobject jduration = null; try { jroutes = jobject.getjsonarray("routes"); /** traversing routes */ for(int i=0;i<jroutes.length();i++){ jlegs = ( (jsonobject)jroutes.get(i)).getjsonarray("legs"); list path = new arraylist<hashmap<string, string>>(); /** traversing legs */ for(int j=0;j<jlegs.length();j++){ // jsteps = ( (jsonobject)jlegs.get(j)).getjsonarray("steps"); /** getting distance json data */ jdistance = ((jsonobject) jlegs.get(j)).getjsonobject("distance"); hashmap<string, string> hmdistance = new hashmap<string, string>(); hmdistance.put("distance", jdistance.getstring("text")); /** getting duration json data */ jduration = ((jsonobject) jlegs.get(j)).getjsonobject("duration"); hashmap<string, string> hmduration = new hashmap<string, string>(); hmduration.put("duration", jduration.getstring("text")); /** adding distance object path */ path.add(hmdistance); /** adding duration object path */ path.add(hmduration); jsteps = ( (jsonobject)jlegs.get(j)).getjsonarray("steps"); /** traversing 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 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 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; { 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; { 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; } }
for application need access database contains places, examples google places or yelp instance.
the process same did parsing directions. query api sending http request correctly formed url, download returned data (most in json format), parse , add markers
.
links documentation of apis have mentionned
https://developers.google.com/places/documentation/ http://www.yelp.com/developers/documentation/v2/overview
Comments
Post a Comment