Site icon Mobile App Development Services

What is Google Maps Geometry Library & How it Works?

Man looking for route on map in mobile app. Geolocation, bus stop, direction. Flat vector illustration. Navigation concept can be used for presentations, banner, website design, landing web page

The earth is round, the map is flat

When calculating the distance between two latitudes and longitudes we need to take the fact that maps are flat, however, the Earth is three-dimensional (round) and is approximated as a sphere.

The black line is the shortest path possible but when plotting on flat map it will look like an arc (the red line). Therefore calculating distance between two coordinates needs to use very advanced mathematics.

Fortunately, with Google Maps API 3 libraries, Google Map offers a Geometry library which makes it very simple to calculate distance.

Google Maps geometry library provides functions for the computation of geometric data on the surface of the earth. All it requires is to call the computeDistanceBetween() function passing it two LatLng objects.

Loading the Maps JavaScript API

http://maps.google.com/maps/api/js?libraries=geometry&sensor=true&key=YOUR_API_KEY

Geometry Library Namespaces

Contains spherical geometry utilities allowing you to compute angles, distances & areas from coordinates (latitudes and longitudes).

Contains utilities for encoding and decoding paths for polylines and polygons. Useful to compress bulky list of coordintes.

Calculating Distance

var location1 = new google.maps.LatLng(38.715, -74.002);
var location2 = new google.maps.LatLng(41.506, -0.119);
var distance = google.maps.geometry.spherical.computeDistanceBetween(location1, location2);

Results are returned in meters.

Computing Heading

var location1 = new google.maps.LatLng(38.715, -74.002);
var location2 = new google.maps.LatLng(41.506, -0.119);
const heading = google.maps.geometry.spherical.computeHeading(
    location1,
    location2
  );

Results are returned in degrees from the north.

Calculating Area

var location1 = new google.maps.LatLng(38.715, -74.002);
var location2 = new google.maps.LatLng(41.506, -0.119);
var location3 = new google.maps.LatLng(20.916, -43.251);
var area = google.maps.geometry.spherical.computeArea([location1, location2, location3]);

Code above will calculate the area of a triangle between three locations provided to computeArea()

Conclusion

Calculating area, heading and distances on geo coordinates can be tricky and may require advanced mathematics, but with the help of the Google Maps Geometry Library it’s really simple. Thanks for reading.