【问题标题】:Google maps api V3 this is undefined error on getCenter() after ajax addedGoogle maps api V3 这是添加 ajax 后 getCenter() 上未定义的错误
【发布时间】:2016-02-15 08:10:36
【问题描述】:

我正在尝试在地图拖动后通过 ajax 更新搜索结果。 这是我正在使用的代码。

function initMap(){
var locations = [];
var count = 0;
$('.oneListing').each(function(){
    locations[count] = {title:$(this).html(),lat: $(this).data('lat'), lng: $(this).data('lng')};
    count ++;
})

window.map = new google.maps.Map(document.getElementById('map_canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

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

var bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
        map: map
    });

    bounds.extend(marker.position);

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent(locations[i]['title']);
            infowindow.open(map, marker);
        }
    })(marker, i));
}

map.fitBounds(bounds);

var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(4);
    google.maps.event.removeListener(listener);
});

    map.addListener('dragend', function() {
        var zoom = map.getZoom();
        var center = map.getCenter();
        updatesearch(center, zoom);
    });
}
function updatesearch(center, zoom){
    jQuery.ajax({
        url: '/searches/update',
        type: 'post',
        data: {zoom: zoom,center: center},
        success: function(data){
            alert(data)
        }            
    })
}

在此之后我收到错误消息说TypeError: this is undefined 它发生在 getCenter() 函数上。 什么会导致这种错误,我能做些什么来避免它。 我正在使用 jquery v1.11.1 让我知道是否需要其他信息。 仅在我尝试对后端进行 ajax 调用以获取新项目后才会出现此错误。否则 getCenter() 返回正确的结果。

【问题讨论】:

  • 我觉得情况不太一样。在他的情况下,他丢失了变量的内容或没有得到它。在我的情况下,我在输入代码 ajax 以调用后端后出现错误。否则我会得到很好的中心latlng。
  • 抱歉忘记提问了,问题已更新。
  • 所以你是说如果你在你的dragend监听器中删除对updatesearch的调用就不会发生错误?如果是这样,请尝试将其替换为中心警报。将 updatesearch(center, zoom); 更改为 alert(center); 以查看它是否仍然未定义。
  • 是的,在这种情况下,我得到了正确的 latlng,即使我没有评论函数调用,而只是评论来自它的 ajax 调用,而是提醒中心

标签: javascript jquery ajax google-maps google-maps-api-3


【解决方案1】:

我发现了问题所在。 getCenter() 正在返回对象而不是字符串,这就是为什么在 ajax 的数据中使用变量后我得到了那个错误。 解决方案是在中心变量上调用 lat() 和 lng() 函数,然后将其传递给 ajax。

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 2012-06-07
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2012-11-06
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多