2016-01-14 54 views
2

我遵循這個問題(How can I find the latitude and longitude from address?)並嘗試獲取地址的經度和緯度。我將這種方法稱爲「GeoPoint point = getLocationFromAddress(」colombo,sri lanka「);」 。但給零值。如何正確調用方法?當從地址找到經緯度時,如何給出地址?

public GeoPoint getLocationFromAddress(String strAddress){ 

Geocoder coder = new Geocoder(this); 
List<Address> address; 
GeoPoint p1 = null; 

try { 
address = coder.getFromLocationName(strAddress,5); 
if (address==null) { 
    return null; 
} 
Address location=address.get(0); 
location.getLatitude(); 
location.getLongitude(); 

p1 = new GeoPoint((int) (location.getLatitude() * 1E6), 
        (int) (location.getLongitude() * 1E6)); 

return p1; 
} 
} 
+0

從API文檔,「該結果是最好的猜測,並不保證是有意義的或正確的。「 –

回答

1

試試下面的代碼

Geocoder gcd = new Geocoder(ReserveTimer.this, Locale.getDefault()); 
    List<Address> addresses = gcd.getFromLocation(Double.parseDouble(lati), Double.parseDouble(longi), 1); 

           if (addresses.size() > 0) { 
            System.out.println(addresses.get(0).getLocality()); 
            System.out.println(addresses.get(0).getCountryName()); 
System.out.println(addresses.get(0).getAddressLine(0)); 


System.out.println(addresses.get(0).getAdminArea()); 
System.out.println(addresses.get(0).getCountryName()); 
System.out.println(addresses.get(0).getPostalCode()); 

           } 
1

您可以用下面的方法是服用含有latitud Location對象和longitud座標和日誌位置到logcat的控制檯:

public void setLocation(Location loc) { 
    //Get Human readable address from latitud and longitud coordinates 
    if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) { 
    try { 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     List<Address> list = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); 
     if (!list.isEmpty()) { 
    Address address = list.get(0); 
    Log.d(CLASS_TAG, "Mi direcci—n es: \n" + address.getAddressLine(0)); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
}