0

我一直在尝试创建一个具有可点击标记的谷歌地图,并且缩放级别适应地图上标记的数量,我有以下代码,我知道它不太正确,但无法弄清楚为什么,任何关于我哪里出错的指针将不胜感激!

<script type="text/javascript">
function initialize() {

  // My options
  var myOptions = {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }

  // Create map on #map_canva
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  // Define boundarys
  var markerBounds = new google.maps.LatLngBounds();

  // Create array
  var countries = [
      {title:'Theatre by the Lake', lat:54.32223562211788, lon:-2.742498400000045, content:"<h2>Theatre by the Lake</h2>"},
      {title:'Pirelli International Rally',  content:"<h2>Pirelli International Rally</h2>"},
      {title:'Lowther Castle',  content:"<h2>Lowther Castle</h2>"},
      {title:'South Lakes Wild Animal Park',  content:"<h2>South Lakes Wild Animal Park</h2>"},
      {title:'Cumbria Karting',  content:"<h2>Cumbria Karting</h2>"},
  ];

  // Create markers
  for (var i = 0; i < countries.length; i++) { 
      var c = countries[i]; 
      c.marker = new google.maps.Marker({
          position: new google.maps.LatLng(c.lat, c.lon), 
          map: map,
          icon: '/display_images/icon_stockist.png',
          title: c.title});
      c.infowindow = new google.maps.InfoWindow({content: c.content}); 
      google.maps.event.addListener(c.marker, 'click', makeCallback(c)); 
      // Create marker bounds
      markerBounds.extend(countries);
  } 

  // Create info windows based on above content
  function makeCallback(country) { 
      return function () { 
          country.infowindow.open(map, country.marker); 
      }; 
  }
}

// Fit map to marker boundaries
map.fitBounds(markerBounds);
</script>
4

1 回答 1

1

您的问题是您在初始化函数中将 map 创建为局部变量,然后在调用时尝试使用该函数访问它,而该函数map.fitBounds无法访问它。

要么声明 map outwith of initialize,要么在你的初始化函数中移动 map.fitBounds() 。

此外,当您调用 时markerBounds.extend(countries);,您将整个国家数组传递给它,而您真正需要的是传递一个单一的 LatLng 对象。尝试这样的事情:

for (var i = 0; i < countries.length; i++) { 
      var c = countries[i]; 
      var latlng = new google.maps.LatLng(c.lat, c.lon);
      c.marker = new google.maps.Marker({
          position: latlng, 
          map: map,
          icon: '/display_images/icon_stockist.png',
          title: c.title});
      c.infowindow = new google.maps.InfoWindow({content: c.content}); 
      google.maps.event.addListener(c.marker, 'click', makeCallback(c)); 
      // Create marker bounds
      markerBounds.extend(latlng);
  } 
于 2013-04-11T14:39:51.627 回答