javascript - 防止加载无限循环

标签 javascript jquery asp.net-mvc-3 google-maps razor

我有一个问题。 .我怎样才能防止这种无限循环,因为我是 Google map 和 Jquery 的新手。

我读了很多答案,但没有一个是有效的

这是我的代码:

<script type="text/javascript">
    var geocoder, infoBubble;
    var map;
    //var mgr;

    function initialize() {
        var minZoomLevel = 4;
        var zooms = 7;
        geocoder = new google.maps.Geocoder();

        map = new google.maps.Map(document.getElementById('map'), {
            zoom: minZoomLevel,
            center: new google.maps.LatLng(38.50, -90.50),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        // Bounds for North America
        var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(15.70, -160.50),
     new google.maps.LatLng(68.85, -55.90)
   );

        // Listen for the dragend event
        google.maps.event.addListener(map, 'dragend', function () {
            if (strictBounds.contains(map.getCenter())) return;

            // We're out of bounds - Move the map back within the bounds

            var c = map.getCenter(),
         x = c.lng(),
         y = c.lat(),
         maxX = strictBounds.getNorthEast().lng(),
         maxY = strictBounds.getNorthEast().lat(),
         minX = strictBounds.getSouthWest().lng(),
         minY = strictBounds.getSouthWest().lat();

            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;

            map.setCenter(new google.maps.LatLng(y, x));
        });


        // Limit the zoom level
        google.maps.event.addListener(map, 'zoom_changed', function () {
            if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
        });
        codeAddress();
    }

    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    function codeAddress() {
        infoBubble = new InfoBubble({
            map: map,
            shadowStyle: 0,
            padding: 10,
            borderRadius: 10,
            arrowSize: 15,
            maxWidth: 300,
            borderWidth: 1,
            borderColor: '#ccc',
            arrowPosition: 50,
            arrowStyle: 0
        });
        $.getJSON('/Dashboard/LoadWorkerList', function (address) {
            $.each(address, function () {
                var currVal = this["AddressLine1"];
                var Name = this["Name"];
                var Gender = this["Gender"];
                var Bdate = this["Birthdate"];
                var ID = this["Worker_ID"];
                geocoder.geocode({ 'address': currVal }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var marker = new google.maps.Marker({
                            map: map,
                            icon: iconBase + 'man.png',
                            position: results[0].geometry.location,
                            title: currVal
                        })

                        var link = $('<a href="#">' + currVal + '</a>')
                         .data('location', results[0].geometry.location);
                        $('#places').append($('<li>').append(link));
                        link.on('click', function (event) {
                            event.preventDefault();
                            google.maps.event.trigger(address[0], "click");
                            infoBubble.removeTab(0);
                            infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br><br>" + '<center><a href="/Worker/WorkerDetails?workerId=' + ID + '">View Profile</a></center>');
                            infoBubble.open(map, marker);
                        }
);

                        google.maps.event.addListener(map, 'idle', function () {
                            $('#places li a').css('display', function () {
                                return (map.getBounds().contains($(this).data('location')))
                      ? ''
                      : 'none';
                            });
                        });



                        google.maps.event.addListener(marker, 'click', (function (marker, i) {
                            return function () {
                                infoBubble.removeTab(0);
                                infoBubble.addTab(Name, "Name: " + Name + "<br> Address: " + currVal + "<br> Gender: " + Gender + "<br> Birthdate: " + Bdate + "<br><br>" + '<center><a href="/Worker/WorkerDetails?workerId=' + ID + '">View Profile</a></center>');
                                infoBubble.open(map, marker);
                            }
                        })(marker, currVal));
                        address.push(marker);

                    }
                    else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                        setTimeout(codeAddress, 2000);
                    }
                    else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });
            });
            google.maps.event.trigger(map, 'bounds_changed');
        });
    }

    window.onload = function () {
        initialize();
    }

</script>

我认为这是导致项目循环的原因

` window.onload = function () {
            initialize();
        }`

还有这个

` google.maps.event.addListener(map, 'zoom_changed', function () {
                if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
            });
            codeAddress();    <------- This one`

最佳答案

initialize 的调用不是无限循环的原因,initialize 将被调用 1 次。

我看到无限循环的唯一原因是代码地址:

 else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                    setTimeout(codeAddress, 2000);
                }

当此条件为真时,您再次调用 codeAddress 没有区别,您将一次又一次地得到相同的结果(延迟 2 秒)。

您可以:

  1. /Dashboard/LoadWorkerList 最多只返回 10 个地址
  2. /Dashboard/LoadWorkerList 的返回中省略之前请求中已经返回的地址

或:

每次调用 geocoder.geocode 时使用增加的超时时间(增加 150 毫秒)

关于javascript - 防止加载无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677822/

相关文章:

javascript - 如何从正则表达式匹配函数中获取匹配的组?

javascript - 常规 JavaScript 可以与 jQuery 混合使用吗?

javascript - 如何使用 PHP 和 JQuery AJAX 在 <div> 标签中检索和插入 MySQL 数据?

javascript - 将事件处理程序添加到动态添加的元素

c# - MVC3 和 Ajax : Refresh list to hide a record which was deleted from list by a button click

asp.net - 将 ASP.NET MVC4 应用程序部署到 GoDaddy 编译器问题

javascript - 不允许在文本框验证中使用特殊字符

javascript - 从纬度经度获取国家

javascript - jQuery 图像绝对源路径

jquery - 使用 JQuery 加载刷新后 HTML 表格行变得太宽