One of the most recurrent needs of developers when working with Google Maps, is how to obtain the distance between 2 different points on the map, usually defined by Markers or just by plain coordinates, for example given the following code:
This will place the 2 markers that appear on the picture of this article. According to Google, we can know that the flight distance from Bucaramanga to Bogota is about 280 Kilometers:
So we will theorically expect an approximated value from our methods to obtain the distance between the 2 coordinates. In this article, we will show you 2 ways to obtain the distance between 2 markers or coordinates with JavaScript in Google Maps.
A. Using Google Geometry Module
By default, Google provides a custom way to obtain the distance between 2 points on the map using the Geometry library. You need to include this library by appending the &libraries
get parameter to the request URL of the Google Maps JS API:
Once you are sure that have loaded this library, you can now obtain the distance between 2 coordinates (LatLng object) from Google Maps through the google.maps.geometry.spherical.computeDistanceBetween method. For example, if you want to obtain the distance between 2 markers, you may simply run the following instruction:
As you can see, the computeDistanceBetween method expects as first and second argument a LatLng object. It will compute the distance from those 2 parameters and return the value in meters. Is up to you to change the units mathematically to Miles or Kilometers. Alternatively if you are not using markers, you may provide the mentioned LatLng object as arguments with the direct coordinates:
B. Using the Haversine formula
If instead of relying on Google Maps, you can calculate the same distance based on the Haversine Formula, an important equation used in navigation, this provides great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
To start, include the 2 following functions in your code:
The first function allows you to convert a degree into radians, necessary in the function of interest, the getDistanceBetweenPoints
method. In this case, with a slightly modification from the original snippet of RosettaCode. The function receives four arguments that correspond respectively to the latitude and longitude values of both points. This solution doesn't rely on Google Maps so it can be used in other projects as well:
Happy coding !
Comments
Post a Comment