简体   繁体   English

使用.getJSON for Google Maps API制作自定义航点

[英]Making custom waypoints by using a .getJSON for google maps api

I am trying to have a function for calculating routes for google maps be dynamically changed based on data retrieved from a .getJSON. 我试图有一个功能,用于基于从.getJSON检索的数据来动态更改Google地图的路线。 I have tried including the bulk of the function calcRoute() under a .done function, but I am receiving an error in property waypoints in the javascript console. 我尝试在.done函数下包含大部分calcRoute()函数,但是在JavaScript控制台中,属性航点出现错误。 I am at a loss as what to do, because when I don't include the bulk of the function under the .done, the array remains blank (asynchronous call with the .getJSON. Here is the code to give you a better idea: 我无所适从,因为当我在.done下不包含函数的大部分时,该数组将保持空白(与.getJSON的异步调用。以下代码为您提供了一个更好的主意:

    function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var waypts = [];
        var data = $.getJSON("/westcoast_map.php", {
            westcoast_id: $('.opener').data('westcoast_id')
        }, function(json) {
            return json[1];
        });

        data.done(function(theData) {
            waypts = theData[1];
            console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...

            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById('directions_panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for (var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }
                }
            });

        });
    }

i'm still not sure what you problem is, because the code pared you show, should at least work from the logical part. 我仍然不确定您的问题是什么,因为您显示的代码经过解析,至少应该在逻辑部分起作用。 but there are parts where it is not clear what you try to achive: 但有些地方您不清楚要达到的目标:

    var data = $.getJSON("/westcoast_map.php", {
        westcoast_id: $('.opener').data('westcoast_id')
    }, function(json) {
        return json[1];
    });

if you expect here that data will become json[1] , then your assumption is wrong. 如果您在这里期望data将变为json[1] ,那么您的假设是错误的。 $.getJSON returns always jQuery XHR . $.getJSON始终返回jQuery XHR the callback function will be called later when the browser received the data. 当浏览器收到数据时,回调函数将在以后被调用。

Here a little example to understand how async works: the callback functions 1 and 2 are called when the client gets the response for the request, but not before the original script was completely executed, so doSomethingElse() will be always called before the callback function 1 and 2 are executed. 这是一个了解异步工作原理的小示例:客户端获取请求的响应时(而不是在原始脚本完全执行之前)调用回调函数1和2,因此doSomethingElse()将始终在回调函数之前调用执行1和2。 the order in which callback function 1 and 2 are executed depends on which response arrives first. 执行回调函数1和2的顺序取决于哪个响应首先到达。

var test = [];
preparesSomeStuff();

$.getJSON("someurl1",{},function() {
   //Callback Function 1

});

doSomething();

$.getJSON("someurl2",{},function() {
   //Callback Function 2
});


doSomethingElse();
//<<END OF SCRIPT>>

if you don't want to have your whole code inside of the callback function (eg because of readability) you could do it the following way: 如果您不希望将整个代码包含在回调函数中(例如,由于可读性),则可以通过以下方式实现:

function calcRoute() {
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    var waypts = [];
    $.getJSON("/westcoast_map.php", {
        westcoast_id: $('.opener').data('westcoast_id')
    }, function(theData) {
        calcualteRoute(theData[1], start, end);
    });

    //if you place code here it will be executed before displayResult will be called because getJSON is async
}


function calcualteRoute(waypts, start, end) {
    console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...

    var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            displayResult(response,status);
        }
    });

    //if you place some code here it will be executed BEFORE displayResult will be called, because 
    //directionsService.route is async

}

function displayResult(response, status) {
    directionsDisplay.setDirections(response);
    var route = response.routes[0];
    var summaryPanel = document.getElementById('directions_panel');
    summaryPanel.innerHTML = '';
    // For each route, display summary information.
    for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i + 1;
        summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM