我正在开发一个接收给定地址的Android应用程序。我只想让该应用程序在设备上运行(如果用户位于该地址或更接近该地址)。
那可能只与谷歌地图API吗?
您可以获取地址,并从该地址获取经度和纬度:
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
}
然后将其与您的位置进行比较:
if (distance(mylocation.latitude, mylocation.longitude, location.getLatitude(), location.getLongitude()) < 0.1) { // if distance < 0.1
// launch the activity
}else {
finish();
}
/** calculates the distance between two locations in MILES */
private double distance(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75; // in miles, change to 6371 for kilometers
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return dist;
}
编辑:正如@FelipeMosso所说,您还可以使用distanceBetween计算两个位置之间的近似距离(以米为单位),或者使用distanceTo给出您在目的地和目的地之间的距离。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句