在我的应用程序中,我必须找出给定位置是否位于指定区域之下。我以新德里的康诺特广场为中心点。我得到了距离中心点 200 英里范围内的地址。但是,如果我输入任何无效位置,例如“abcdfdfkc”,应用程序就会崩溃,因为它正在尝试查找该位置的坐标,而我想避免这种情况。
下面我发布代码:
public static boolean isServicedLocation(Context _ctx, String strAddress){
boolean isServicedLocation = false;
Address sourceAddress = getAddress(_ctx, "Connaught Place, New Delhi, India");
Location sourceLocation = new Location("");
sourceLocation.setLatitude(sourceAddress.getLatitude());
sourceLocation.setLongitude(sourceAddress.getLongitude());
Address targetAddress = getAddress(_ctx, strAddress);
Location targetLocation = new Location("");
if (targetLocation != null) {
targetLocation.setLatitude(targetAddress.getLatitude());
targetLocation.setLongitude(targetAddress.getLongitude());
float distance = Math.abs(sourceLocation.distanceTo(targetLocation));
double distanceMiles = distance/1609.34;
isServicedLocation = distanceMiles <= 200;
//Toast.makeText(_ctx, "Distance "+distanceMiles, Toast.LENGTH_LONG).show();
}
return isServicedLocation;
}
获取地址方法:
public static Address getAddress(Context _ctx, String addressStr) {
Geocoder geoCoder = new Geocoder(_ctx, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr,
1);
if (addresses.size() != 0) {
return addresses.get(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}