代码之家  ›  专栏  ›  技术社区  ›  richjh205

在谷歌地图中创建多个单独的信息窗口和多个标记

  •  0
  • richjh205  · 技术社区  · 12 年前

    我的项目搜索易趣API(使用PHP并返回simpleXML),并返回多个项目的邮政编码(目前为5)。然后使用这些信息在我的网站上的谷歌地图上绘制标记。我想做的是创建多个信息窗口和这些标记,这样我也可以从易趣拍卖中返回信息并将其放入信息窗口(拍卖链接、物品图片等),但我运气不好!我似乎无法在循环中正确地获得闭包,我一直在信息窗口中显示数组中的最后一个邮政编码,而不是与该标记实际关联的邮政编码(这样做只是为了测试目的)。

    我做错了什么?任何信息都会有所帮助。

    这是我目前的代码:

    for (var i = 0; i < msg.length; i++) {
        info = msg[i];
        console.log(info);
        geocoder.geocode( { 'address': msg[i]}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    animation: google.maps.Animation.DROP,
                    icon: image,
                    position: results[0].geometry.location
                })
                listenMarker(marker);
                markerBounds.extend(results[0].geometry.location);
                map.fitBounds(markerBounds);
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    
    function listenMarker (marker){
        google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(info);
        infoWindow.open(map, this);
    });
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   geocodezip    12 年前

    您还需要在地理编码器调用上使用函数闭包(未测试),看起来您的listMarker函数也可能有问题(似乎缺少“info”的定义,如果您依赖于它的全局值,那可能是您的问题):

    function geocodeAddress(msg)
    {
                geocoder.geocode( { 'address': msg}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                map: map,
                animation: google.maps.Animation.DROP,
                icon: image,
                position: results[0].geometry.location
                })
                    listenMarker(marker, msg);
                    markerBounds.extend(results[0].geometry.location);
                    map.fitBounds(markerBounds);
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    
    for (var i = 0; i < msg.length; i++) {
                info = msg[i];
                console.log(info);
                geocodeAddress(msg[i]);
    }
    
    function listenMarker (marker, info){
        google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(info);
        infoWindow.open(map, this);
    });