简体   繁体   English

在For Loop中的Google Maps调用未返回距离

[英]google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances. 我在JavaScript中的for循环内调用了Google地图,因为我有多条路线,需要根据距离分别计算。

Everything works great except that the distance is only returned for one of the routes. 一切都很好,除了只返回其中一条路线的距离。

I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. 我感觉这与我在地图的ajax调用中声明的项的方式有关。 Any ideas what could be the issue from the code below? 有什么想法可能是下面的代码的问题吗?

for (var i = 1; i <= numJourneys; i++) {
                var mapContainer = 'directionsMap' + i;
                var directionContainer = $('#getDistance' + i);

                $.ajax({
                    async: false,
                    type: "POST",
                    url: "Journey/LoadWayPoints",
                    data: "{'args': '" + i + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        if (msg.d != '[]') {
                            var map = new GMap2(document.getElementById(mapContainer));
                            var distance = directionContainer;
                            var wp = new Array();

                            //routes
                            var counter = 0;
                            $.each(content, function () {
                                wp[counter] = new GLatLng(this['Lat'], this['Long']);
                                counter = counter + 1;
                            });

                            map.clearOverlays();
                            map.setCenter(wp[0], 14);

                            // load directions
                            directions = new GDirections(map);
                            GEvent.addListener(directions, "load", function () {
                                alert(directions.getDistance());
                                //directionContainer.html(directions.getDistance().html);
                            });
                            directions.loadFromWaypoints(wp, { getSteps: true });
                        }
                    }
                });
            }

The issue was down to a non declared variable. 问题归结于一个未声明的变量。 Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out. 就在GEvent调用之前,有一个名为“ directions”的变量,但实际上从未使用var进行声明,因此并未将其清除。

var directions = new GDirections(map);

Doing the above worked for me. 进行上述操作对我有用。

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

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