【问题标题】:Initialising Google map with multiple markers使用多个标记初始化 Google 地图
【发布时间】:2010-09-29 12:19:36
【问题描述】:

我正在尝试开发一个应用程序,从数据库中提取地址以使用我网站上的谷歌地图上的标记显示它们。

我有以下 javascript 代码 + jquery 、google maps 和所有其他必要的 javascript 文件:

$(document).ready(function(){

    // initialise map
    var myLatlng = new google.maps.LatLng(50.52,4.22);
    // specify options
    var myOptions = {
        zoom: 5,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    // attach map to html and set reference
    var map = new google.maps.Map(document.getElementById("googlemap"), myOptions);

    // markers array
    var markers = Array();

    // infowindows array
    var infos = Array();

    var lat = 50;
    for(var j = 0; j < 5; j++){

        var contentString = '<div id="content">test</div>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat,4.22),
            map: map,
            title: 'Europe'
        });

        // push vars to arrays markers and infos
        markers.push(marker);
        infos.push(infowindow);

        lat = lat + 1;

    }

    for(var i = 0; i < markers.length; i++) {
        google.maps.event.addListener(markers[i], 'click', clickHandler(i));
    }

    function clickHandler(i) {
        infowindow.open(map,infos[i]);
    }

});

为了测试/模拟我将使用 PHP 从数据库中提取数据的 for 循环,我插入了小的 for 语句来填充标记和 infos 数组。

一切正常(显示标记),除了单击标记不显示信息框。

Onload 我在 firebug 中也遇到了这个错误: 参数应为函数类型第 23 行 - http://maps.gstatic.com/intl/nl_ALL/mapfiles/api-3/2/7/main.js

有人可以帮忙吗?

另外一个问题:如何将街道号码、邮政编码、城市等字符串地址转换为纬度和经度?

谢谢!

【问题讨论】:

标签: javascript jquery google-maps


【解决方案1】:

标记显示的问题在于您正在调用:

infowindow.open(map,infos[i]);

第二个参数应该是一个标记,而不是信息。

infowindow.open(map,marker);

javascript错误来自于此:

google.maps.event.addListener(markers[i], 'click', clickHandler(i));

该代码实际上调用 clickHandler 并尝试将返回值(无)作为参数传递给侦听器,而不是将 clickHandler 绑定为事件函数。修复它以指向一个函数仍然不会产生你想要的,这在http://code.google.com/apis/maps/documentation/javascript/events.html#EventClosures中进行了讨论

所以你应该这样做:

addEventListener(markers[i]);

function addEventListener(marker) {
   google.maps.event.addListener(marker, 'click', function() {
     infowindow.open(map, marker);
   });
}

要转换街道编号等坐标,请查看 Google 的地理编码 API:http://code.google.com/apis/maps/documentation/geocoding/index.html

【讨论】:

  • 很高兴听到!如果确实解决了您的问题,请记住接受答案。
猜你喜欢
  • 2012-07-19
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多