我正在测试一个应用程序,它借助三星平板电脑中的 GPS 获取纬度和经度。我能够从 GPS 单元捕获当前的纬度、经度。现在我想使用经纬度从这些位置获取地址,而不使用互联网,即 wi-fi、移动数据。
我正在按照以下方式进行操作:
public String getAddress(Context ctx, double latitude, double longitude) {
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
String locality=address.getLocality();
String city=address.getCountryName();
String region_code=address.getCountryCode();
String zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
result.append(locality+" ");
result.append(city+" "+ region_code+" ");
result.append(zipcode);
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return result.toString();
}
private class GetCurrentAddress extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// this lat and log we can get from current location but here we given hard coded
double latitude=12.916523125961666;
double longitude=77.61959824603072;
String address= getAddress(context, latitude, longitude);
return address;
}
@Override
protected void onPostExecute(String resultString) {
dialog.dismiss();
result.setText(resultString);
}
}
在 mainfest 我做以下条目:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />