How to find distance (by road) between 2 geo points in Android application without using google map direction api? -
i developing android application. need find distance between 2 geo coordinates.
i used location.distancebetween()
, location.distanceto()
functions. these functions give straight distance, actual distance different when travel road.
use google api as
public float getdistance(double lat1, double lon1, double lat2, double lon2) { string result_in_kms = ""; string url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric"; string tag[] = {"text"}; httpresponse response = null; try { httpclient httpclient = new defaulthttpclient(); httpcontext localcontext = new basichttpcontext(); httppost httppost = new httppost(url); response = httpclient.execute(httppost, localcontext); inputstream = response.getentity().getcontent(); documentbuilder builder = documentbuilderfactory.newinstance().newdocumentbuilder(); document doc = builder.parse(is); if (doc != null) { nodelist nl; arraylist args = new arraylist(); (string s : tag) { nl = doc.getelementsbytagname(s); if (nl.getlength() > 0) { node node = nl.item(nl.getlength() - 1); args.add(node.gettextcontent()); } else { args.add(" - "); } } result_in_kms =string.valueof( args.get(0)); } } catch (exception e) { e.printstacktrace(); } float f=float.valueof(result_in_kms); return f*1000; }
or can use following function
public final static double average_radius_of_earth = 6371; public float calculatedistance(double userlat, double userlng, double venuelat, double venuelng) { double latdistance = math.toradians(userlat - venuelat); double lngdistance = math.toradians(userlng - venuelng); double = (math.sin(latdistance / 2) * math.sin(latdistance / 2)) + (math.cos(math.toradians(userlat))) * (math.cos(math.toradians(venuelat))) * (math.sin(lngdistance / 2)) * (math.sin(lngdistance / 2)); double c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)); return (float) (math.round(average_radius_of_earth * c)); }
Comments
Post a Comment