Google Maps crashes after a while after a few clicks - javascript

I am having a problem where the google maps will start to slow down and crash after playing around with the draw area function (bottom of page). Wanted to know if I have missed something or I have something in there which is causing it to crash?
var map;
var weatherDisplayIsOn = false;
var markers = [];
var cArea;
function initialize() {
var myLatlng = new google.maps.LatLng(51.488651, -0.063232);
var newYork = new google.maps.LatLng(40.719967, -74.009893);
var paris = new google.maps.LatLng(48.857278, 2.352210);
var london = new google.maps.LatLng(51.519670, -0.125631);
var towerBridge = new google.maps.LatLng(51.506231, -0.075356);
var mapOptions = {
center: myLatlng,
zoom: 8,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var Home = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Home</h1>' +
'<div id="bodyContent">' +
'<p><b>Home</b>, the buidling I had spent the last 13 years living ' +
'in with the locality of Primary Schools, Secondary and Localised ' +
'public transport ' +
'</p>' +
'</div>' +
'</div>';
var infoHome = new google.maps.InfoWindow({
content: Home
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP,
title: 'Homeland'
});
google.maps.event.addListener(marker, 'click', function() {
infoHome.open(map, marker);
});
var NewYork = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">New York</h1>' +
'<div id="bodyContent">' +
'<p><b>New York</b>, often called New York City or the City of New York to distinguish ' +
'it from the State of New York, of which it is a part of the most populous city ' +
'in the United States and the center of the New York metropolitan area, the premier gateway for' +
'legal immigration to the United States and one of the most populous urban agglomerations in the world.' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/MtCMtC50gwY?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</p>' +
'</div>' +
'</div>';
var nyInfo = new google.maps.InfoWindow({
content: NewYork
});
var marker1 = new google.maps.Marker({
position: newYork,
map: map,
animation: google.maps.Animation.DROP,
title: 'New York'
});
google.maps.event.addListener(marker1, 'click', function() {
nyInfo.open(map, marker1);
});
var Paris = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Paris, France</h1>' +
'<div id="bodyContent">' +
'<p><b>Paris</b>, is the capital and most populous city of France. ' +
'Situated on the Seine River, in the north of the country, it is in the centre of the ' +
'Ile-de-France region, also known as the region parisienne.' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/hWo-43ObCP8" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var parisInfo = new google.maps.InfoWindow({
content: Paris
});
var marker2 = new google.maps.Marker({
position: paris,
map: map,
animation: google.maps.Animation.DROP,
title: 'Paris'
});
google.maps.event.addListener(marker2, 'click', function() {
parisInfo.open(map, marker2);
});
var London = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">London, United Kingdom</h1>' +
'<div id="bodyContent">' +
'<p><b>London</b>, is the capital city of England and the United Kingdom.' +
'It is the most populous city in the United Kingdom, with a metropolitan area of over ' +
'13 million inhabitants. ' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/45ETZ1xvHS0?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var londonInfo = new google.maps.InfoWindow({
content: London
});
var marker3 = new google.maps.Marker({
position: london,
map: map,
animation: google.maps.Animation.DROP,
title: 'London'
});
google.maps.event.addListener(marker3, 'click', function() {
londonInfo.open(map, marker3);
});
var TowerBridge = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Tower Bridge,London</h1>' +
'<div id="bodyContent">' +
'<p><b>Tower Bridge</b>, is the capital city of England and the United Kingdom.' +
'It is the most populous city in the United Kingdom, with a metropolitan area of over ' +
'13 million inhabitants. ' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/45ETZ1xvHS0?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var towerBridgeInfo = new google.maps.InfoWindow({
content: TowerBridge
});
var marker4 = new google.maps.Marker({
position: towerBridge,
map: map,
animation: google.maps.Animation.DROP,
title: 'Tower Bridge'
});
google.maps.event.addListener(marker4, 'click', function() {
towerBridgeInfo.open(map, marker4)
});
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
google.maps.event.addDomListener(document.getElementById('weather'), 'click', toggleWeather);
};
google.maps.event.addDomListener(window, 'load', initialize);
function setRoad() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
}
function setHYB() {
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
}
function zoomTo() {
var lat = prompt("Enter your latitude");
var lng = prompt("Enter your longtitude");
map.panTo(new google.maps.LatLng(lat, lng));
}
function zoomIn() {
var currentZoomLevel = map.getZoom();
if (currentZoomLevel != 21) {
map.setZoom(currentZoomLevel + 1);
}
}
function zoomOut() {
var currentZoomLevel = map.getZoom();
if (currentZoomLevel != 21) {
map.setZoom(currentZoomLevel - 1);
}
}
function toggleWeather() {
if (weatherDisplayIsOn) {
weatherLayer.setMap(null);
weatherDisplayIsOn = false;
}
else {
weatherLayer.setMap(map);
weatherDisplayIsOn = true;
}
}
function addMarker(myLatlng) {
var customMarker = new google.maps.Marker({
position: myLatlng,
map: map
});
markers.push(customMarker);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function clearMarkers() {
setAllMap(null);
}
function showMarkers() {
setAllMap(map);
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function drawArea()
{
var points = new google.maps.MVCArray();
var endPoint = new google.maps.LatLngBounds();
cArea = new google.maps.Polygon({
path: points,
strokeOpacity: 0.7,
strokeWeight: 2,
fillOpacity: 0.2,
fillColor: "#FF0000"
});
cArea.setMap(map);
google.maps.event.addListener(map, 'click', function(e)
{
var path = cArea.getPath();
path.push(e.latLng);
endPoint.extend(e.latLng);
addMarker(e.latLng);
});
}
function deleteArea(){
cArea.setMap(null);
}

You have this function:
function addMarker(myLatlng) {
var customMarker = new google.maps.Marker({
position: myLatlng,
map: map
});
markers.push(customMarker);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
In which you define an event listener for map clicks, which calls... the addMarker function... which defines an event listener for map clicks, which calls... the addMarker function... which defines an event listener for map clicks,... etc etc ad infinitum.
In other words, the error is probably too much recursion.
And to cap it all, you also define the same event listener elsewhere too:
google.maps.event.addListener(map, 'click', function(e)
{
var path = cArea.getPath();
path.push(e.latLng);
endPoint.extend(e.latLng);
addMarker(e.latLng);
});
Although this seems to be in a function ('drawArea') that isn't called from anywhere.
Just move this outside of the addMarker function, to wherever you create the map:
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});

Related

By clicking a button, that's on a infowindow of a specific marker, I want the marker to change color depending on which button I click [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a view of the ASP.NET, using mvc. I using google maps with different markers. Each of those markers have their own infowindows that have 3 buttons each. By clicking a specific button I want the marker to change color. How can I do that?
I have already tried using document.getElementById and using the addEventListner. I also tried to program the button by using the onclick function.
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019",38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019",38.487978, -9.004425, 90,"foto.jpg"],
["Concluído", "01/07/2019",37.045804, -8.898041, 12, "foto.jpg"]
];
var infowindow = new google.maps.InfoWindow({});
function setMarkers(map) {
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker ;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({ content: contentString });
marker = new google.maps.Marker({
position: { lat: fire[2], lng: fire[3] },
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
}
The buttons are represented in the variable contentString, and when I click the button with the id "Aceite", I want to change the color of the marker to green.
Attempt to change the marker to green:
<button id="aceite" onclick="state(marker)">Aceite</button>
function state(marker){
marker.setIcon('google.com/mapfiles/marker_green.png');
}
Simplest would be to add the click listener function when you open the InfoWindow (when you know what marker it is associated with).
Add the click listener to the button when the domready event of the InfoWindow fires (and it has been added to the DOM):
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
Use function closure on the marker in the marker click listener (this references the marker in the click event listener function, but not in the InfoWindow domready event listener, save it so you can use it there):
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
proof of concept fiddle
code snippet:
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var infowindow = new google.maps.InfoWindow({});
setMarkers(map);
}
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019", 38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019", 38.487978, -9.004425, 90, "foto.jpg"],
["Concluído", "01/07/2019", 37.045804, -8.898041, 12, "foto.jpg"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker = new google.maps.Marker({
position: {
lat: fire[2],
lng: fire[3]
},
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Google Maps API Polygon Infowindow Appears on Last Clicked Marker

I have a set of markers and polygons displayed on my map, each marker and polygon is stored in a separate array. Currently, I have infowindows tied to my markers and I wanted to add infowindows to my polygons in case the user clicks on them. The marker infowindows work perfectly.
The problem is that when you click on the polygon the infowindow won't pop up unless you've clicked on a marker first. Then, the polygon infowindow will appear on the last clicked marker.
I've worked through every line of relevant code. I think the problem exists in that the infowindow is tied specifically to the marker icons, but I don't know how to detach it. I'm relatively new to JS and this is my first major on-going project.
var map;
var mapCenter = { lat: 28.201890, lng: -81.027334 };
var mPoint = "/images/placemark_circle_highlight.png";
var locations = [];
var locationsPoly = [];
var markers = [];
var infos = [];
var polygons = [];
var polyInfos = [];
var infowindow;
var testInfoWindow1 =
'<div id="content">' +
'<h1 class="header">Test Marker #1</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 1.</p>" +
"</div>" +
"</div>";
var testInfoWindow2 =
'<div id="content">' +
'<h1 class="header">Test Marker #2</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 2.</p>" +
"</div>" +
"</div>";
var testInfoWindow3 =
'<div id="content">' +
'<h1 class="header">Test Marker #3</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 3.</p>" +
"</div>" +
"</div>";
var testInfoWindow4 =
'<div id="content">' +
'<h1 class="header">Test Marker #4</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 4.</p>" +
"</div>" +
"</div>";
var testInfoWindow5 =
'<div id="content">' +
'<h1 class="header">Test Marker #5</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 5.</p>" +
"</div>" +
"</div>";
var pOneDesc =
'<div id="content">' +
'<h1 class="header">#1 Polygon Window</h1>' +
'<div class="desc">' +
"<p>Lorem.</p>" +
"</div>" +
"</div>";
var pTwoDesc =
'<div id="content">' +
'<h1 class="header">#2 Polygon Window</h1>' +
'<div class="desc">' +
"<p>elementum pulvinar etiam.</p>" +
"</div>" +
"</div>";
var pThreeDesc =
'<div id="content">' +
'<h1 class="header">#3 Polygon Window</h1>' +
'<div class="desc">' +
"<p>orci eu lobortis elementum nibh tellus molestie.</p>" +
"</div>" +
"</div>";
function initMap() {
var myOptions = {
zoom: 15,
center: mapCenter,
mapTypeControl: true,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
map = new google.maps.Map(document.getElementById("map"),
myOptions);
locations = [
["Test Marker #1", 28.210862, -81.038192, testInfoWindow1, mPoint, 'category1'],
["Test Marker #2", 28.206477, -81.016176, testInfoWindow2, mPoint, 'category1'],
["Test Marker #3", 28.216659, -81.029092, testInfoWindow3, mPoint, 'category1'],
["Test Marker #4", 28.195328, -81.044638, testInfoWindow4, mPoint, 'category1'],
["Test Marker #5", 28.196439, -81.006932, testInfoWindow5, mPoint, 'category1']
];
var polygonOne = [
[28.187985, -81.045365],
[28.183579, -81.045365],
[28.183579, -81.041156],
[28.187922, -81.041341]
];
var pointsPolyOne = [];
for (var i = 0; i < polygonOne.length; i++) {
pointsPolyOne.push({
lat: polygonOne[i][0],
lng: polygonOne[i][1]
});
}
var polygonTwo = [
[28.185258, -81.033373],
[28.183601, -81.030751],
[28.187809, -81.026072]
];
var pointsPolyTwo = [];
for (var i = 0; i < polygonTwo.length; i++) {
pointsPolyTwo.push({
lat: polygonTwo[i][0],
lng: polygonTwo[i][1]
});
}
var polygonThree = [
[28.189691, -81.032381],
[28.188111, -81.032337],
[28.188291, -81.031608],
[28.189719, -81.031276]
];
var pointsPolyThree = [];
for (var i = 0; i < polygonThree.length; i++) {
pointsPolyThree.push({
lat: polygonThree[i][0],
lng: polygonThree[i][1]
});
}
locationsPoly = [
[pointsPolyThree, pOneDesc, "#f44336", 0.8, 2, "#ffffff", 0.35, 'FY19'],
[pointsPolyTwo, pTwoDesc, "#4caf50", 0.8, 2, "#bdeabf", 0.35, 'FY19'],
[pointsPolyOne, pThreeDesc, "#849199", 0.8, 2, "#ffffff", 0.35, 'FY19']
];
infowindow = new google.maps.InfoWindow();
setMarkers(map, locations);
setPolygons(map, locationsPoly);
}
function setMarkers(map, locations) {
var marker, i
for (i = 0; i < locations.length; i++) {
var title = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var desc = locations[i][3];
var pin = locations[i][4];
var category = locations[i][5];
latlngset = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
map: map,
title: title,
position: latlngset,
icon: pin,
category: category
});
marker.mycategory = category;
marker.myname = name;
markers.push(marker);
var content = desc;
google.maps.event.addListener(marker, 'click', (function (marker, content) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(content);
infowindow.setPosition(event.latlng);
infowindow.open(map, marker);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(marker, content));
google.maps.event.addListener(map, "click", function (marker, content) {
closeInfos();
});
}
}
function setPolygons(map, locationsPoly) {
var polygon, i
for (i = 0; i < locationsPoly.length; i++) {
var paths = locationsPoly[i][0];
var polyDesc = locationsPoly[i][1];
var strokeColor = locationsPoly[i][2];
var strokeOpacity = locationsPoly[i][3];
var strokeWeight = locationsPoly[i][4];
var fillColor = locationsPoly[i][5];
var fillOpacity = locationsPoly[i][6];
var categoryPoly = locationsPoly[i][7];
polygon = new google.maps.Polygon({
map: map,
paths: paths,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
category: categoryPoly
});
polygon.mycategory = categoryPoly;
polygon.myname = name;
polygons.push(polygon);
var polyContent = polyDesc;
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map, polygon);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent));
google.maps.event.addListener(map, "click", function (marker, content) {
closeInfos();
});
}
}
function getHighestWindowPosition(paths) {
var lat = -5000, lng = 0, i = 0, n = paths.length;
for (; i !== n; ++i) {
if (paths[i].lat > lat) {
lat = paths[i].lat;
lng = paths[i].lng;
}
}
return { lat: lat, lng: lng };
}
function closeInfos() {
if (infos.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
infos[0].set("marker", "polygon", null);
/* and close it */
infos[0].close();
/* blank the array */
infos.length = 0;
}
}
<!DOCTYPE html>
<html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<head>
<title>Test Map for Markers-Polygons</title>
<script type="application/javascript" src="js/checkbox.js?rndstr=<%= getRandomStr() %>"></script>
<style>
#map {
height: 100vh;
}
html,
body {
height: 100vh;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=##APIKEYHERE##&callback=initMap"
async defer></script>
</body>
</html>
UPDATE: Minimum reproducible example.
The infowindow now appears on a polygon, but only the first one in the array.
Two issues remain.
Per my comment, and the related question: Open InfoWindow for each polygon google maps V3, the InfoWindow.open method's second parameter (if it exists) must be an "anchor" (with a position property), which a google.maps.Polygon object is not.
infowindow.open(map, polygon);
should be:
infowindow.open(map);
You are using the paths variable inside the "click" event listener function, but you don't have function closure on it (you only have function closure on polygon and polygonContent).
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map, polygon);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent));
should be:
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent, paths) {
return function (evt) {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent, paths));
proof of concept fiddle
code snippet:
var map;
var mapCenter = {
lat: 28.201890,
lng: -81.027334
};
var mPoint = "/images/placemark_circle_highlight.png";
var locations = [];
var locationsPoly = [];
var markers = [];
var infos = [];
var polygons = [];
var polyInfos = [];
var infowindow;
var testInfoWindow1 =
'<div id="content">' +
'<h1 class="header">Test Marker #1</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 1.</p>" +
"</div>" +
"</div>";
var testInfoWindow2 =
'<div id="content">' +
'<h1 class="header">Test Marker #2</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 2.</p>" +
"</div>" +
"</div>";
var testInfoWindow3 =
'<div id="content">' +
'<h1 class="header">Test Marker #3</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 3.</p>" +
"</div>" +
"</div>";
var testInfoWindow4 =
'<div id="content">' +
'<h1 class="header">Test Marker #4</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 4.</p>" +
"</div>" +
"</div>";
var testInfoWindow5 =
'<div id="content">' +
'<h1 class="header">Test Marker #5</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 5.</p>" +
"</div>" +
"</div>";
var pOneDesc =
'<div id="content">' +
'<h1 class="header">#1 Polygon Window</h1>' +
'<div class="desc">' +
"<p>Lorem.</p>" +
"</div>" +
"</div>";
var pTwoDesc =
'<div id="content">' +
'<h1 class="header">#2 Polygon Window</h1>' +
'<div class="desc">' +
"<p>elementum pulvinar etiam.</p>" +
"</div>" +
"</div>";
var pThreeDesc =
'<div id="content">' +
'<h1 class="header">#3 Polygon Window</h1>' +
'<div class="desc">' +
"<p>orci eu lobortis elementum nibh tellus molestie.</p>" +
"</div>" +
"</div>";
function initMap() {
var myOptions = {
zoom: 13,
center: mapCenter,
mapTypeControl: true,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
map = new google.maps.Map(document.getElementById("map"),
myOptions);
locations = [
["Test Marker #1", 28.210862, -81.038192, testInfoWindow1, mPoint, 'category1'],
["Test Marker #2", 28.206477, -81.016176, testInfoWindow2, mPoint, 'category1'],
["Test Marker #3", 28.216659, -81.029092, testInfoWindow3, mPoint, 'category1'],
["Test Marker #4", 28.195328, -81.044638, testInfoWindow4, mPoint, 'category1'],
["Test Marker #5", 28.196439, -81.006932, testInfoWindow5, mPoint, 'category1']
];
var polygonOne = [
[28.187985, -81.045365],
[28.183579, -81.045365],
[28.183579, -81.041156],
[28.187922, -81.041341]
];
var pointsPolyOne = [];
for (var i = 0; i < polygonOne.length; i++) {
pointsPolyOne.push({
lat: polygonOne[i][0],
lng: polygonOne[i][1]
});
}
var polygonTwo = [
[28.185258, -81.033373],
[28.183601, -81.030751],
[28.187809, -81.026072]
];
var pointsPolyTwo = [];
for (var i = 0; i < polygonTwo.length; i++) {
pointsPolyTwo.push({
lat: polygonTwo[i][0],
lng: polygonTwo[i][1]
});
}
var polygonThree = [
[28.189691, -81.032381],
[28.188111, -81.032337],
[28.188291, -81.031608],
[28.189719, -81.031276]
];
var pointsPolyThree = [];
for (var i = 0; i < polygonThree.length; i++) {
pointsPolyThree.push({
lat: polygonThree[i][0],
lng: polygonThree[i][1]
});
}
locationsPoly = [
[pointsPolyThree, pOneDesc, "#f44336", 0.8, 2, "#ffffff", 0.35, 'FY19'],
[pointsPolyTwo, pTwoDesc, "#4caf50", 0.8, 2, "#bdeabf", 0.35, 'FY19'],
[pointsPolyOne, pThreeDesc, "#849199", 0.8, 2, "#ffffff", 0.35, 'FY19']
];
infowindow = new google.maps.InfoWindow();
setMarkers(map, locations);
setPolygons(map, locationsPoly);
}
function setMarkers(map, locations) {
var marker, i
for (i = 0; i < locations.length; i++) {
var title = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var desc = locations[i][3];
var pin = locations[i][4];
var category = locations[i][5];
latlngset = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
map: map,
title: title,
position: latlngset,
// icon: pin,
category: category
});
marker.mycategory = category;
marker.myname = name;
markers.push(marker);
var content = desc;
google.maps.event.addListener(marker, 'click', (function(marker, content) {
return function() {
/* close the previous info-window */
closeInfos();
infowindow.setContent(content);
infowindow.setPosition(event.latlng);
infowindow.open(map, marker);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(marker, content));
google.maps.event.addListener(map, "click", function(marker, content) {
closeInfos();
});
}
}
function setPolygons(map, locationsPoly) {
var polygon, i
for (i = 0; i < locationsPoly.length; i++) {
var paths = locationsPoly[i][0];
var polyDesc = locationsPoly[i][1];
var strokeColor = locationsPoly[i][2];
var strokeOpacity = locationsPoly[i][3];
var strokeWeight = locationsPoly[i][4];
var fillColor = locationsPoly[i][5];
var fillOpacity = locationsPoly[i][6];
var categoryPoly = locationsPoly[i][7];
polygon = new google.maps.Polygon({
map: map,
paths: paths,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
category: categoryPoly
});
polygon.mycategory = categoryPoly;
polygon.myname = name;
polygons.push(polygon);
var polyContent = polyDesc;
google.maps.event.addListener(polygon, 'click', (function(polygon, polyContent, paths) {
return function(evt) {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent, paths));
google.maps.event.addListener(map, "click", function(marker, content) {
closeInfos();
});
}
}
function getHighestWindowPosition(paths) {
console.log(paths);
var lat = -5000,
lng = 0,
i = 0,
n = paths.length;
for (; i !== n; ++i) {
if (paths[i].lat > lat) {
lat = paths[i].lat;
lng = paths[i].lng;
}
}
console.log("lat=" + lat + " lng=" + lng);
return {
lat: lat,
lng: lng
};
}
function closeInfos() {
if (infos.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
infos[0].set("marker", "polygon", null);
/* and close it */
infos[0].close();
/* blank the array */
infos.length = 0;
}
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Google Maps API. calling multiple info windows from an array

I have searched all over this site to find an answer with no luck. I have an array of lat, and lng markers and I'd like to open an info window based on the array index. I got it to work by replacing markers with variables instead of an array list, but I want to keep my code DRY. Here is my code:
function initMap() {
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
for(var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
icon: 'images/pin-cloud.png',
animation: google.maps.Animation.DROP,
map: map
});
}
var blairCountyContentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Blair County, PA</h1>'+
'<div id="bodyContent">'+
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study Blair County, PA</span> </a></p>'+
'</div>'+
'</div>';
var blairCountyInfowindow = new google.maps.InfoWindow({
content: blairCountyContentString,
position: locations[0]
});
marker.addListener('click', function() {
blairCountyInfowindow.open(map, marker);
});
My issue seems to be with the "position: locations[0]" object literal. Sometimes I get an error stating that this needs to be a number value of lng, lat...Tried it though with no luck. The window currently opens but only for the last index of the array. Any ideas?
See updated Code. Now customize the infowindow content
Fiddle link
function initMap() {
var marker = [];
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
var ContentString =
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + locations[i][0] + '</h1>' +
'<div id="bodyContent">' +
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study ' + locations[i][0] + '</span> </a></p>' +
'</div>' +
'</div>';
return function() {
infowindow.setContent(ContentString);
infowindow.open(map, marker);
}
})(marker, i));
}
}

Showing same marker details after close of markers using infobubbles

Here in this small code snippet,I am facing a little problem.THe problem is if I close all the marker after page completely loaded.And again when I click on markers same detail display on all markers..Here is my code:
var map, infoBubble;
function onload() {
var mapCenter = new google.maps.LatLng(13.0162476, 77.5073893);
map = new google.maps.Map(document.getElementById('dvMap'), {
zoom: 8,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (i = 0; i < markers.length; i++) {
//icons[i];
//alert("undefined icons" + icons[i]);
var data = markers[i]
//var myLatlng = new google.maps.LatLng(13.4162691, 77.5064153);
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Par Id ' + data.ParId,
icon: 'Google Marker/In/' + data.title + '.png'
});
if (data.RANK == "1") {
data.RANK = "Primary";
} else {
data.RANK = "Secondary";
}
// alert(data.IMAGEPATH);
var contentString = '<div id="content" align="left" >' +
'<h1>Parcel Details</h1>' +
'<h3>Parcel Id:' + data.ParId + '</h3>' +
'<h3>Rank:' + data.RANK + '</h3>' +
'<h3>Captured by:' + data.Capturedby + '</h3>' +
'<h3>Captured Date:' + data.Capturedate + '</h3>' +
'</div>';
infoBubble = new InfoBubble({
maxWidth: 300,
maxHeight: 200,
backgroundColor: 'rgb(236,255,255)'
});
infoBubble.open(map, marker);
var div = document.createElement('DIV');
div.align = "left";
div.innerHTML = '<IMG BORDER="0" ALIGN="Left" width=97% height=200px alt="Pulpit rock1" SRC="' + data.IMAGEPATH + '"/>';
infoBubble.addTab('Photo', div);
infoBubble.addTab('Details', contentString);
(function (marker, data) {
google.maps.event.addListener(marker, 'click', function () {
// if (!infoBubble.isOpen()) {
infoBubble.open(map, marker);
alert("Par Id:" + data.ParId);
//alert("2");
//}
//infoWindow.open(map);
});
// alert(data.title);
//google.maps.event.trigger(marker, 'click'); //stil
}(marker, data));
}
}
google.maps.event.addDomListener(window, 'load', onload);
the infoBubble-variable will be overwritten inside the loop.
Solution: pass the infoBubble as argument to the function that adds the click-listener:
(function (marker, data , infoBubble) {
google.maps.event.addListener(marker, 'click', function () {
infoBubble.open(map, marker);
});
}(marker, data, infoBubble));

Got a fault in my google maps code

I am making a google maps for my website so you can view where each user is.
This works perfect only when you click on an icon of someone it will show you the same every time i cant understand it am i doing something wrong?
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","includes/xml.php",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("USER");
var infoWindow = new google.maps.InfoWindow();
var map;
var users = [];
function initialize() {
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(52.1424, 5.09428),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i=0;i<x.length;i++) {
var id = x[i].getElementsByTagName("USERID")[0].childNodes[0].nodeValue;
users['USERNAME'+id] = x[i].getElementsByTagName("USERNAME")[0].childNodes[0].nodeValue;
users['CITY'+id] = x[i].getElementsByTagName("CITY")[0].childNodes[0].nodeValue;
users['COUNTRY'+id] = x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
users['IMAGE'+id] = x[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue;
users['IMAGEPIN'+id] = x[i].getElementsByTagName("IMAGEPIN")[0].childNodes[0].nodeValue;
users['LAT'+id] = x[i].getElementsByTagName("LAT")[0].childNodes[0].nodeValue;
users['LONG'+id] = x[i].getElementsByTagName("LONG")[0].childNodes[0].nodeValue;
users['DATETIME'+id] = x[i].getElementsByTagName("DATETIME")[0].childNodes[0].nodeValue;
users['TWITTER'+id] = x[i].getElementsByTagName("TWITTER")[0].childNodes[0].nodeValue;
users['FA'+id] = x[i].getElementsByTagName("FA")[0].childNodes[0].nodeValue;
users['ACTIVEUSER'+id] = x[i].getElementsByTagName("ACTIVEUSER")[0].childNodes[0].nodeValue;
users['myLatlng'+id] = new google.maps.LatLng(users['LAT'+id],users['LONG'+id]);
users['content'+id] = '<div style="width:220px;"><img id="avatar"style="margin-right: 5px;" src="' + users['IMAGE'+id] + '"></img>' +
'<b>' + users['USERNAME'+id] + '</b><br />' +
users['CITY'+id] + '<br />' + users['COUNTRY'+id] + '<br />' +
'<i>' + users['DATETIME'+id] + '</i><br />' +
'<img src="http://www.kinzart.com/images/fur-affinity-icon.png" Alt="Twitter" width="30" height="30">' +
'<img src="http://biophiliccities.org/wp-content/uploads/2013/06/twitterICON.png" Alt="Twitter" width="30" height="30">';
users['window'+id] = new google.maps.InfoWindow({ content: users['content'+id]});
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
google.maps.event.addListener(users['marker'+id], 'click', function() { infoWindow.setContent(users['content'+id]); infoWindow.open(map, users['marker'+id]) });
}
}
google.maps.event.addDomListener(window, 'load', initialize);
The problem is that when you setup your event listener within the loop, it ends up that every iteration of the loop sets the infowindow content to be whatever the last value of users['content'+id] is. You need to look into using closures in your code.
Here's another way of doing it that should work:
for (i=0;i<x.length;i++) {
... // trimmed for brevity
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
bindInfoWindow(users['marker'+id], users['content'+id]);
}
then have this function:
function bindInfoWindow(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(content);
infoWindow.open(map, marker)
});
}

Categories

Resources