Geolocation Distance Sorting Example
This is an example demo to go with the article Geo-sorting: Using Device Geolocation to Sort by Distance.
You are viewing the low-end device version of the demo. It takes manual location input, geocodes the address using the Google Geocoding API, and uses Google static map tiles instead of dynamic javascript maps.
The high-end version uses the HTML5 Geolocation API, and the Google Maps API. View high-end version
‘;
// geosort-lowend.php
// Server side location based sorting
$locations = array(array(“id” => “office-us”, “latlon” => “40.7251397,-73.9918808”, “address” => “NEW YORK – 315 Bowery, Manhattan, New York, USA”),
array(“id” => “office-irl”, “latlon” => “53.349635, -6.250268”, “address” => “DUBLIN – 2 La Touche House, IFSC, Dublin 1, Ireland”),
array(“id” => “office-de”, “latlon” => “52.489405,13.359632”, “address” => “BERLIN – Hauptstrasse 155, Schoneberg, Berlin, Germany”));
$address = isset($_GET[‘address’])?filter_var($_GET[‘address’], FILTER_SANITIZE_STRING):”;
$latlon = ”;
function geocodeAddress($address) {
$API_REQ = “http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=”;
$req = $API_REQ . urlencode($address);
// Send API request to Google geocoder
$response = file_get_contents($req);
// Parse json response
$response = json_decode($response, true);
$lat = $response[‘results’][0][‘geometry’][‘location’][‘lat’];
$lon = $response[‘results’][0][‘geometry’][‘location’][‘lng’];
return array(‘lat’=> $lat, ‘lon’ => $lon);
}
function geoDistance ($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo – $latFrom;
$lonDelta = $lonTo – $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
function sortResults($address, &$locations) {
global $latlon;
$latlon = geocodeAddress($address);
usort($locations, compare);
}
function compare($a, $b) {
global $latlon;
$locA = array_map(‘floatval’, array_map(‘trim’, explode(‘,’, $a[‘latlon’])));
$locB = array_map(‘floatval’, array_map(‘trim’, explode(‘,’, $b[‘latlon’])));
$distA = geoDistance($latlon[‘lat’], $latlon[‘lon’], $locA[0], $locA[1]);
$distB = geoDistance($latlon[‘lat’], $latlon[‘lon’], $locB[0], $locB[1]);
if($distA == $distB) {
return 0;
}
return ($distA < $distB) ? -1 : 1;
}
if(!empty($address)) {
sortResults($address, $locations);
}
?>
Our offices
-
500) $zoom=17;
- View low-end version
Our offices
- NEW YORK – 315 Bowery, Manhattan, New York, USA
- DUBLIN – 2 La Touche House, IFSC, Dublin 1, Ireland
- BERLIN – Hauptstrasse 155, Schoneberg, Berlin, Germany
function sortResults(position) { // Grab current position var latlon = new LatLon(position.coords.latitude, position.coords.longitude);
var locations = document.getElementById('locations'); var locationList = locations.querySelectorAll('li'); //Covert NodeList to array var locationArray = Array.prototype.slice.call(locationList, 0);
//Sort, using inline comparartor function locationArray.sort(function(a,b){ var locA = a.getAttribute('data-latlon').split(','); var locB = b.getAttribute('data-latlon').split(',');
distA = latlon.distanceTo(new LatLon(Number(locA[0]),Number(locA[1]))); distB = latlon.distanceTo(new LatLon(Number(locB[0]),Number(locB[1])));
return distA - distB; });
//Reorder the list locations.innerHTML = ""; locationArray.forEach(function(el) { locations.appendChild(el); });
}
Now read the Geo-sorting: Using Device Geolocation to Sort by Distance article!
$url .= ‘&zoom=’.$zoom.’&size=’.$max_width.’x’.$max_height.’&maptype=roadmap&sensor=false’;
?>