Calculate distance in km from longitude e latitude of google maps

#1

Hi, how to calculate the distance from two langitude e latitude points.

i would to calculate the distance from my geo position and a set of points.

what is the best way to calculate this?

Thank you!

#2

i found this method of google api v3

var myLatLng1 = { lat: 40.634315, lng: 14.602552 };
var myLatLng2 = {lat: 40.04215, lng: 14.102552 };

google.maps.geometry.spherical.computeDistanceBetween(myLatLng1, myLatLng2);

but return this error

Uncaught (in promise): TypeError: Cannot read property 'spherical' of undefined

#3

google.maps.geometry.spherical.computeDistanceBetween(myPos, new google.maps.LatLng(myLatLng1, myLatLng2));

#4

thanks yes i know but how to import geometry spherical object?

#5

Unhandled Promise rejection: Cannot read property 'spherical' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'spherical' of undefined

how to import google.maps.geometry?

#6

do you use
declare var google: any;
?

#7

yes i delcare var google but i can’t import geometry spherical object.
Any solution?

#8

Maybe this functions can help to get an approach. You should translate them into TypeScript, or ES6.

function degToRad(n)
{
	return n * Math.PI / 180;
}

function radToDeg(n)
{
	return n * 180 / Math.PI;
}

function getDistance(lat1, lon1, lat2, lon2, mode)
{	
	var R = 6371; // Earth radius in km
	
	switch(mode)
	{	
		case 'spherical':
		default:
			var dLon = degToRad(lon2 - lon1);
			lat1 = degToRad(lat1);
			lat2 = degToRad(lat2);
			var d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(dLon)) * R;
		break;	
		
		case 'haversine':
			var dLat = degToRad(lat2 - lat1);
			var dLon = degToRad(lon2 - lon1);
			lat1 = degToRad(lat1);
			lat2 = degToRad(lat2);
			var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); 
			var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
			var d = R * c;
		break;	
		
		case 'rectangle':
			var x = degToRad(lon2 - lon1) * Math.cos(degToRad(lat1 + lat2) / 2);
			var y = degToRad(lat2 - lat1);
			var d = Math.sqrt(x * x + y * y) * R;
		break;	
	}
		
	return d;	
}
2 Likes
Showing maps with markers
#9

You need to add google map geometry library in index.html file
something similar to this <script src="http://maps.google.com/maps/api/js?key=YOU_GOOGLE_MAP_KEY&libraries=geometry"></script>