您的代码看起来太复杂了,这里有更简单的方法:
String searchPattern = "123 Main St." LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //I use last known location, but here we can get real location Location lastKnownLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); List<Address> addresses = null; try { //trying to get all possible addresses by search pattern addresses = (new Geocoder(this)).getFromLocationName(searchPattern, Integer.MAX_VALUE); } catch (IOException e) { } if (addresses == null || lastKnownLocation == null) { // location service unavailable or incorrect address // so returns null return null; } Address closest = null; float closestDistance = Float.MAX_VALUE; // look for address, closest to our location for (Address adr : addresses) { if (closest == null) { closest = adr; } else { float[] result = new float[1]; Location.distanceBetween(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), adr.getLatitude(), adr.getLongitude(), result); float distance = result[0]; if (distance < closestDistance) { closest = adr; closestDistance = distance; } } } return closest; //here can be null if we did not find any addresses by search pattern.
getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude)
我尝试了Jin35的建议并增加了Geocoder.getFromLocationName()的max_results,但结果并不理想。首先,大的max_result,无限制的调用比我的模拟器上的5个结果,geocoord有界调用花了更长的时间(2.5x - 7x = 1 - 6秒)。也许现实世界会更快,这个因素变得不那么重要了。
杀手是无论max_results是50还是100, 的 每次只有20个结果回来 强> 。似乎Google正在限制服务器端的结果。最接近的“123 Main St”对我来说并不是那20个结果 - 从加利福尼亚州的Mt View测试,并被归还加利福尼亚州奥克利。
除非Geocoder.getFromLocationName()之外的其他方法用于进行地址查找,或者使用边界坐标更好的方法,我将接受我自己的原始答案。