2012-04-19 28 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(); 
}