Line Length and Polygon Area With Google Maps API V3
This is just a demo page showing how to use the geometry library for the Google Maps API. For more information, check out the blog post with details.
Click the map below to start drawing lines and polygons and to start measuring. Distance and area measurements are below the map as well as a link to reset the measurements.
Length (red line): 0 mt - Area (grey area): 0 mt² - Reset Measure
How it works
The relevant bits of code are below.
First and foremost, be sure that you’re requesting the geometry library from the Google Maps API by adding the &libraries=geometry URL parameter in your script tag. This library is not included with the default script download.
http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&libraries=geometry
We’ll create a global variable for our map and a measure object to keep things in order.
1 2 3 4 5 6 7 8 9 10 | |
Now, we’ll create the map and listen for map clicks, sending these coordinates to a measureAdd function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
The measureAdd function does most of the heavy lifing here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
The measureCalc function is doing the actual length and area measurements with the help of the Google Maps geometry library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Lastly, we’ll want to wire up a link or button to clear the measurement objects and reset the values to 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |