大家好我正在开发一个Android应用程序,而移动那里的设备是一个保存的位置(latlng对象)在数组中,我希望它提醒用户离他的设备最近的地方,但它可能是最靠近下摆的地方下摆前面,如下图所示: ng2-admin
这是位置列表
List<LatLng> cameraLocation = new ArrayList<>();
这里我如何计算距离
for (LatLng location : cameraLocation) {
closestCamera = location;
smallestDistance = distance;
Log.e("distanceTest", distance + "");
Log.d("closestCamera" , location+"" );
distanceList.add(CalculationByDistance(myLocation, location));
distance = Collections.min(distanceList);
}
CalculationByDistance函数就像这样
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("#");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
任何帮助请...
答案 0 :(得分:0)
您的班级可以有两个Location
个实例,第一个currentLocation
和第二个lastLocation
。计算place
与currentLocation
和lastLocation
之间的距离。 currentLocation
与place
greater
之间的距离是lastLocation
与place
之间的距离,而不是place
之间的距离private Location currentLocation;
private Location lastLocation;
public void onLocationUpdate(Location location){
lastLocation = currentLocation;
currentLocation = location;
calculateDistance();
}
private double smallestDistance;
private LatLng closestCamera;
private void calculateDistance(){
for (LatLng location : cameraLocation) {
double distanceFromLastLocation = CalculationByDistance(new LatLng(lastLocation.lat, lastLocation.lng), location);
double distanceFromCurrentLocation = CalculationByDistance(new LatLng(lastLocation.lat, lastLocation.lng), location);
if (distanceFromCurrentLocation < distanceFromLastLocation) {
continue; // User is going away from location i.e location is behind user. No need to calculate distance between user and cameraLocation.
}
distanceList.add(CalculationByDistance(myLocation, location));
if (Collections.min(distanceList) == distanceFromCurrentLocation) {
// this location is nearest amongst all the cameraLocations.
smallestDistance = distanceFromCurrentLocation;
closestCamera = location;
}
}
}
}。那个地方在你当前的位置后面。
示例代码:
{{1}}