'Easiest way to calculate area of drawn polygon with google map
Javascript/google maps beginner here. I am looking for a simple way to calculate the area of a polygon the user draws on the map. Code Snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53,
lng: 0
},
zoom: 13
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon']
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
}
<div>
<div id="map" style="width: 100%; height: 500px;"></div>
</div>
Solution 1:[1]
Use the google.maps.geometry.spherical.computeArea
method
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area="+area.toFixed(2)+" sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
});
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53.000581,
lng: -0.005
},
zoom: 19
});
var infowindow = new google.maps.InfoWindow();
var polygon = new google.maps.Polygon({
path: [{lat: 53.000842,lng: -0.004903},
{lat: 53.000823,lng: -0.004798},
{lat: 53.000779,lng: -0.004823},
{lat: 53.000799,lng: -0.004935}],
map: map
});
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon']
},
drawingMode: null
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
});
drawingManager.setMap(map);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |