Uncaught RangeError: Maximum call stack size excee

2019-09-16 13:46发布

I am trying to write simple example with google maps and markers but i faces with error:

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条回答
Fickle 薄情
2楼-- · 2019-09-16 13:59

The error Uncaught RangeError: Maximum call stack size exceeded when calling fitBounds usually means you have called bounds.extend with an invalid google.maps.LatLng object.

This is incorrect (x.lat and x.lng are undefined):

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);
}

It yields latlng with lat: NaN, lng: NaN

Which isn't valid.

should be:

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

查看更多
登录 后发表回答