开发者

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.

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. 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 () {
                                aler开发者_开发知识库t(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.

var directions = new GDirections(map);

Doing the above worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜