I'm using the lastest version of google maps, and trying to print the markers
in the map
. To do that, I'm using:
function initmap2() {
map2 = new google.maps.Map(document.getElementById('map-scan'), {
zoom: 16,
styles: style,
center: { lat: 13.7218501, lng: -89.2039192 }
});
for (i = 0; i < positions.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
});
}
var markers = positions.map(function (location, i) {
return new google.maps.Marker({
position: location,
});
});
for (var i = 0; i < markers.length; i++) {
markers[i].info = new google.maps.InfoWindow({
content: '<b>' + positions[i]["title"].toUpperCase() + '</b>'
});
markers[i].info.open(map2, markers[i]);
}
}
The markers are displayed in the right position, but the InfoWindws
are very distanced of them.
Why I'm using map2
instead of map
. I have preloaded another googlemap
and the map2
is loaded in a dialog (on demand, when the dialog is open)
How to fix this behavior?
Your problem is this... you loop over positions
, creating a marker for each of your positions:
for (i = 0; i < positions.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
});
}
You then do the same thing again:
var markers = positions.map(function (location, i) {
return new google.maps.Marker({
position: location,
});
});
And at the end of this 2nd way of doing it, markers
is an array of markers. Which you then loop over to setup the infowindows.
However, the first time you created the marker, you specified the map
attribute. So those markers show up on the map. The second time you didn't bother, so these markers aren't on the map.
You've got markers visible thanks to your first way of doing it. But then you're attaching the infowindows to the non-visible markers created the second way! :-/
The code's a bit of a mess, you can do it all in just the one loop over positions
, and make sure you specify the map
property for each marker. I'd just do:
var markers = [];
for (i = 0; i < positions.length; i++) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
}));
markers[i].info = new google.maps.InfoWindow({
content: '<b>' + positions[i]["title"].toUpperCase() + '</b>'
});
markers[i].info.open(map2, markers[i]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.