调用函数内部的函数

calling functions inside function

本文关键字:函数 内部 调用      更新时间:2023-09-26

我使用的是谷歌地图,我有在地图上显示标记的工作代码。我现在想把这个代码放在函数view_maps()中,并在单击时激活这个函数。到目前为止,我得到了错误超过了最大调用堆栈大小并且getAddress不是函数。这是有效的,但当view_maps()函数内部的代码出现这些错误时。

function view_maps() {
    function marker_map() {
        var url = "http://example.co.uk/deliveries/map/get_region_orders";
        var region = $("ul#regions").children("li[data-active='1']").attr("class");
        var data = {
            region: region
        };
        var obj = {};
        var locations = [];
        var details_array = [];
        $.ajax({
            type: "POST",
            url: "http://example.co.uk/deliveries/map/get_region_orders",
            data: data,
            async: false,
            success: function(response) {
                var result = $.parseJSON(response);
                jQuery.each(result, function(i) {
                    var order_id = result[i].order_id;
                    var customer_name = result[i].customer_name;
                    var address_1 = result[i].address_1;
                    var address_2 = result[i].address_2;
                    var post_code = result[i].post_code;
                    var address = post_code;
                    var details = "<b>Order Number: " + order_id + "</b><br>" + address_1 + "<br>" + address_2 + "<br>" + post_code;
                    details_array.push(details);
                    locations.push(address);
                });
            }
        });
        obj['address'] = locations;
        obj['details'] = details_array;

        return (obj);
    }
    // delay between geocode requests - at the time of writing, 100 miliseconds seems to work well
    var delay = 70;
    // ====== Create map objects ======
    var infowindow = new google.maps.InfoWindow();
    var latlng = new google.maps.LatLng(53.381021, -2.608138);
    var mapOptions = {
        zoom: 9,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var geo = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById("marker-map"), mapOptions);
    var bounds = new google.maps.LatLngBounds();
    // ====== Geocoding ======
    function getAddress(search, count, next) {
        geo.geocode({
            address: search
        }, function(results, status) {
            // If that was successful
            if (status == google.maps.GeocoderStatus.OK) {
                // Lets assume that the first marker is the one we want
                var p = results[0].geometry.location;
                var lat = p.lat();
                var lng = p.lng();
                // Output the data
                var msg = 'address="' + search + '" lat=' + lat + ' lng=' + lng + '(delay=' + delay + 'ms)<br>';
                document.getElementById("messages").innerHTML += msg;
                // Create a marker
                createMarker(search, count, lat, lng);
            }
            // ====== Decode the error status ======
            else {
                // === if we were sending the requests to fast, try this one again and increase the delay
                if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                    nextAddress--;
                    delay++;
                } else {
                    var reason = "Code " + status;
                    var msg = 'address="' + search + '" error=' + reason + '(delay=' + delay + 'ms)<br>';
                    //document.getElementById("messages").innerHTML += msg;
                }
            }
            next();
        });
    }
    // ======= Function to create a marker
    function createMarker(add, count, lat, lng) {
        var contentString = add;
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            map: map,
            zIndex: Math.round(latlng.lat() * -100000) << 5
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(details_array[count]);
            //infowindow.setContent(contentString); 
            infowindow.open(map, marker);
        });
        bounds.extend(marker.position);
    }
    // ======= An array of locations that we want to Geocode ========
    //console.log(marker_map());
    var locations = marker_map();
    var addresses = locations.address;
    var details_array = locations.details;
    // ======= Global variable to remind us what to do next
    var nextAddress = 0;
    // ======= Function to call the next Geocode operation when the reply comes back
    function theNext() {
        if (nextAddress < addresses.length) {
            setTimeout('getAddress("' + addresses[nextAddress] + '","' + nextAddress + '",theNext)', delay);
            nextAddress++;
        } else {
            // We're done. Show map bounds
            map.fitBounds(bounds);
        }
    }
    // ======= Call that function for the first time =======
    theNext();
}

我该如何解决?我认为这与函数的作用域有关,因为getAddress显然是一个函数。

您必须用这个函数来更改您的theNext函数。

function theNext() {
    if (nextAddress < addresses.length) {
    setTimeout(getAddress(addresses[nextAddress],nextAddress,theNext), delay);
    nextAddress++;
    } else {
        // We're done. Show map bounds
        map.fitBounds(bounds);
    }
}

请参阅setTimeout中的更改,我正在调用不传递字符串的函数(稍后将进行评估并在全局范围内搜索)

我还创建了一个演示来验证概念。享受:)