创建具有多个标记和弹出窗口的自定义Google地图 - 问题 [英] Creating a custom google map with multiple markers and popup windows - Issues

查看:103
本文介绍了创建具有多个标记和弹出窗口的自定义Google地图 - 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建一个自定义的Google地图,我已经编写了代码,但有些不太正确,想知道有没有人可以指出我做错了什么。代码在这里:

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();

  countries.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);
      });

}

推荐答案

除了使用错误的样式 for 循环,你试图在循环中创建一个功能这是一个非常常见的错误。由于JS具有功能级别的作用域,而不是阻止级别,因此您无法正常工作。

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.

尝试这样:

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));
}

这篇关于创建具有多个标记和弹出窗口的自定义Google地图 - 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆