Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

get nearest location based on latitude and longitude javascript

function distance(lat1, lon1, lat2, lon2, unit) {
    	var radlat1 = Math.PI * lat1/180
    	var radlat2 = Math.PI * lat2/180
    	var theta = lon1-lon2
    	var radtheta = Math.PI * theta/180
    	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    	if (dist > 1) {
    		dist = 1;
    	}
    	dist = Math.acos(dist)
    	dist = dist * 180/Math.PI
    	dist = dist * 60 * 1.1515
    	if (unit=="K") { dist = dist * 1.609344 }
    	if (unit=="N") { dist = dist * 0.8684 }
    	return dist
    }

    var data = [{
        "code": "0001",
        "lat": "1.28210155945393",
        "lng": "103.81722480263163",
        "location": "Stop 1"
    }, {
        "code": "0003",
        "lat": "1.2777380589964",
        "lng": "103.83749709165197",
        "location": "Stop 2"
    }, {
        "code": "0002",
        "lat": "1.27832046633393",
        "lng": "103.83762574759974",
        "location": "Stop 3"
    }];

    var html = "";
    var poslat = 1.28210155945393;
    var poslng = 103.81722480263163;

    for (var i = 0; i < data.length; i++) {
        // if this location is within 0.1KM of the user, add it to the list
        if (distance(poslat, poslng, data[i].lat, data[i].lng, "K") <= 0.1) {
            html += '<p>' + data[i].location + ' - ' + data[i].code + '</p>';
        }
    }

    $('#nearbystops').append(html);
Comment

PREVIOUS NEXT
Code Example
Javascript :: convert js date time to mysql datetime 
Javascript :: ex:loop array 
Javascript :: operators in javascript 
Javascript :: passport jwt npm 
Javascript :: send post request 
Javascript :: javascript remove scientific notation 
Javascript :: Date toLocaleDateString Javascript 
Javascript :: Factorialize a Number 
Javascript :: moment 
Javascript :: Alpinejs notification 
Javascript :: regex[ress for password 
Javascript :: convert nuber into string react js 
Javascript :: react mid senior dev interview questuions 
Javascript :: react time input 
Javascript :: Capturing enter in javascript 
Javascript :: solo números js 
Javascript :: how to store object in session storage 
Javascript :: how to apply border to table in angular 
Javascript :: javascript to camelcase 
Javascript :: tolocale string no seconds 
Javascript :: indexof javascript duplicate arrays 
Javascript :: js history 
Javascript :: nestjs set swagger api keys 
Javascript :: convert exp date token to date 
Javascript :: javascript add to html 
Javascript :: getting data from an api 
Javascript :: npm install could not resolve peerDependencies 
Javascript :: check browser 
Javascript :: array map 
Javascript :: check url if it has trailing slash 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =