android - How to calculate distance from different markers in a map and then pick up the least one -
i have distance different markers on map current location of device , pick shortest one. have lat , long markers , current location lat , long can fetched dynamically.
suppose have 5 markers on map, bangalore (lat : 12.971599, long : 77.594563), delhi (lat : 28.635308, long : 77.224960), mumbai (lat : 19.075984, long : 72.877656), chennai (lat : 13.052414, long : 80.250825), kolkata (lat : 22.572646, long : 88.363895).
now suppose user standing somewhere near hyderabad (lat : 17.385044, long : 78.486671). when user clicks button, app should calculate distance each marker , pick , return shortest one, bangalore here.
there way possible of local databases. can on please.?
can suggest me nice way this, or come code if please can. thanx in advance.
from comment see expect maximum of 70-80 locations. not much.
you can brute force search on markers , take minimum.
iterate on markers, , search min distance:
list<marker> markers = createmarkers(); // returns arraylist<markers> data source int minindex = -1; double mindist = 1e38; // initialize huge value overwritten int size = markers.size(); (int = 0; < size; i++) { marker marker = markers.get(i); double curdistance = calcdistance(curlatitude, curlongitude, marker.latitude, marker.longitude); if (curdistance < mindist) { mindist = curdistance; // update neares minindex = i; // store index of nearest marker in minindex } } if (minindex >= 0) { // nearest maker found: marker nearestmarker = markers.get(minindex); // todo nearesr marker } else { // list of markers empty }
for calcdistance, use distance calculation method provided android. (e.g location.distanceto()
)
70-80 markers there no need make faster , more complex. if have thousands points worth invest in faster solution (using spatial index, , own distance calculation avoids sqrt calc).
just print out current time in milli seconds @ begin , @ end of nearest maker search, , see, fast enough.
Comments
Post a Comment