get nearest location based on latitude and longitude javascript

Solutions on MaxInterview for get nearest location based on latitude and longitude javascript by the best coders in the world

showing results for - "get nearest location based on latitude and longitude javascript"
Valeria
24 Jul 2019
1function distance(lat1, lon1, lat2, lon2, unit) {
2    	var radlat1 = Math.PI * lat1/180
3    	var radlat2 = Math.PI * lat2/180
4    	var theta = lon1-lon2
5    	var radtheta = Math.PI * theta/180
6    	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
7    	if (dist > 1) {
8    		dist = 1;
9    	}
10    	dist = Math.acos(dist)
11    	dist = dist * 180/Math.PI
12    	dist = dist * 60 * 1.1515
13    	if (unit=="K") { dist = dist * 1.609344 }
14    	if (unit=="N") { dist = dist * 0.8684 }
15    	return dist
16    }
17
18    var data = [{
19        "code": "0001",
20        "lat": "1.28210155945393",
21        "lng": "103.81722480263163",
22        "location": "Stop 1"
23    }, {
24        "code": "0003",
25        "lat": "1.2777380589964",
26        "lng": "103.83749709165197",
27        "location": "Stop 2"
28    }, {
29        "code": "0002",
30        "lat": "1.27832046633393",
31        "lng": "103.83762574759974",
32        "location": "Stop 3"
33    }];
34
35    var html = "";
36    var poslat = 1.28210155945393;
37    var poslng = 103.81722480263163;
38
39    for (var i = 0; i < data.length; i++) {
40        // if this location is within 0.1KM of the user, add it to the list
41        if (distance(poslat, poslng, data[i].lat, data[i].lng, "K") <= 0.1) {
42            html += '<p>' + data[i].location + ' - ' + data[i].code + '</p>';
43        }
44    }
45
46    $('#nearbystops').append(html);