Google Map API InfoWindow click event not returning latlng - google-maps-api-3

I created a polygon on google map and would like a infoWindow to pop up when I click on the polygon. Code as the follows:
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
In the showVolume function,
function showVolume(event){
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latlng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(pt);
}
The function returned the correct information belonging to the polygon. However it returned the event.latlng as undefined. I wonder what is wrong.

event.latlng doesn't exist, javascript is case sensitive, the property is event.latLng
proof of concept fiddle
code snippet:
var geocoder;
var map;
var polygon_infoWindow;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polygon = new google.maps.Polygon({
map: map,
Name: "Fred",
Volume: 1000,
path: [{
lat: 37.4419,
lng: -122.1419
}, {
lat: 37.42,
lng: -122.16
}, {
lat: 37.4419,
lng: -122.1819
}]
});
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
}
google.maps.event.addDomListener(window, "load", initialize);
function showVolume(event) {
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latLng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.setPosition(pt);
polygon_infoWindow.open(map);
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Related

How to disable map zooming after rendering driving directions?

Like title says - I want to avoid map zooming after rendering directions.
I found here a lot of about it, for example Do not change map center or zoom level when rendering directions, but after adding {preserveViewport: true} to DirectionsRenderer nothing happens.
I don't want to calculate the union of the bounds of the directions responses, but only 'freeze' while rendering directions. What am I doing wrong?
My map: https://jsfiddle.net/harlowpl/xawy71r0/33/
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
}
});
You have the zoom level set to a non-integer value. It is changing to an integer value when the directions result is displayed.
Hidden away in the documentation, it says: Specify zoom level as an integer.
proof of concept fiddle (setting zoom to 16, rather than 15.5)
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map"></div>
<script>
var sourceLocation = {
lat: 52.340822,
lng: 16.855841
};
var destinationLocations = [{
lat: 52.344583,
lng: 16.849864
},
{
lat: 52.343319,
lng: 16.855080
},
];
var directionsService;
var directionsDisplay;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.343580,
lng: 16.857495
},
zoom: 16,
styles: [{
"featureType": "poi",
"elementType": "all",
"stylers": [{
"visibility": "off"
}]
}],
gestureHandling: 'cooperative'
});
// console.log("zoom=" + map.getZoom());
// console.log("zoom=" + map.getZoom()+" bounds="+map.getBounds().toUrlValue());
google.maps.event.addListener(map, 'zoom_changed', function() {
console.log("zoom=" + map.getZoom());
});
google.maps.event.addListener(map, 'bounds_changed', function() {
console.log("zoom=" + map.getZoom() + " bounds=" + map.getBounds().toUrlValue());
});
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
function createSourceMarker() {
new google.maps.Marker({
position: sourceLocation,
map: map,
icon: 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/marker-main.svg'
});
}
var opis = [
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<center><h4 id="firstHeading" class="firstHeading">Apteka</h4></center>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 750m' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h4 id="firstHeading" class="firstHeading">Przedszkole</h4>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 450m' + '<br>' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
];
var opisIndex = 0;
var iconBase = 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/';
var markers = [
iconBase + 'marker-01.svg',
iconBase + 'marker-02.svg'
];
var markersIndex = 0;
function createDestinationMarkers() {
destinationLocations.forEach(function(location, index) {
var opisIndex = markersIndex;
var marker = new google.maps.Marker({
position: location,
map: map,
icon: markers[markersIndex++ % markers.length],
});
marker.addListener('click', function() {
infoWindow.setContent(opis[opisIndex % opis.length]);
infoWindow.open(map, marker);
});
marker.addListener('click', function() {
markerClicked(location);
});
})
}
// google.maps.event.addDomListener(window, "load", initMap);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo5rkrpNDFQnr5Afq9fKGmGjOTPC0C390&callback=initMap" async defer></script>

Remove Bounds icon on google maps marker

currently I created pages with google maps api v3, and there is a marker that user can drag. after dragend, the script with draw blue line on the road between marker. my problem is shown 2 marker on destination (a marker and "B" marker)
I've try using fitbounds() but still facing my problem.
<div id="current"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=xxx"></script>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-7.760722, 110.408761),
map: map,
draggable:true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
}
else
{
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
how to remove bound marker ("B" marker) on destination? I expect there is only one marker in destination
You need to remove all the markers (with the {suppressMarkers:true} option on the DirectionsRenderer (they can't be suppressed separately)
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
To make the "A" Marker appear, create it:
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
proof of concept fiddle
code snippet:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-7.760722, 110.408761),
map: map,
draggable: true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
// add "A" marker
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
} else {
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
<div id="current"></div>
<div id="map_canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Center map on window with random number

I am new to this forum (this is my first post) and a beginner in using google map with javascript. I hope I apologize if the question is silly.
I have an arrangement with several cities and want to focus the map according to the result of a random number. I'm using the attached code, but does not work me. Can anyone see what I am doing wrong? Thank you.
<script>
var myrand=0
function initialize() {
var i;
var Locations = [
{
lat: 40.7127837,
lon: -74.00594130000002,
title: "New york",
description: "I'm number 1"
},
{
lat: 23.634501,
lon: -102.55278399999997,
title: "Mexico",
description: "I'm number 2"
},
{
lat: 36.778261,
lon: -119.41793239999998,
title: "California",
description: "I'm number 3"
}
];
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(30.011902,-98.48424649999998),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// loop over our array
for (i = 0; i < Locations.length; i++) {
// create a marker
var marker = new google.maps.Marker({
title: Locations[i].title,
position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),
map: map
});
// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].description + "</p>");
//bindInfoWindow(marker, map, infowindow, Locations[i].description);
}
}
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
//alert("seleccionado el "+html);
});
}
function aleatorio(min,max)
{
myrand = Math.floor(Math.random()*(max-min+1)+min);
alert('salió '+ myrand);
map.setCenter({lat: Locations[myrand].lat, lng: Locations[myrand].lon});
return Math.floor(Math.random()*(max-min+1)+min);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You have typos in your code:
the random number function in javascript is Math.random, not Math.myrandom.
the function aleatorio depends on the array Locations being in scope. Currently that array is local to the initialize function. You either need to move aleatorio inside the initialize function or move the Locations array into the global namespace.
proof of concept fiddle
code snippet:
var myrand = 0
function initialize() {
var i;
var Locations = [{
lat: 40.7127837,
lon: -74.00594130000002,
title: "New york",
description: "I'm number 1"
}, {
lat: 23.634501,
lon: -102.55278399999997,
title: "Mexico",
description: "I'm number 2"
}, {
lat: 36.778261,
lon: -119.41793239999998,
title: "California",
description: "I'm number 3"
}];
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(30.011902, -98.48424649999998),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// loop over our array
for (i = 0; i < Locations.length; i++) {
// create a marker
var marker = new google.maps.Marker({
title: Locations[i].title,
position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),
map: map
});
// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].description + "</p>");
}
aleatorio(0, 2);
function aleatorio(min, max) {
myrand = Math.floor(Math.random() * (max - min + 1) + min);
map.setCenter({
lat: Locations[myrand].lat,
lng: Locations[myrand].lon
});
return Math.floor(Math.random() * (max - min + 1) + min);
}
}
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
//alert("seleccionado el "+html);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

More Efficient Way to Add Markers to Google Maps v3

I am building this JS programmatically. Each marker is being represented by separate variables like marker_0,marker_1, etc... This works but is there a way to generate the markers & info windows in a more efficient/elegant way?
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//**************************************************************
//Add 1st marker
//**************************************************************
var contentString_0 ='<strong>Club name: Fort Wayne Time Corners</strong>';
var infowindow_0 = new google.maps.InfoWindow({
content: contentString_0
});
var image_0 = '/js/markers/marker1.png';
var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
var marker_0 = new google.maps.Marker({
position: Latlng_0,
title:"0",
icon: image_0});
marker_0.setMap(map);
google.maps.event.addListener(marker_0, 'click', function() {
infowindow_0.open(map,marker_0);
});
//**************************************************************
//Add 2nd marker
//**************************************************************
var contentString_1='<strong>Club name: Roanoke</strong>';
var infowindow_1 = new google.maps.InfoWindow({
content: contentString_1
});
var image_1 = '/js/markers/marker2.png';
var Latlng_1 = new google.maps.LatLng(41.17805990,-85.4436640);
var marker_1 = new google.maps.Marker({
position: Latlng_1,
title:"1",
icon: image_1});
marker_1.setMap(map);
google.maps.event.addListener(marker_1, 'click', function() {
infowindow_1.open(map,marker_1);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
Yes, you can do this easily:
Create an array of data that describes each marker.
Write a function that adds a single marker based on the description in one entry of that array.
Call that function for each entry in that array.
So the only part you have to generate dynamically is that array of data; all of the actual marker code is shared for all markers.
Like this:
var map;
var places = [
{
lat: 41.057814980291,
lng: -85.329851919709,
image: 'marker1',
title: '0',
club: 'Fort Wayne Time Corners'
},
{
lat: 41.17805990,
lng: -85.4436640,
image: 'marker2',
title: '1',
club: 'Roanoke'
}
];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"),
mapOptions
);
for( var i = 0; i < places.length; i++ ) {
addPlace( places[i] );
}
function addPlace( place ) {
var content = '<strong>Club name: ' + place.club + '</strong>';
var infowindow = new google.maps.InfoWindow({
content: content
});
var image = '/js/markers/' + place.image + '.png';
var latlng = new google.maps.LatLng( place.lat, place.lng );
var marker = new google.maps.Marker({
position: latlng,
title: place.title,
icon: image
});
marker.setMap( map );
google.maps.event.addListener( marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;

Open InfoWindow for each polygon google maps V3

Hope someone can help me with this issue.
I'm trying to open an info windows on click for each polygon that my users created.
I used the same code for a marker and works well but i couldn't make it work for each polygon.
Any thoughts on how to solve this problem?
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2>Test</h2>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Show Areas
<?php foreach ($field->result() as $f):?>
// Create an array with the coordanates of each area
var field<?=$f->id?>Coords = [
<?php $latlng=$this->resources_data->field_latlng($f->id);?>
<?php foreach ($latlng->result() as $point):?>
new google.maps.LatLng(<?=$point->lat?>, <?=$point->lng?>),
<?php endforeach;?>
];
// Create a polygon with the points of the area
var area<?=$f->id?>=new google.maps.Polygon({
paths: area<?=$f->id?>Coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
// Add the area to the map.
area<?=$f->id?>.setMap(map);
google.maps.event.addListener(area<?=$f->id?>,'click',function(){
infowindow.open(map,area<?=$f->id?>)
});
<?php endforeach;?>
You can't use the same form of InfoWindow.open for a polygon as you use for a marker (there is no marker to pass in).
From the documentation
open(map?:Map|StreetViewPanorama, anchor?:MVCObject)
Return Value: None
Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the core API, the only anchor is the Marker class. However, an anchor can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow.)
You need to specifically set the place you want it to open when you call the open method (the latlng of the click is usually a good choice) with InfoWindow.setPosition().
Example
code snippet:
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var geolib = google.maps.geometry.spherical;
var myOptions = {
zoom: 20,
center: new google.maps.LatLng(32.738158, -117.14874),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
bounds = new google.maps.LatLngBounds();
var polygon1 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 0),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 120),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, -120)
],
name: "polygon1"
});
google.maps.event.addListener(polygon1, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon1.getPath().getLength(); i++) {
bounds.extend(polygon1.getPath().getAt(i));
}
var polygon2 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 180),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 60),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, -60)
],
name: "polygon2"
});
google.maps.event.addListener(polygon2, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon2.getPath().getLength(); i++) {
bounds.extend(polygon2.getPath().getAt(i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
function createClickablePoly(poly, html, label, point) {
gpolys.push(poly);
if (!point && poly.getPath && poly.getPath().getLength && (poly.getPath().getLength > 0) && poly.getPath().getAt(0)) {
point = poly.getPath().getAt(0);
}
var poly_num = gpolys.length - 1;
if (!html) {
html = "";
} else {
html += "<br>";
}
var length = poly.Distance();
if (length > 1000) {
html += "length=" + poly.Distance().toFixed(3) / 1000 + " km";
} else {
html += "length=" + poly.Distance().toFixed(3) + " meters";
}
for (var i = 0; i < poly.getPath().getLength(); i++) {
html += "<br>poly[" + poly_num + "][" + i + "]=" + poly.getPath().getAt(i);
}
html += "<br>Area: " + poly.Area() + " sq meters";
// html += poly.getLength().toFixed(2)+" m; "+(poly.getLength()*3.2808399).toFixed(2)+" ft; ";
// html += (poly.getLength()*0.000621371192).toFixed(2)+" miles";
var contentString = html;
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(contentString);
if (event) {
point = event.latLng;
}
infowindow.setPosition(point);
infowindow.open(map);
// map.openInfoWindowHtml(point,html);
});
if (!label) {
label = "polyline #" + poly_num;
}
label = "<a href='javascript:google.maps.event.trigger(gpolys[" + poly_num + "],\"click\");'>" + label + "</a>";
// add a line to the sidebar html
// side_bar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />';
}
body,
html {
height: 100%;
width: 100%;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height:100%; width:100%">
<tr>
<td>
<div id="map_canvas" style="width:100%; height:100%"></div>
</td>
<td width="200">
<div id="report"></div>
</td>
</tr>
</table>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 45.15492713361847, lng: 15.40557861328125}
});
var polygons = [{name: 'first name', coordinates:[{lat:45.15492713361847,lng:15.40557861328125},{lat:45.07933920973809,lng:15.5291748046875},{lat:45.01918507438175,lng:15.43304443359375},{lat:45.07933920973809,lng:15.3204345703125}]}];
// foreach your polygons
for (var i = 0; i < polygons.length; i++) {
var item = polygons[i];
var coors = item["coordinates"];
var name = item["name"];
var Polygon = new google.maps.Polygon({
path: coors,
strokeColor: '#66b3ff',
strokeOpacity: 0.8,
strokeWeight: 5,
editable: false,
fillColor: 'blue',
fillOpacity: 0.5,
});
Polygon.setMap(map);
// call function to set window
attachPolygonInfoWindow(Polygon, coors, name);
}
}
function attachPolygonInfoWindow(polygon, coors, html)
{
polygon.infoWindow = new google.maps.InfoWindow({
content: html
});
polygon.infoWindow.setPosition(getHighestWindowPosition(coors));
google.maps.event.addListener(polygon, 'mouseover', function () {
polygon.infoWindow.open(map, polygon);
});
google.maps.event.addListener(polygon, 'mouseout', function () {
polygon.infoWindow.close();
});
}
// function to get highest position of polygon to show window nice on top
function getHighestWindowPosition(coors) {
var lat = -5000, lng = 0, i = 0, n = coors.length;
for (; i !== n; ++i) {
if (coors[i].lat > lat) {
lat = coors[i].lat;
lng = coors[i].lng;
}
}
return {lat: lat, lng: lng};
}
</script>

Resources