Geometry Library Stay organized with collections Save and categorize content based on your preferences.
AI-generated Key Takeaways
The Google Maps Javascript API geometry library provides utility functions for calculating geometric data on the Earth's surface, such as distances, areas, and headings.
This library includes functionalities for encoding and decoding polylines, offering a way to compress and manage path data efficiently.
It enables the determination of a point's location relative to polygons and polylines, allowing you to check if a point is inside a polygon or on the edge of a polyline/polygon.
To use these functionalities, you need to explicitly include the
geometrylibrary when loading the Maps Javascript API using thelibrariesbootstrap parameter.
Overview
The concepts within this document refer to features only available within thegoogle.maps.geometry library. This library is not loaded by default when you load the Maps Javascript API but must be explicitly specified through use of alibraries bootstrap parameter. For more information, see theLibraries Overview.
The Maps JavaScript API geometry library provides utility functions for the computation of geometric data on the surface of the Earth. The library includes three namespaces:
sphericalcontains spherical geometry utilities allowing you to compute angles, distances and areas from latitudes and longitudes.encodingcontains utilities for encoding and decoding polyline paths according to theEncoded Polyline Algorithm.polycontains utility functions for computations involving polygons and polylines.
Thegoogle.maps.geometry library does not contain anyclasses; instead, the library contains static methods on the abovenamespaces.
Spherical Geometry Concepts
The images within the Maps JavaScript API are two-dimensionaland "flat." The Earth, however, is three-dimensional, and is oftenapproximated as either anoblate spheroidor more as a sphere. Within the Maps API we use a sphere, and torepresent the Earth on a two-dimensional flat surface — such asyour computer screen — the Maps API uses aprojection.
Within 2D projections, appearances can sometimes be deceiving.Because the map projection necessarily requires some distortion, simpleEuclidian geometry often is not applicable. For example, the shortest distancebetween two points on a sphere is not a straight line, but a great circle(a type of geodesic), and the angles that make up a triangle on the surfaceof a sphere add up to more than 180 degrees.
Because of these differences, geometric functions on a sphere (or on itsprojection) necessitate usingSpherical Geometryto calculate such constructs as distance, heading, and area. Utilities tocalculate these spherical geometric constructs are contained within the MapsAPI'sgoogle.maps.geometry.spherical namespace. This namespaceprovides static methods for computing scalar values from spherical coordinates(latitudes and longitudes).
Distance and Area Functions
The distance between two points is the length of the shortest path betweenthem. This shortest path is called a geodesic. On a sphere all geodesics aresegments of a great circle. To compute this distance, callcomputeDistanceBetween(), passing it twoLatLngobjects.
You may instead usecomputeLength() to calculate the lengthof a given path if you have several locations.
Distance results are expressed in meters.
To compute the area (in square meters) of a polygonal area, callcomputeArea(), passing the array ofLatLng objects defining a closed loop.
Navigation Functions
When navigating on a sphere, a heading is the angle of a directionfrom a fixed reference point, usually true north. Within the Google Maps API,a heading is defined in degrees from true north, where headings are measuredclockwise from true north (0 degrees). You may compute this heading betweentwo locations with thecomputeHeading() method, passing it twofrom andtoLatLng objects.
Given a particular heading, an origin location, and the distance totravel (in meters), you can calculate the destination coordinates usingcomputeOffset().
Given twoLatLng objects and value between 0 and 1, you mayalso calculate a destination between them using theinterpolate() method, which performs spherical linearinterpolation between the two locations, where the value indicatesthe fractional distance to travel along the path from the origin tothe destination.
The following example creates two polylines when you click two pointson the map — one geodesic and one "straight" line connecting the twolocations — and computes the heading for travelling between thetwo points:
TypeScript
// This example requires the Geometry library. Include the libraries=geometry// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">letmarker1:google.maps.Marker,marker2:google.maps.Marker;letpoly:google.maps.Polyline,geodesicPoly:google.maps.Polyline;functioninitMap():void{constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:4,center:{lat:34,lng:-40.605},});map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById("info")asHTMLElement);marker1=newgoogle.maps.Marker({map,draggable:true,position:{lat:40.714,lng:-74.006},});marker2=newgoogle.maps.Marker({map,draggable:true,position:{lat:48.857,lng:2.352},});constbounds=newgoogle.maps.LatLngBounds(marker1.getPosition()asgoogle.maps.LatLng,marker2.getPosition()asgoogle.maps.LatLng);map.fitBounds(bounds);google.maps.event.addListener(marker1,"position_changed",update);google.maps.event.addListener(marker2,"position_changed",update);poly=newgoogle.maps.Polyline({strokeColor:"#FF0000",strokeOpacity:1.0,strokeWeight:3,map:map,});geodesicPoly=newgoogle.maps.Polyline({strokeColor:"#CC0099",strokeOpacity:1.0,strokeWeight:3,geodesic:true,map:map,});update();}functionupdate(){constpath=[marker1.getPosition()asgoogle.maps.LatLng,marker2.getPosition()asgoogle.maps.LatLng,];poly.setPath(path);geodesicPoly.setPath(path);constheading=google.maps.geometry.spherical.computeHeading(path[0],path[1]);(document.getElementById("heading")asHTMLInputElement).value=String(heading);(document.getElementById("origin")asHTMLInputElement).value=String(path[0]);(document.getElementById("destination")asHTMLInputElement).value=String(path[1]);}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
JavaScript
// This example requires the Geometry library. Include the libraries=geometry// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">letmarker1,marker2;letpoly,geodesicPoly;functioninitMap(){constmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center:{lat:34,lng:-40.605},});map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById("info"),);marker1=newgoogle.maps.Marker({map,draggable:true,position:{lat:40.714,lng:-74.006},});marker2=newgoogle.maps.Marker({map,draggable:true,position:{lat:48.857,lng:2.352},});constbounds=newgoogle.maps.LatLngBounds(marker1.getPosition(),marker2.getPosition(),);map.fitBounds(bounds);google.maps.event.addListener(marker1,"position_changed",update);google.maps.event.addListener(marker2,"position_changed",update);poly=newgoogle.maps.Polyline({strokeColor:"#FF0000",strokeOpacity:1.0,strokeWeight:3,map:map,});geodesicPoly=newgoogle.maps.Polyline({strokeColor:"#CC0099",strokeOpacity:1.0,strokeWeight:3,geodesic:true,map:map,});update();}functionupdate(){constpath=[marker1.getPosition(),marker2.getPosition()];poly.setPath(path);geodesicPoly.setPath(path);constheading=google.maps.geometry.spherical.computeHeading(path[0],path[1],);document.getElementById("heading").value=String(heading);document.getElementById("origin").value=String(path[0]);document.getElementById("destination").value=String(path[1]);}window.initMap=initMap;
Try Sample
Encoding Methods
Paths within the Maps JavaScript API are often specified as anArray ofLatLng objects. However, passing aroundsuch an array is often bulky. You may instead use Google'spolylineencoding algorithm to compress a given path, which you can laterdecompress through decoding.
Thegeometrylibrary contains anencodingnamespace for utilities to encode and decode polylines.
The static methodencodePath() encodes the given path.You may pass either an array ofLatLngs or anMVCArray (which is returned byPolyline.getPath()).
To decode an encoded path, calldecodePath()passing the method the encoded string.
The following example displays a map of Oxford, Mississippi.Clicking on the map adds a point to a polyline. As the polyline isconstructed, its encoding appears underneath.
TypeScript
// This example requires the Geometry library. Include the libraries=geometry// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">functioninitMap():void{constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:14,center:{lat:34.366,lng:-89.519},});constpoly=newgoogle.maps.Polyline({strokeColor:"#000000",strokeOpacity:1,strokeWeight:3,map:map,});// Add a listener for the click eventgoogle.maps.event.addListener(map,"click",(event)=>{addLatLngToPoly(event.latLng,poly);});}/** * Handles click events on a map, and adds a new point to the Polyline. * Updates the encoding text area with the path's encoded values. */functionaddLatLngToPoly(latLng:google.maps.LatLng,poly:google.maps.Polyline){constpath=poly.getPath();// Because path is an MVCArray, we can simply append a new coordinate// and it will automatically appearpath.push(latLng);// Update the text field to display the polyline encodingsconstencodeString=google.maps.geometry.encoding.encodePath(path);if(encodeString){(document.getElementById("encoded-polyline")asHTMLInputElement).value=encodeString;}}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
JavaScript
// This example requires the Geometry library. Include the libraries=geometry// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">functioninitMap(){constmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:14,center:{lat:34.366,lng:-89.519},});constpoly=newgoogle.maps.Polyline({strokeColor:"#000000",strokeOpacity:1,strokeWeight:3,map:map,});// Add a listener for the click eventgoogle.maps.event.addListener(map,"click",(event)=>{addLatLngToPoly(event.latLng,poly);});}/** * Handles click events on a map, and adds a new point to the Polyline. * Updates the encoding text area with the path's encoded values. */functionaddLatLngToPoly(latLng,poly){constpath=poly.getPath();// Because path is an MVCArray, we can simply append a new coordinate// and it will automatically appearpath.push(latLng);// Update the text field to display the polyline encodingsconstencodeString=google.maps.geometry.encoding.encodePath(path);if(encodeString){document.getElementById("encoded-polyline").value=encodeString;}}window.initMap=initMap;
Try Sample
Polygon and Polyline functions
The geometry library'spoly namespace contains utility functions that determine whether a given point is inside or near a polygon or polyline.
containsLocation()
containsLocation(point:LatLng, polygon:Polygon)
To find whether a given point falls within a polygon, pass the point and the polygon togoogle.maps.geometry.poly.containsLocation(). The functions returns true if the point is within the polygon or on its edge.
The following code writes 'true' to the browser console if the user's click falls within the defined triangle; otherwise, it writes 'false'.
functioninitialize(){varmapOptions={zoom:5,center:newgoogle.maps.LatLng(24.886,-70.269),mapTypeId:'terrain'};varmap=newgoogle.maps.Map(document.getElementById('map'),mapOptions);varbermudaTriangle=newgoogle.maps.Polygon({paths:[newgoogle.maps.LatLng(25.774,-80.190),newgoogle.maps.LatLng(18.466,-66.118),newgoogle.maps.LatLng(32.321,-64.757)]});google.maps.event.addListener(map,'click',function(event){console.log(google.maps.geometry.poly.containsLocation(event.latLng,bermudaTriangle));});}google.maps.event.addDomListener(window,'load',initialize);
Another version of this code draws a blue triangle on the map if the click fallswithin the Bermuda Triangle, and a red circle otherwise:
isLocationOnEdge()
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees togoogle.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
functioninitialize(){varmyPosition=newgoogle.maps.LatLng(46.0,-125.9);varmapOptions={zoom:5,center:myPosition,mapTypeId:'terrain'};varmap=newgoogle.maps.Map(document.getElementById('map'),mapOptions);varcascadiaFault=newgoogle.maps.Polyline({path:[newgoogle.maps.LatLng(49.95,-128.1),newgoogle.maps.LatLng(46.26,-126.3),newgoogle.maps.LatLng(40.3,-125.4)]});cascadiaFault.setMap(map);if(google.maps.geometry.poly.isLocationOnEdge(myPosition,cascadiaFault,10e-1)){alert("Relocate!");}}google.maps.event.addDomListener(window,'load',initialize);
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-21 UTC.