I'm developing an application where I get a list of companies and their location (latitude and longitude), so I have to plot all these locations in Google Maps
, my problem and when trying to add a listner
to capture the click in these markers and then open a infoWindow
.
My code:
empresaMark;
empresasMarkers = [];
for (var i = 0; i < empresas.length; i++) {
empresaMark = new google.maps.Marker({
position: { lat: Number(empresas[i].Latitude), lng: Number(empresas[i].Longitude) },
map: map,
title: empresas[i].Nome,
icon :'../Content/imagens/Icones/Markers/building-marker.png'
});
empresaMark.info = new google.maps.InfoWindow({
content: '<IMG BORDER="0" class="img img-rounded" style="height:55px;width:55px;margin-right:10px;object-fit: cover" ALIGN="Left" SRC='
+ empresaMark.LinkFoto + '>'
+ empresaMark.Nome
});
empresaMark.addListener('click', function() {
empresaMark.info.open(map, empresaMark);
});
empresaMarkers.push(empresaMark);
}
The error occurs in the following part of the code in object empresaMark
:
empresaMark.addListener('click', function() {
empresaMark.info.open(map, empresaMark);
});
The error is as follows:
Closure on a variable in loop of outer scope
I've been reading about Closure
and I've seen some questions in stackoverflow
but I could not fully understand, much less apply to my code if someone can explain to me what I need to do to fix this code and the usefulness of% how would i be grateful.
Some questions I've seen:
JavaScript closure inside loops - simple practical example
Javascript infamous Loop issue? [duplicate]
How to make object in loop in js with external value in javascript?