Created
April 13, 2016 14:23
-
-
Save tlfrd/6a6b5ce95e9115313be349a21c0d8951 to your computer and use it in GitHub Desktop.
Which Unboxed office is closer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<p>Click the button to get your coordinates.</p> | |
<button onclick="getLocation()">Try It</button> | |
<p id="demo"></p> | |
<script> | |
var x = document.getElementById("demo"); | |
var london = { lat: 51.521131, long: -0.077818 }; | |
var capeTown = { lat: -33.981384, long: 18.464796 }; | |
var londonDist, capeTownDist; | |
function getLocation() { | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(showPosition); | |
} else { | |
x.innerHTML = "Geolocation is not supported by this browser."; | |
} | |
} | |
function showPosition(position) { | |
londonDist = getDistanceFromLatLonInKm(position.coords.latitude, position.coords.longitude, london.lat, london.long); | |
capeTownDist = getDistanceFromLatLonInKm(position.coords.latitude, position.coords.longitude, capeTown.lat, capeTown.long); | |
x.innerHTML = "Latitude: " + position.coords.latitude + | |
"<br>Longitude: " + position.coords.longitude + "<br>" + | |
"<br>Distance to London: " + londonDist + " km" + | |
"<br>Distance to Cape Town: " + capeTownDist + " km" + | |
"<br>The closest office to you is: " + closestLocation("London", "capeTown", londonDist, capeTownDist); | |
} | |
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) { | |
var R = 6371; // Radius of the earth in km | |
var dLat = deg2rad(lat2-lat1); // deg2rad below | |
var dLon = deg2rad(lon2-lon1); | |
var a = | |
Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * | |
Math.sin(dLon/2) * Math.sin(dLon/2) | |
; | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); | |
var d = R * c; // Distance in km | |
return d; | |
} | |
function deg2rad(deg) { | |
return deg * (Math.PI/180) | |
} | |
function closestLocation(loc1name, loc2name, loc1dist, loc2dist) { | |
if (loc1dist < loc2dist) { | |
return loc1name; | |
} else { | |
return loc2name; | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment