以编程方式向Google地图添加按钮以跳转到标记

时间:2015-12-07 07:35:53

标签: ajax google-maps google-maps-api-3 google-maps-markers

我通过Laravel从mySQL中提取数据,生成一张效果很好的地图,现在我只想要跳转到每个标记的按钮。出于某种原因,它只会到达最后一个位置。

    $.ajax({
      url: '/lookup',
      type: "post",
      data: {'lat':$("#lat").val() ,'lng':$("#lng").val(), '_token': $('input[name=_token]').val()},
      success: function(data){
        var nearest = data;
        var markers = data;

        // Loop through our array of markers & place each one on the map  
        for( i = 0; i < markers.length; i++ ) {
            var position = new google.maps.LatLng(markers[i].lat, markers[i].lng);
            bounds.extend(position);
            marker = new google.maps.Marker({
                position: position,
                map: map,
                title: markers[i].name,
                icon: 'http://website.com/assets/images/icons/love_google.png'
            });

            google.maps.event.addDomListener(document.getElementById("link_"+i), "click", function(e) {
                alert(position);
                map.setCenter(position);
            });
            // Allow each marker to have an info window    
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    //infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.setContent('<div class="info_content"><h3>' + markers[i].name + '</h3><p>' + markers[i].address + '<br />' + markers[i].city + ', ' + markers[i].state + ' ' + markers[i].zip + '<br /><a href="tel:' + markers[i].phone + '">' + markers[i].phone + '</a></p></div>' );
                    infoWindow.open(map, marker);
                }
            })(marker, i));

        }

      }
    });

1 个答案:

答案 0 :(得分:1)

您应该按照与标记点击相同的方式构建按钮单击的事件侦听器。问题是,当您单击按钮时position将是该变量在该时间点的任何内容,而不是构建事件侦听器时循环迭代中的任何变量。

尝试类似:

google.maps.event.addDomListener(document.getElementById("link_"+i), "click", (function(position) {
    return function() {
        alert(position);
        map.setCenter(position);
    }
})(position));