Android中如何通过Google Places Autocomplete API缩短地址显示
解决Android地址显示过长的问题
你当前使用Geocoder获取的getAddressLine(0)会返回完整地址串,导致内容冗余。要得到类似“Ganesh Nagar, Bharatpur”的精简格式,无需依赖完整地址行,直接提取Address类中的细分地址组件即可。
可行方案
1. 提取核心地址组件拼接
Address类提供了多个细分字段,按需组合就能得到目标格式:
getSubLocality():返回小区、街区级名称(如示例中的Ganesh Nagar)getLocality():返回城市/城镇名称(如示例中的Bharatpur)
2. 兼容空字段场景
部分地区可能没有subLocality数据,可使用getThoroughfare()(街道名称)作为备选,避免显示空值。
修改后的代码
Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } catch (Exception ioException) { Log.e("", "Error in getting address for the location"); } if (addresses == null || addresses.size() == 0) { msg = "No address found for the location"; sendResultsToReceiver(1, msg); } else { Address address = addresses.get(0); // 构建精简地址 StringBuilder simplifiedAddress = new StringBuilder(); // 添加子区域(小区/街区) String subLocality = address.getSubLocality(); if (subLocality != null && !subLocality.isEmpty()) { simplifiedAddress.append(subLocality); } // 添加城市 String locality = address.getLocality(); if (locality != null && !locality.isEmpty()) { if (simplifiedAddress.length() > 0) { simplifiedAddress.append(", "); } simplifiedAddress.append(locality); } // 处理所有字段为空的情况 if (simplifiedAddress.length() == 0) { msg = "No address found for the location"; sendResultsToReceiver(1, msg); } else { sendResultsToReceiver(2, simplifiedAddress.toString()); } }
补充说明
如果你的需求是直接使用Google Places Autocomplete API(而非当前的逆地理编码),可以在请求时通过types参数限制返回结果类型,比如指定types=locality,sublocality,让API直接返回更精简的地址选项,减少后续处理成本。
内容的提问来源于stack exchange,提问作者Puru Chaudhary
相关产品推荐
相关产品推荐

