简体   繁体   中英

ArrayList<LatLng> compare to another one LatLng for distance calculation and store the result in ArrayList

Now I have multiple LatLng values stored inside ArrayList<LatLng> locations = new ArrayList<>(); and one LatLng TGlatlng value. I want to loop through Array and get each value of Array and compare to one LatLng TGlatlng to calculate distance. After that store the result in the ArrayList<Double> distance = new ArrayList<>() .

for(LatLng location : locations){
     int Radius = 6371;// radius of earth in Km
     double lat1 = location.latitude;
     double lat2 = TGlatlng.latitude;
     double lon1 = location.longitude;
     double lon2 = TGlatlng.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;
     ArrayList<Double> distance = new ArrayList<>();
     distance.add(km); 
}

This is what I have done so far and I'm stuck, I don't get any value inside ArrayList distance , anyone have idea?

The 'haversine' formula looks to be correctly implemente, not sure why distance is created inside the for loop. can you take it out and try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM