未捕获的RangeError:当我使用谷歌地图时,超出了最大调用堆栈大小

时间:2015-08-06 21:59:47

标签: javascript google-maps-api-3 stack-overflow

我正在尝试使用谷歌地图和标记编写简单示例,但我面临错误:

Uncaught RangeError: Maximum call stack size exceeded

JS:

$(document).ready(function() {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var markers = [];
    coords = [{
        lat: 55,
        lng: 37
    }];
    for (var x = 0; x < coords.length; x++) {
        var latlng = new google.maps.LatLng(x.lat, x.lng);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
        markers.push(marker);


    }

    fitBounds();

    function fitBounds() {
        var bounds = calculateBounds();
        if (bounds != undefined) {
            map.fitBounds(bounds);
        }
    }

    function calculateBounds() {
        var allMarkers = markers;
        if (allMarkers.length > 0) {
            var bounds = new google.maps.LatLngBounds();
            for (i = 0; i < allMarkers.length; i++) {
                bounds.extend(allMarkers[i].getPosition());
            }
        }
        return bounds;
    }

});

fiddle

1 个答案:

答案 0 :(得分:8)

调用Uncaught RangeError: Maximum call stack size exceeded时出现错误fitBounds通常意味着您使用无效的bounds.extend对象调用google.maps.LatLng

这是不正确的(x.lat和x.lng未定义):

for (var x = 0; x < coords.length; x++) {
    var latlng = new google.maps.LatLng(x.lat, x.lng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
    markers.push(marker);
}

它产生纬度为lat:NaN,lng:NaN

哪个无效。

应该是:

for (var x = 0; x < coords.length; x++) {
    var latlng = new google.maps.LatLng(coords[x].lat, coords[x].lng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
    markers.push(marker);
}

updated fiddle