Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@johnbhartley
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbhartley/9eb5050cb5a1f654e001 to your computer and use it in GitHub Desktop.
Save johnbhartley/9eb5050cb5a1f654e001 to your computer and use it in GitHub Desktop.
Distance between lat/long coordinates
<script>
// from http://html5doctor.com/finding-your-position-with-geolocation/
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
console.log("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
// save lat long as cookies
// via http://www.satya-weblog.com/2007/05/php-and-javascript-cookie.html
document.cookie = 'lat='+position.coords.latitude;
document.cookie = 'long='+ position.coords.longitude;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
console.log("Error: " + errors[error.code]);
}
</script>
<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
// grab from $_COOKIE
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
$lat = $_COOKIE['lat'];
$long = $_COOKIE['long'];
// echo user distance to set location (second set of lat long)
echo distance($lat, $long, 29.46786, -98.53506, "M") . " Miles<br />";
echo distance($lat, $long, 29.46786, -98.53506, "K") . " Kilometers<br />";
echo distance($lat, $long, 29.46786, -98.53506, "N") . " Nautical Miles<br />";
?>
via http://www.geodatasource.com/developers/php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment