开发者

"Find Nearest" process for mobile device webapp?

Looking to implement a "Find N开发者_StackOverflowearest" process for a mobile web application that will auto select the closest match of an item in a dropdown list in a form based on the user's current location.

Assuming we have the lat/long for each element of our list, and the persons location from the mobile device, what is the best method to locate the closest item? We will have approx 150-200 possible items and want the one closest to the user so we can set it as the default.

Is there a means to efficiently do this in JS or would it be better suited to server side?


You'll need a loop to calculate distance and henceforth, the closest. Use the Haversine formula:

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad(); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var distance = R * c;

Better run your own benchmarks to find out if it would be better to do this server-side or client-side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜