标记和infowindows谷歌地图

时间:2017-10-24 17:04:35

标签: javascript google-maps

我正在尝试使用for循环从api中输出标记和信息窗口,但只获取列表中的最后一个。我有for循环,因为我需要遍历API并将我的信息基于此。但在我看来,我也应该在循环中放出标记或?

    //get all the restaurants which are open
$.getJSON(uri, function(data) {
    for(i = 0; i < 5; i++) {
        var place = data.response.groups[0].items[i].venue.name;
        var placeLat = data.response.groups[0].items[i].venue.location.lat;
        var placeLng = data.response.groups[0].items[i].venue.location.lng;
        var placeAddress = data.response.groups[0].items[i].venue.location.formattedAddress;
        var openPlace = data.response.groups[0].items[i].venue.hours;
        var placeGenre = data.response.groups[0].items[i].venue.categories[0].shortName;
        console.log(place, placeLat, placeLng, placeAddress, openPlace)
        var placePosition = {
            lat: placeLat,
            lng: placeLng
        }

        var marker = new google.maps.Marker({
            position: placePosition,
            map: map
        });

        var infowindow = new google.maps.InfoWindow();

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
            infowindow.open(map, this);
        });
    }
});
map.setCenter(pos);
    }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } 
    else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

感谢您的期待

1 个答案:

答案 0 :(得分:0)

我尝试并完成了代码。

第一种方法: 实际上,IIFE对于这种情况非常有用。

(function(place, placeGenre, placeAddress, openPlace, map, marker){
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
        infowindow.open(map, marker);
    })
})(place, placeGenre, placeAddress, openPlace, map, marker)

第二种方法: 在循环中调用一个函数,然后传递值。

setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow);

在外面定义setInfowindow函数:

function setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow) {
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>');
        infowindow.open(map, marker);
    })
}