gpt4 book ai didi

android - 从纬度和经度获取地址

转载 作者:太空狗 更新时间:2023-10-29 16:41:16 25 4
gpt4 key购买 nike

我正在尝试通过这样的经纬度获取用户的地址:

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”。我了解该错误意味着我正在尝试访问不存在的内容,但我不确定是什么原因造成的。我一直在寻找获取地址的最佳方式,这是我找到的,但它可能不是最有效或最好的方式。有什么建议么?

最佳答案

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

关于android - 从纬度和经度获取地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17508266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com