var map;
var rectangles = [];
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 10,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Set markers and rectangles once the map is idle
google.maps.event.addListenerOnce(map, 'idle', function() {
// Get map bounds, north-east and south-west coords
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
// Create a few markers to test
setMarker(new google.maps.LatLng(-0.05, -0.05));
setMarker(new google.maps.LatLng(0.05, -0.05));
setMarker(new google.maps.LatLng(0.05, 0.05));
setMarker(new google.maps.LatLng(-0.05, 0.05));
// Define 4 rectangles based on map bounds and center
setRectangle(new google.maps.LatLngBounds(
new google.maps.LatLng(center.lat(), sw.lng()),
new google.maps.LatLng(ne.lat(), center.lng()),
), 'blue');
setRectangle(new google.maps.LatLngBounds(
new google.maps.LatLng(center.lat(), center.lng()),
new google.maps.LatLng(ne.lat(), ne.lng()),
), 'yellow');
setRectangle(new google.maps.LatLngBounds(
new google.maps.LatLng(sw.lat(), sw.lng()),
new google.maps.LatLng(center.lat(), center.lng()),
), 'green');
setRectangle(new google.maps.LatLngBounds(
new google.maps.LatLng(sw.lat(), center.lng()),
new google.maps.LatLng(center.lat(), ne.lng()),
), 'red');
});
}
function setMarker(latLng, title) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: title,
draggable: true
});
new google.maps.event.addListener(marker, 'click', function() {
checkRectangleContains(this.position);
});
}
function setRectangle(bounds, color) {
var rectangle = new google.maps.Rectangle({
strokeWeight: 0,
fillColor: color,
fillOpacity: 0.35,
map: map,
bounds: bounds,
_reference: color
});
rectangles.push(rectangle);
}
function checkRectangleContains(markerCoords) {
for (var i = 0; i < rectangles.length; i++) {
// Check if the rectangle bounds contain the marker position
if (rectangles[i].getBounds().contains(markerCoords)) {
// Output message
document.getElementById('rectangle-contains').innerHTML = 'This point is contained within ' + rectangles[i]._reference + ' rectangle.';
}
}
}
#map-canvas {
height: 180px;
}
<div id="map-canvas"></div>
<div id="rectangle-contains"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>