开发者

Creating a custom google map with multiple markers and popup windows - Issues

Been trying to create a custom google map, i've written the code but something isn't quite right, wondered if anyone could point out what I've done wrong. Code is here:

<script type="text/javascript">
  function initialize() {
    var myLatlng = new google.maps.LatLng(30,0);
    var myOptions = {
      zoom: 2,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN
  }

  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var countries = Array();

  countrie开发者_运维百科s.push({
      marker: new google.maps.Marker({position: new google.maps.LatLng(4.52,115), map: map, title: 'Test'}),
      infowindow: new google.maps.InfoWindow({content: "Hello world"})
  });
  countries.push({
      marker: new google.maps.Marker({position: new google.maps.LatLng(42.45,23.20), map: map, title: 'Test2'}),
      infowindow: new google.maps.InfoWindow({content: "Hello world2"})
  });
  countries.push({
      marker: new google.maps.Marker({position: new google.maps.LatLng(12.15,-1.30), map: map, title: 'Test3'}),
      infowindow: new google.maps.InfoWindow({content: "Hello world3"})
  });

  for each (var item in countries) {
      google.maps.event.addListener(item.marker, 'click', function() {
        item.infowindow.open(map, item.marker);
      });

}


Aside from using the wrong style for loop, you're trying to make a function in a loop. This is a very common mistake. Since JS has function-level scoping, not block level, this doesn't work as you might expect.

Try this:

function makeCallback(country) {
    return function () {
        country.infowindow.open(map, country.marker);
    };
}

var item;
for (var i=0; i<countries.length; i++) {
    item = countries[i];
    google.maps.event.addListener(item.marker, 'click', makeCallback(item));
}


It seems to work fine, I see a map with 3 markers but without knowing what the problem is it's hard to tell.

A few guesses:

  • You're missing a curly brace at the end which closes initialize
  • Do you have a div with an id of "map_canvas"?
  • Is initialize being called from anywhere?
  • Have you included the Google maps javascript?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜