从纬度和经度获取地址

时间:2013-07-07 00:26:10

标签: android location latitude-longitude

我试图从纬度和经度中获取用户的地址,如下所示:

LocationManager locationManager = (LocationManager)  
this.getSystemService(Context.LOCATION_SERVICE);
    // Define a listener that responds to location updates
    final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            lat =location.getLatitude();
            lon = location.getLongitude();


        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };




    try{
        Geocoder geocoder;

        geocoder = new Geocoder(this, Locale.getDefault());
        addresses=(geocoder.getFromLocation(lat, lon, 1));

    }catch(IOException e){
        e.printStackTrace();
    }

    String address = addresses.get(0).getAddressLine(0);
    String city = addresses.get(0).getAddressLine(1);
    String country = addresses.get(0).getAddressLine(2);


    TextView tv = (TextView) findViewById(R.id.tv3);
    tv.setText(address+"\n"+city+"\n"+country);

// Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

每次运行此操作时,我都会在“String address = addresses.get(0).getAddressLine(0);”行中收到错误“IndexOutOfBoundsException:索引0无效,大小为0”。我理解错误意味着我试图访问不存在的东西,但我不确定是什么导致了这一点。我一直在寻找找到地址的最佳方法,这就是我找到的,但它可能不是最有效或最好的方式。有什么建议?

2 个答案:

答案 0 :(得分:3)

Lat和lon仅在onLocationchanged中设置为各自的值,在地理编码后触发,尝试先设置lat和lon,或者将地理编码放在onLocationChanged中。我看不到所有代码,但我猜你正在将lat和lon初始化为0,而地理编码器没有0,0的地址

答案 1 :(得分:2)

根据Android文档

  

用于处理地理编码和反向地理编码的类。地理编码是将街道地址或位置的其他描述转换为(纬度,经度)坐标的过程。反向地理编码是将(纬度,经度)坐标转换为(部分)地址的过程。反向地理编码位置描述中的详细信息量可能会有所不同,例如,一个可能包含最近建筑物的完整街道地址,而另一个可能只包含城市名称和邮政编码。 Geocoder类需要一个未包含在核心android框架中的后端服务。如果平台中没有后端服务,则Geocoder查询方法将返回空列表。使用isPresent()方法确定是否存在Geocoder实现。

您没有在代码中测试Geocoder.isPresent()。很可能它只是没有在您的设备上实现,只是返回一个空列表。我从来没有使用过Geocoder,但我可以想象即使它存在,也可以返回一个空列表,比如说你在海洋中间指定了一个位置。在访问其内容之前,您应该始终测试列表的大小:

TextView tv = (TextView) findViewById(R.id.tv3);

if (addresses.size() > 0) {
    String address = addresses.get(0).getAddressLine(0);
    String city = addresses.get(0).getAddressLine(1);
    String country = addresses.get(0).getAddressLine(2);
    tv.setText(address+"\n"+city+"\n"+country);
} else {
    tv.setText("Oops...");
}