RSS

Get distance from the current location

19 Apr

This tutorial demonstrates how to calculate distance  to the specified destination from your location.

Demo           Download

Here is the complete source code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.7.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://j.maxmind.com/app/geoip.js"></script>


<script type="text/javascript">

var directionRenderer;
var directionsService = new google.maps.DirectionsService();
var map;

$(document).ready(function () {

// Set up map starting point for Google Maps.
// Set initial coords to latitude 7 and longitude 81, which is somewhere
// around Kansas City in the center of the US, and then set the zoom to 4
// so the entire US is visible and centered.
var kansas = new google.maps.LatLng(81,7);
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: kansas
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);

// wire up button click
$('#go').click(function () {
// Use our new getLatLng with fallback and define an inline function to
// handle the callback.
getLatLng(function (latitude, longitude, isMaxMind) {
// set the starting point
var start = new google.maps.LatLng(latitude, longitude);

// get the address the user entered
var address = $('#address').val();
if (address) {
// set end point
var end = $('#address').val();

// set the request options
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

// make the directions request
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {

// Display the directions using Google's Directions
// Renderer.
directionsRenderer.setDirections(result);

// output total distance separately
var distance = getTotalDistance(result);
// output either miles or km
var units = $('#units').val();
if (units == 'IMPERIAL') {
$('#distance').html('Total Distance: <strong>' +
metersToMiles(distance) + '</strong> miles');
} else {
$('#distance').html('Total Distance: <strong>' +
metersToKilometers(distance) + '</strong> km');
}

} else {
error("Directions failed due to: " + status);
}
});

}
else {
error('Please enter an address');
}

// if we used MaxMind for location, add attribution link
if (isMaxMind) {
$('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP to Location Service Provided by               MaxMind</a></p>');
}
});
});

});

function getLatLng(callback) {
// test for presence of geolocation
if (navigator && navigator.geolocation) {
// make the request for the user's position
navigator.geolocation.getCurrentPosition(function (position) {
// success handler
callback(position.coords.latitude, position.coords.longitude);
},
function (err) {
// handle the error by passing the callback the location from MaxMind
callback(geoip_latitude(), geoip_longitude(), true);
});
} else {
// geolocation not available, so pass the callback the location from
// MaxMind
callback(geoip_latitude(), geoip_longitude(), true);
}
}

// return total distance in meters
function getTotalDistance(result) {
var meters = 0;
var route = result.routes[0];
for (ii = 0; ii < route.legs.length; ii++) {
// Google stores distance value in meters
meters += route.legs[ii].distance.value;
}
return meters;
}

function metersToKilometers(meters) {
return Math.round(meters / 1000);
}

function metersToMiles(meters) {
// 1 mile = 1609.344 meters
return Math.round(meters / 1609.344);
}

function error(msg) {
alert(msg);
}

</script>
</head>

<body>
<div>
<label for="address">Enter a Destination Address:</label>
<input type="text" id="address" />
</div>

<div>
<label for="units">Units:</label>
<select id="units">
<option value="IMPERIAL">Miles</option>
<option value="METRIC">Kilometers</option>
</select>
</div>

<div>
<input type="button" id="go" value="Get Directions" />
</div>

<div id="distance"></div>

<div id="map"></div>

</body>
</html>


Advertisements
 
Leave a comment

Posted by on April 19, 2012 in Geo Programming, JavaScript

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: