Javascript 化为乌有

Javascript 化为乌有,javascript,Javascript,我正在使用GoogleMapsAPI,这段代码将异步返回一个位置列表。在收集所有数据时,如何调用此函数并使其触发某些内容?到目前为止,我一直在尝试这样做- $.search = function(boxes) { function findNextPlaces(place_results, searchIndex) { var dfd = $.Deferred(); if (searchIndex < boxes.length) {

我正在使用GoogleMapsAPI,这段代码将异步返回一个位置列表。在收集所有数据时,如何调用此函数并使其触发某些内容?到目前为止,我一直在尝试这样做-

$.search = function(boxes) {

    function findNextPlaces(place_results, searchIndex) {
        var dfd = $.Deferred();
        if (searchIndex < boxes.length) {
            service.radarSearch({
                bounds: boxes[searchIndex],
                types: ["food"]
            }, function (results, status) {
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    return dfd.reject("Request["+searchIndex+"] failed: "+status);
                }
                console.log( "bounds["+searchIndex+"] returns "+results.length+" results" );
                for (var i = 0, result; result = results[i]; i++) {
                    var marker = createMarker(result);
                    place_results.push(result.reference); // marker?
                }
            });
            return dfd.then(findNextPlaces);
        } else {
            return dfd.resolve(place_results).promise();
        }
    }

    return findNextPlaces([], 0);
};
$.search=函数(框){
函数findNextPlaces(place\u结果、searchIndex){
var dfd=$.Deferred();
if(searchIndex
当前JavaScript:

var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var infowindow = new google.maps.InfoWindow();

var promises = [];

function MyPromise() {
    return this;
};

MyPromise.prototype.promise = function () {
    var p = promises[this] || {
        then: []
    };

    promises[this] = p;

    return this;
};

MyPromise.prototype.then = function (func) {
    this.promise();

    promises[this].then.push(func);

    return this;
};

MyPromise.prototype.resolve = function () {
    this.promise();

    var then = promises[this].then;

    for (var promise in then) {
        then[promise].apply(this, arguments);
    }

    return this;
};

function initialize() {
    // Default the map view to the continental U.S.
    var mapOptions = {
        center: new google.maps.LatLng(40, -80.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 8
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    service = new google.maps.places.PlacesService(map);

    routeBoxer = new RouteBoxer();

    directionService = new google.maps.DirectionsService();
    directionsRenderer = new google.maps.DirectionsRenderer({
        map: map
    });
}

function route() {
    var dfd = new MyPromise().promise();

    // Clear any previous route boxes from the map
    clearBoxes();

    // Convert the distance to box around the route from miles to km
    distance = parseFloat(document.getElementById("distance").value) * 1.609344;

    var request = {
        origin: document.getElementById("from").value,
        destination: document.getElementById("to").value,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    }

    // Make the directions request
    directionService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(result);

            // Box around the overview path of the first route
            var path = result.routes[0].overview_path;
            var boxes = routeBoxer.box(path, distance);
            // alert(boxes.length);
            drawBoxes(boxes);
            // findPlaces(boxes,0);
            $.search(boxes, 0).then(function (p) {
                console.log("done", p);
            }).then(dfd.resolve);
        } else {
            alert("Directions query failed: " + status);
        }
    });

    // $.when(findPlaces()).done(function(){
    //  console.log("done");
    // });

    return dfd;
}

// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
    boxpolys = new Array(boxes.length);
    for (var i = 0; i < boxes.length; i++) {
        boxpolys[i] = new google.maps.Rectangle({
            bounds: boxes[i],
            fillOpacity: 0,
            strokeOpacity: 1.0,
            strokeColor: '#000000',
            strokeWeight: 1,
            map: map
        });
    }
}


$.search = function findPlaces(boxes, searchIndex) {
    var dfd = new MyPromise().promise();

    var request = {
        bounds: boxes[searchIndex],
        types: ["food"]
    };

    window.place_Results = [];

    service.radarSearch(request, function (results, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert("Request[" + searchIndex + "] failed: " + status);
            return;
        }

        document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"

        for (var i = 0, result; result = results[i]; i++) {
            var marker = createMarker(result);
            place_Results.push(result.reference);
        }

        searchIndex++;

        if (searchIndex < boxes.length) findPlaces(boxes, searchIndex);

        if (place_Results.length > 0) {
            dfd.resolve(place_Results);
        }
    });

    return dfd;
}

// Clear boxes currently on the map
function clearBoxes() {
    if (boxpolys != null) {
        for (var i = 0; i < boxpolys.length; i++) {
            boxpolys[i].setMap(null);
        }
    }
    boxpolys = null;
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    if (place.icon) {
        var image = new google.maps.MarkerImage(
        place.icon, new google.maps.Size(71, 71),
        new google.maps.Point(0, 0), new google.maps.Point(17, 34),
        new google.maps.Size(25, 25));
    } else var image = null;

    var marker = new google.maps.Marker({
        map: map,
        icon: image,
        position: place.geometry.location
    });
    var request = {
        reference: place.reference
    };
    google.maps.event.addListener(marker, 'click', function () {
        service.getDetails(request, function (place, status) {
            // console.log(place);
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
                if ( !! place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
                if ( !! place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
                contentStr += '<br>' + place.types + '</p>';
                infowindow.setContent(contentStr);
                infowindow.open(map, marker);
            } else {
                var contentStr = "<h5>No Result, status=" + status + "</h5>";
                infowindow.setContent(contentStr);
                infowindow.open(map, marker);
            }
        });

    });
    gmarkers.push(marker);
    var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
    document.getElementById('side_bar').innerHTML += side_bar_html;
}

initialize();

document.getElementById('route').onclick = route;
var-map=null;
var-boxpolys=null;
var方向=null;
var routeBoxer=null;
变量距离=null;//公里
var服务=null;
var gmarkers=[];
var infowindow=new google.maps.infowindow();
var承诺=[];
函数MyPromise(){
归还这个;
};
MyPromise.prototype.promise=函数(){
var p=承诺[这]| |{
然后:[]
};
许诺[这个]=p;
归还这个;
};
MyPromise.prototype.then=函数(func){
这是我的承诺;
承诺[this].then.push(func);
归还这个;
};
MyPromise.prototype.resolve=函数(){
这是我的承诺;
var-then=promises[this];
for(当时的var承诺){
然后[承诺]。应用(这个,论点);
}
归还这个;
};
函数初始化(){
//默认地图视图为美国大陆。
变量映射选项={
中心:新google.maps.LatLng(40,-80.5),
mapTypeId:google.maps.mapTypeId.ROADMAP,
缩放:8
};
map=new google.maps.map(document.getElementById(“map”)、mapOptions);
服务=新的google.maps.places.PlacesService(地图);
routeBoxer=新的routeBoxer();
directionService=new google.maps.directionService();
directionsRenderer=新建google.maps.directionsRenderer({
地图:地图
});
}
函数路径(){
var dfd=新的MyPromise().promise();
//从地图中清除所有以前的路线框
ClearBox();
//将路线周围的距离从英里转换为公里
距离=parseFloat(document.getElementById(“距离”).value)*1.609344;
var请求={
来源:document.getElementById(“from”).value,
目标:document.getElementById(“to”).value,
travelMode:google.maps.Directions travelMode.DRIVING
}
//提出指示要求
路由(请求、功能(结果、状态){
if(status==google.maps.directionstatus.OK){
directionsRenderer.setDirections(结果);
//第一条路线的概览路径周围的框
var path=result.routes[0]。概述\u路径;
变量框=路由框(路径、距离);
//警报(框。长度);
抽屉(盒);;
//findPlaces(框,0);
$.search(框,0)。然后(函数(p){
console.log(“完成”,p);
}).然后(dfd.解决);
}否则{
警报(“方向查询失败:+状态”);
}
});
//$.when(findPlaces()).done(function()函数){
//控制台日志(“完成”);
// });
返回dfd;
}
//将长方体阵列绘制为地图上的多段线
功能抽丝盒(盒){
boxpolys=新数组(box.length);
对于(变量i=0;i”
for(变量i=0,结果;结果=结果[i];i++){
var marker=createMarker(结果);
放置_Results.push(result.reference);
}
searchIndex++;
if(searchIndex0){
dfd.解决(放置结果);
}
});
返回dfd;
}
//清除地图上当前的方框
函数clearboxs(){
if(boxpolys!=null){
对于(var i=0;i$.search = function(boxes) {

    function findNextPlaces(place_results, searchIndex) {
        var dfd = $.Deferred();
        if (searchIndex < boxes.length) {
            service.radarSearch({
                bounds: boxes[searchIndex],
                types: ["food"]
            }, function (results, status) {
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    return dfd.reject("Request["+searchIndex+"] failed: "+status);
                }
                console.log( "bounds["+searchIndex+"] returns "+results.length+" results" );
                for (var i = 0, result; result = results[i]; i++) {
                    var marker = createMarker(result);
                    place_results.push(result.reference); // marker?
                }
                dfd.resolve(place_results, searchIndex+1);
            });
            return dfd.then(findNextPlaces);
        } else {
            return dfd.resolve(place_results).promise();
        }
    }

    return findNextPlaces([], 0);
};
$.search(boxes,0).then(function(results) {
    console.log("done", results);
}, function(err) {
    alert(err);
});
obj.method(param1, param2, ... paramN, callbackFn);
$.Deferred(function(dfd) {
    obj.method(param1, param2, ... paramN, dfd.resolve);
}).promise();
$.search = function(boxes, types) {

    function findPlaces(box) {
        var request = {
           bounds: box,
           types: types
        };

        //***********************
        // Here's the promisifier
        //***********************
        return $.Deferred(function(dfd) {
            service.radarSearch(request, dfd.resolve);
        }).promise();
        //***********************
        //***********************
        //***********************
    }

    function handleResults(results, status, searchIndex) {
        var message, marker;
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            message = "bounds[" + searchIndex + "] failed : " + status;
        }
        else {
            message = "bounds[" + searchIndex + "] returns " + results.length + " results";
            for (var i = 0, result; result = results[i]; i++) {
                marker = createMarker(result);
                place_Results.push(result.reference);
            }
        }
        return message;
    }

    var place_Results = [],
        p = $.when();//resolved starter promise

    //This concise master routine comprises a loop to build a `.then()` chain.
    $.each(boxes, function(i, box) {
        p = p.then(function() {
            return findPlaces(box).done(function(results, status) {
                // This function's arguments are the same as the original callback's arguments.
                var message = handleResults(results, status, i);
                $('#side_bar').append($("<div/>").append(message));
            });
        });
    });

    //Now, chain a final `.then()` in order to make the private var `place_Results` available via the returned promise. For good measure, the `types` array is also repeated back.
    return p.then(function() {
        return {
            types: types,
            results: place_Results
        };
    });
};
$.search(boxes, ["food"]).done(function(obj) {
    alert(obj.results.length + ' markers were a added for: "' + obj.types.join() + '"');
});