Android中根據座標擷取地址,一般用Geocoder,大概像下面這樣:
try{ Geocoder geo = new Geocoder(NewCommentActivity.this, Locale.getDefault()); List<Address> addresses = geo.getFromLocation(23.0897174,113.3116872, 1); if (addresses.isEmpty()) { Log.i("location", "addressed is Empty"); } else { if (addresses.size() > 0) { Log.i("location", addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName()); } } }
當我使用這段代碼在真機上運行時,報錯:
java.io.IOException:Sevice not Available
at android.location.Geocoder.getFromLocation
Google了一下,都說是在模擬器上才有這個問題,真機不會有此問題。但我確確實實在真機上遇到了這個問題。
查看Android官方文檔,發現人家已經說的很明白了:
The Geocoder API is available for this purpose. Note that behind the scene, the API is dependent on a web service. If such service is unavailable on the device, the API will throw a "Service not Available exception" or return an empty list of addresses. A helper
method calledisPresent() was added in Android 2.3 (API level 9) to check for the existence of the service.
看來對於沒有這個服務的機型,確實是用不了這個方法的。那隻能另闢蹊徑了。在網上找到另外的方法:
訪問Google的這個URL可以獲得地址資訊的JSON字串。
String url = String.format("http://ditu.google.cn/maps/geo?output=json&key=abc&q=%s,%s", latitude, longitude);