(二)进阶练习____1、让你的App可定位——显示地理位置-Displaying the Location Address
负责人:walker02
原文链接:http://docs.eoeandroid.com/training/basics/location/geocoding.html
显示位置地址
随着上一节的学习,位置更新是以经纬度坐标的形式接收的。这种接收方式适用于计算距离和在地图上显示标志的,十进制数字对于用户来说并没有什么意思,如果你需要显示位置给用户,更好的是显示地址信息。
执行反向地理编码
反向地理编码是把处理经纬度坐标转换为人们可以读取的地址信息。这里使用的是Geocoder API。注意这套API背后以来的是网络服务。如果这个服务在设备里不可以使用,那么API会抛出服务不可使用的异常,或者返回一个空的地址列表。在android2.3里增加了一个可用的方法isPresent(),这个方法用于检测是否存在该服务。 下边的代码片段就是使用Geocoder API来实现反向地理解码。因为double, int) getFromLocation()方法是同步的,你不应该在UI线程哩调用,因此在下边代码里使用了AsyncTask。
private final LocationListener listener = new LocationListener() { public void onLocationChanged(Location location) { // Bypass reverse-geocoding if the Geocoder service is not available on the // device. The isPresent() convenient method is only available on Gingerbread or above. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent()) { // Since the geocoding API is synchronous and may take a while. You don't want to lock // up the UI thread. Invoking reverse geocoding in an AsyncTask. (new ReverseGeocodingTask(this)).execute(new Location[] {location}); } } ... }; // AsyncTask encapsulating the reverse-geocoding API. Since the geocoder API is blocked, // we do not want to invoke it from the UI thread. private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> { Context mContext; public ReverseGeocodingTask(Context context) { super(); mContext = context; } @Override protected Void doInBackground(Location... params) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); Location loc = params[0]; List<Address> addresses = null; try { // Call the synchronous getFromLocation() method by passing in the lat/long values. addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); } catch (IOException e) { e.printStackTrace(); // Update UI field with the exception. Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget(); } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); // Format the first line of address (if available), city, and country name. String addressText = String.format("%s, %s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getLocality(), address.getCountryName()); // Update the UI via a message handler. Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget(); } return null; } }

浙公网安备 33010602011771号