Мой скрипт не успевает за API (Google Maps)
Всем добрый день.
Надо сделать скрипт, который бы выдавал общее расстояние по нескольким адресам. Вот мой скрипт (для удобства отладки я разбил его на отдельные функции): <script type="text/javascript"> var geocoder, location1, location2, gDir, locationTo; var addressTo = []; //Обработчик кнопки для добавления еще одного поля для адреса function addLocation() { var div = document.getElementById("addLocations"); div.innerHTML += "<input type=\"text\" name=\"Address\" value=\"Москва\" />"; } function initialize() { // debugger geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)'; }); } function showLocation() { var addressFrom; var count = document.getElementsByName("Address").length; addressFrom = document.getElementsByName("Address")[0].value; for (var i=1; i<count; i++) { addressTo.push(document.getElementsByName("Address")[i].value); } geocoder.getLocations(addressFrom, getLocationFrom); } function getLocationFrom(response) { debugger if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(addressTo[0], getLResponse); } } function getLResponse(response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; locationTo = location2.address; if (addressTo.length > 1) { for (var i = 1; i < addressTo.length; i++) { geocoder.getLocations(addressTo[i], getAddLocation); } } //!!!!!!!!Метод ниже срабатывает быстрее, чем я пробегаю по всем адресам. gDir.load('from: ' + location1.address + ' to: ' + locationTo); form1.submit(); } } function getAddLocation(response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; locationTo += 'to:' + location2.address; } } </script> <body onload="initialize()" onunload="GUnload()"> <form action="#" id="form1" method="get"> <input type="text" name="Address" value="Москва" /> <input type="text" name="Address" value="Рязань" /> <div id="addLocations"> </div> <input type="button" value="Добавить адрес" onclick="addLocation();" /> <input type="button" value="Расчитать" onclick="showLocation();" /> </form> <p id="results"> </p> </body> В коде я пометил метод, с которым у меня трудности. Иными словами надо чтобы gDir.load('from: ' + location1.address + ' to: ' + locationTo); вызывался после того как я обработаю все адреса. А он вызывается когда у меня только 1 адрес. Я не очень силен в js, может кто-нибудь подсказать, что мне надо сделать, чтобы метод подождал пока обработаются все адреса в цикле, где вызывается функция getAddLocation, а потом уже вызывался метод gDir.load? |
Часовой пояс GMT +3, время: 23:35. |