在函数内部调用函数

时间:2016-05-19 10:16:27

标签: javascript jquery google-maps

我正在使用谷歌地图,我有工作代码在地图上显示标记。我现在想将此代码放在函数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 显然是一个函数。

1 个答案:

答案 0 :(得分:0)

你必须用这个改变你的下一个功能。

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中的更改,我正在调用函数而不是传递字符串(稍后将评估并在全局范围内搜索)

我还创建了一个demo来证明概念。享受:)