2014-03-25 53 views
1

我有兩組lat和lng。如何從lat和lng獲取地址?

我想這兩個地址,並存儲在一些變量:

var geocoder = new google.maps.Geocoder(); 
     for(var i=0; i<json_devices.length; i++) 
     { 
      var lat = json_devices[i].latitude; 
      var lng = json_devices[i].longitude; 
      console.log(lat); 
      console.log(lng); 
      var latlng = new google.maps.LatLng(lat,lng); 
      geocoder.geocode({'latLng': latlng}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[1]) { 
       address=results[1].formatted_address; 
        } else { 
        alert('No results found'); 
        } 
       } else { 
        alert('Geocoder failed due to: ' + status); 
       } 
      }); 
      console.log(address); 
     } 

在這方面,LAT & LAN得到正確。但地址不存儲在變量中。什麼是錯誤?

+0

您可以創建的jsfiddle? –

+0

@VinceLowe這裏是[jsfiddle](http://jsfiddle.net/2Vz6m/28/)粗略的數據,其中OP的問題被複制。 – Praveen

回答

1

我正在使用這種方法,它對我來說非常適合。 請看看它。

public String getAddressFromLatLong(GeoPoint point) { 
     String address = "Address Not Found"; 
     Geocoder geoCoder = new Geocoder(
       getBaseContext(), Locale.getDefault()); 
     try { 
      List<Address> addresses = geoCoder.getFromLocation(
        point.getLatitudeE6()/1E6, 
        point.getLongitudeE6()/1E6, 1); 

      if (addresses.size() > 0) { 
          address =addresses.get(0).getAddressLine(0); 
       if(address.length()<=0) 
       address =addresses.get(0).getSubLocality(); 
       } 
     } 
     catch (Exception e) {     
      e.printStackTrace(); 
      } 
     return address; 
    } 
0

在這裏,谷歌的地理編碼是asynchonous類型的函數調用的。

DOCS

訪問地理編碼服務是異步的,因爲谷歌地圖 API需要外部服務器的呼叫。因此, 需要傳遞迴調方法,以在完成 請求時執行。這個回調方法處理結果。請注意, 地理編碼器可能會返回多個結果。

所以你不能得到這樣的地址,而是使用所謂的callback的常用方法。

在這裏我創建了一個示例代碼來解釋這個過程,它可以被你自己改變。

var geocoder; 

function codeLatLng(callback) { 
    geocoder = new google.maps.Geocoder(); 
    var input = document.getElementById("latlng").value; 
    var latlngStr = input.split(",", 2); 
    var lat = parseFloat(latlngStr[0]); 
    var lng = parseFloat(latlngStr[1]); 
    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder.geocode({ 
     'latLng': latlng 
    }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[1]) { 
       address = results[1].formatted_address; 
       callback(address); 
      } else { 
       alert("No results found"); 
      } 
     } else { 
      alert("Geocoder failed due to: " + status); 
     } 
    }); 
} 

$('input[type="button"]').on('click', function() { 
    codeLatLng(function (address) { //function call with a callback 
     console.log(address); // THE ADDRESS WILL BE OBTAINED 
    }) 
}); 

JSFIDDLE

相關問題