2016-01-14 42 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(); 
    } 
    } 
}