Skip to content

Instantly share code, notes, and snippets.

@Dygear
Last active March 6, 2024 21:35
Show Gist options
  • Save Dygear/40e6e4770ece73955a267905e1ad8539 to your computer and use it in GitHub Desktop.
Save Dygear/40e6e4770ece73955a267905e1ad8539 to your computer and use it in GitHub Desktop.
Google Maps JavaScript API getBounds on Polygon.
<!DOCTYPE html>
<main class="container">
<div class="row" id="map" style="height: 600px"></div>
</main>
<script src="https://maps.googleapis.com/maps/api/js?key=<!--YOURKEYHERE-->&libraries=drawing"></script>
<script>
var map, drawingManager;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.9, lng: -73}, zoom: 10
});
drawingManager = new google.maps.drawing.DrawingManager({
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'rectangle']
},
polygonOptions: {
editable: true,
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', (polygon) => {
let bounds = new google.maps.LatLngBounds();
map.data.forEach((polygon) => {
polygon.getGeometry().forEachLatLng((latlng) => {
bounds.extend(latlng);
});
});
let marker = new google.maps.Marker({
position: bounds.getCenter(),
map: map,
title: mapGrid.value
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<!DOCTYPE html>
<main class="container">
<div class="row" id="map" style="height: 600px"></div>
</main>
<script src="https://maps.googleapis.com/maps/api/js?key=<!--YOURKEYHERE-->&libraries=drawing"></script>
<script>
var map, drawingManager;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.9, lng: -73}, zoom: 10
});
drawingManager = new google.maps.drawing.DrawingManager({
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'rectangle']
},
polygonOptions: {
editable: true,
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', (polygon) => {
let bounds = new google.maps.LatLngBounds();
polygon.getPath().forEach((latLng) => {
bounds.extend(latLng);
});
let marker = new google.maps.Marker({
map: map,
title: mapGrid.value,
position: bounds.getCenter()
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
@Dygear
Copy link
Author

Dygear commented Nov 26, 2019

Draw a polygon with the DrawingManger. Once you complete the shape, it will fire the polygon complete method. It should then add a marker to the center of the polygon. But it does not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment