简体   繁体   中英

javascript google maps api v3 markers and infowindow

I have a problem with google maps api v3 and markers with infowindow.

following part of code set markers, but its not possible to access the infowindows with click.

var infowindow = new google.maps.InfoWindow();
var marker, i;
function setMarker(){
 for (i = 1; i < 240; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(line[i][0], line[i][1]),
    map: map2
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent("Test");
infowindow.open(map,marker);
});
}
}

I hope someone can help me :)?

If everything else is alright then variable scoping problem and in infowindow.open(map, marker) should be map2

var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 1; i < 240; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(line[i][0], line[i][1]),
    map: map2
  });

  google.maps.event.addListener(marker, 'click', (function(marker) {
    return function() {
      infowindow.setContent("Test");
      infowindow.open(map2, marker);
    }
  })(marker));
}

Maybe this is the problem:

infowindow.open(map2,marker);

Where you declaring map2 ? What is map ?

If you have an array of locations like following

var locations = [
    [33.890542, 150.274856],
    [36.923036, 152.259052],
    [38.028249, 154.157507]
];

then you can use following code

function initialize() {
    var myLatlng = new google.maps.LatLng(locations[0][0], locations[0][1]);
    var myOptions = {
        zoom: 4,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    for(var i=0;i<locations.length;i++)
    {
        var latlng=new google.maps.LatLng(locations[i][0], locations[i][1]);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: "marker : "+(i+1)
        });
    }     
}
google.maps.event.addDomListener(window, 'load', initialize);

Working Example

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM