in Advanced 

Question preview

HomeQuestion preview:
Log in

How to get Distance using Google Map API

image
ANONYMOUS
23:41/17.08.2010
JavaScript
OPEN
Do any one know how to get Distance of two locations when an user entered? using google API
Do you know someone who could answer? Ask him for help
Answers: 2
Sort by: date rating
image xpert
11:01/19.08.2010
3 from possible 5 with 1 votes
Here is complete example posted on google site for MAP API Version 3:

http://www.barattalo.it/examples/ruler.html

Base function from the above sample that calculates the distance is:
function distance(lat1,lon1,lat2,lon2) {
	var R = 6371; // km (change this constant to get miles)
	var dLat = (lat2-lat1) * Math.PI / 180;
	var dLon = (lon2-lon1) * Math.PI / 180; 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * 
		Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	if (d>1) return Math.round(d)+"km";
	else if (d<=1) return Math.round(d*1000)+"m";
	return d;
}

In this sample the elevation of the two points is ignored and it is assumed that the Earth is a sphere.
More details on formula you can get by searching google for "distance spherical coordinate system".
Vote:
image jbloch
09:22/19.05.2011
-
var location1
var location2
function AddDistance(Add1,Add2) 
{
   geocoder = new google.maps.Geocoder(); 
   if (geocoder) 
   {
		geocoder.geocode( { 'address': Add1}, function(results, status) 
		{
			if (status == google.maps.GeocoderStatus.OK) 
			{
				location1 = results[0].geometry.location;
		      }
               });
		geocoder.geocode( { 'address': Add2}, function(results, status) 
		{
			if (status == google.maps.GeocoderStatus.OK) 
			{
				location2 = results[0].geometry.location;				
				showMap();	
			} 
		});
		
	}
	
}
function showMap()
{
  	
	latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
	
    var myOptions = {
    zoom: 1,
    center:latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
	
	
		directionsService = new google.maps.DirectionsService();
		directionsDisplay = new google.maps.DirectionsRenderer(
		{
			suppressMarkers: true,
			suppressInfoWindows: true
		});
		directionsDisplay.setMap(map);
		var request = {
			origin:location1, 
			destination:location2,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		directionsService.route(request, function(response, status) 
		{
			if (status == google.maps.DirectionsStatus.OK) 
			{
				directionsDisplay.setDirections(response);
			}
		});
		
		// show a line between the two points
		var line = new google.maps.Polyline({
			map: map, 
			path: [location1, location2],
			strokeWeight: 7,
			strokeOpacity: 0.8,
			strokeColor: "#FFAA00"
		});
		
		var line1 = new google.maps.Polyline({
			map: map, 
			path: [myLatlng, location2],
			strokeWeight: 7,
			strokeOpacity: 0.8,
			strokeColor: "#FFAA00"
		});
		// create the markers for the two locations		
		var marker1 = new google.maps.Marker({
			map: map, 
			position: location1,
			title: "Location1"
                        icon='icon name'
			
		});
		var marker2 = new google.maps.Marker({
			map: map, 
			position: location2,
			title: "AirPort",
			icon: 'icon name'
		});
				
		var R = 6371; 
		var dLat = toRad(location2.lat()-location1.lat());
		var dLon = toRad(location2.lng()-location1.lng()); 		
				
		var dLat1 = toRad(location1.lat());
		var dLat2 = toRad(location2.lat());		
		
		var a1 = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(dLat1) * Math.cos(dLat1) * 
				Math.sin(dLon/2) * Math.sin(dLon/2); 
		
		var c = 2 * Math.atan2(Math.sqrt(a1), Math.sqrt(1-a1)); 
		
		var d = R * c;
		
		// create the text to be shown in the infowindows
		var text1 =	'<b><font color=red>Distance</font></b> <br> : '+Math.floor(d)+' To '+Math.floor(d+1)+ 'Km'
		var text2 = '<b><font color=red>Distance</font></b> <br> : '+Math.floor(d)+' To '+Math.floor(d+1)+ 'Km'				
		
		// create info boxes for the two markers
		var infowindow1 = new google.maps.InfoWindow({
			content: text1
		});
		var infowindow2 = new google.maps.InfoWindow({
			content: text2
		});
		

		// add action events so the info windows will be shown when the marker is clicked
		google.maps.event.addListener(marker1, 'click', function() {
			infowindow1.open(map,marker1);
		});
		google.maps.event.addListener(marker2, 'click', function() {
			infowindow2.open(map,marker2);
		});
	}
function toRad(deg) 
{
	return deg * Math.PI/180;
}	
Vote:
Please vote! Your opinion matters!
If you haven't found what you've looking for, post a question
Ask question
| Home | Hall of fame | Registration | Log in | Terms of service | Privacy policy | Help | Contacts | RSS |