2016-01-06 26 views
-1

我有一些緯度和經度我想知道他們的地址。在google map api中經緯度遞歸查找地址

function OnSuccess(response) { 
    showLatLng(0, JSON.parse(response.d).Table, JSON.parse(response.d).Table.length); 
} 

其中JSON.parse(response.d).Table包含結果集。

function showLatLng(index, resultSet, totalLen) { 
    var lat = resultSet[index].x; 
    var lng = resultSet[index].y; 

    var latlng = new google.maps.LatLng(lat, lng); 

    new google.maps.Geocoder().geocode({ 'latLng': latlng }, 
     function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[0]) { 

        var z = " <tr>" + 
         "<td>" + results[0].formatted_address + "</td>" + 
         "</tr>"; 

        $("#result").append(z); 

        if (index < totalLen) { 
         showLatLng(index + 1, resultSet, totalLen); 
        } 
       } 
      } 
     }); 
} 

此代碼僅工作4到5次,然後停止,並在螢火蟲沒有錯誤。 請給我一個更好的方式來做到這一點。編輯: 盧卡斯你是完全正確的。

以前我已經使用超時迴路如下

$.each(JSON.parse(response.d).Table, function (index, value) { 
     setTimeout(function() { 
      showLatLng(index , value.x, value.y); 
     }, (index + 1) * 7000); 
    }); 

但由於某些原因(因爲我認爲這是工作在異步調用),它跳過了一定的成效。

+1

這可能是因爲你的循環的地理編碼器,它具有油門操作謂過快防止幾乎正是你正在嘗試做的。雖然4或5次似乎不足以觸發這一點。你可以在你的遞歸中嘗試setTimeout,或者在你的'if(status == google.maps.GeocoderStatus.OK){'和console.log'google.maps.GeocoderStatus'處添加一個else。但實際上,如果你有一個已知的座標列表,最好的辦法是對它們進行一次地理編碼,並對數組中的地址進行硬編碼,而不是在每次頁面加載時調用地理編碼器 – lucas

回答

0

通經緯度值腳本

function GetAddress() { 
     var lat = parseFloat(document.getElementById("txtLatitude").value); 
     var lng = parseFloat(document.getElementById("txtLongitude").value); 
     var latlng = new google.maps.LatLng(lat, lng); 
     var geocoder = geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'latLng': latlng }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[1]) { 
        alert("Location: " + results[1].formatted_address); 
       } 
      } 
     }); 
    } 
+0

如何爲20條記錄執行操作(遞歸地)在包含經度和緯度的對象中? – Sdei

+0

你可以寄給我你有的全部節目嗎? –