2012-04-19 31 views
1

我有這樣的方法來顯示在地圖上活動的用戶的緯度和經度:使用地理編碼器來顯示用戶的位置地址

public void animateMap(Location location){ 
     double lat = location.getLatitude(); 
     double lng = location.getLongitude(); 

     Toast.makeText(MyMapActivity.this, 
       "Sie sind an\n" + lat + "\n" + lng, Toast.LENGTH_SHORT) 
       .show(); 
     GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); 
     mapController.animateTo(point, new Message()); 
     mapOverlay.setPointToDraw(point); 

    } 

如何實現我的方法的地理編碼?所以吐司將顯示該位置的地址,而不是座標

回答

1

您使用

Geocoder myLocation = new Geocoder(context, Locale.ENGLISH); 
List<Address> myList= myLocation.getFromLocation(lat, lng, 1); 
Address add = myList.get(0); 
String addressString = add.getAddressLine(0); 
String country = add.getCountryName();      
String city = add.getLocality(); 
+0

GeoCoder無法從給定位置找到位置時會發生錯誤。並且應用程序將被迫關閉。 – 2012-07-19 05:27:03

1

最簡單的實現方式是通過利用地理編碼器類:

Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
     geocoder.getFromLocation(lat, lng, 1); 
     List<Address> ls=new ArrayList(); 
     ls= geocoder.getFromLocation(lat, lng, 1); 
     String myLocation = ls.get(0).getSubAdminArea(); 

您可以檢查這個類返回的所有信息,並選擇哪一個最適合你。它包含國家名稱,地標名稱,鄰居郵政編碼......幾乎任何你可能需要的。

但請記住,如果谷歌沒有關於這個位置的信息將返回一個空字符串!因此,對於你

exapmple應該是類似的東西:

public void animateMap(Location location){ 
    double lat = location.getLatitude(); 
    double lng = location.getLongitude(); 


String myLocation; 
try{ 
      Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
     geocoder.getFromLocation(lat, lng, 1); 
     List<Address> ls=new ArrayList(); 
     ls= geocoder.getFromLocation(lat, lng, 1); 
     myLocation = ls.get(0).getSubAdminArea(); 
}catch(Exception e){ 
    myLocation="Sorry, we have no information about this location"; 
} 



    Toast.makeText(MyMapActivity.this, 
      "Sie sind an\n" + myLocation , Toast.LENGTH_SHORT) 
      .show(); 
    GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); 
    mapController.animateTo(point, new Message()); 
    mapOverlay.setPointToDraw(point); 

} 
+0

太糟糕了,我的myLocation空了。任何解決方案 – hectichavana 2012-04-19 11:36:54

+0

subadminarea是一個非常詳細的信息,你可以嘗試管理等等等等,所以你可以有至少一些基本inoframtion這個位置! – 2012-04-19 11:39:45

0

從地理編碼您的位置獲取地址的列表,並檢查是否有null or empty result

Geocoder geocoder = new Geocoder(getApplicationContext,Locale.getDefault()); 
List<Address> address = geocoder.getFromLocation(lat, long, 1); 
String myLocation = ""; 
if(address != null && !address.isEmpty()) 
{ 
    myLocation = address.get(0).getSubAdminArea(); 
}