Google Maps with Polygon and Marker

Google Maps API allows drawing polygons on maps. This demo shows how to build a map with a polygon and a marker altogether.

In the HTML page, add a div holding the map.

<div id="map-canvas"></div>

In JavaScript, first provide the marker location and an array with the coordinates for the polygon. Then in the initialization code, create a map with a marker and a polygon, while the boundary of the map automatically fits with the polygon.

var MarkerData = [49.272238, -123.122482, "Elsie Roy Elementary"];
var PathData = [
[49.2761419673641, -123.118069007778], 
[49.2791259862655, -123.129144031353],
[49.2704849721733, -123.125236002048],
[49.2732990317854, -123.117229946411],
[49.2761419673641, -123.118069007778]

function initialize() {
	var map = 
	    new google.maps.Map(document.getElementById('map-canvas'));
	var infowindow = new google.maps.InfoWindow();
	var center = 
	    new google.maps.LatLng(MarkerData[0], MarkerData[1]);
	var marker = new google.maps.Marker({
		position: center,
		map: map,
		title: MarkerData[2]

	google.maps.event.addListener(marker, 'click', function() {
		infowindow.setContent(this.title);, this);

	var path = [];
	var bounds = new google.maps.LatLngBounds();
	for (var i in PathData)
		var p = PathData[i];
		var latlng = new google.maps.LatLng(p[0], p[1]);
	var poly = new google.maps.Polygon({
		paths: path,
		strokeColor: '#FF0000',
		strokeOpacity: 0.8,
		strokeWeight: 3,
		fillColor: '#FF0000',
		fillOpacity: 0.1

google.maps.event.addDomListener(window, 'load', initialize);

The following is the result.

View this demo in full screen.

Related Posts



Tagged with:
Posted in Web