Reputation: 109
Here I downloaded data of places from a server via script, now I want to sort the list of Place
in ascending order of distance using Pythagore
private class chargeur extends AsyncTask<Void, Void, List<Place>> {
@Override
protected List<Place> doInBackground(Void... voids) {
List<Place> pl = new ArrayList<>();
URL adresse = null;
try {
HttpsURLConnection cnx = Connecteur.connecter("get_all_places.php");
BufferedReader B = new BufferedReader(new InputStreamReader(cnx.getInputStream()));
String reponse = "";
String lign = "";
while ((lign = B.readLine())!=null) {
reponse+= lign;
}
JSONArray tab = new JSONArray(reponse);
for (int i = 0; i<tab.length();i++) {
JSONObject obj = tab.getJSONObject(i);
String name = obj.getString("name");
String longitude = obj.getString("longitude");
String latitude = obj.getString("latitude");
Place p = new Place(name, longitude ,latitude);
pl.add(p);
}
return pl;
} catch (Exception e) {}
}
// ...
}
Upvotes: 2
Views: 246
Reputation: 164069
You can use hypot()
which returns the distance of 2 points from java.lang.Math
class:
Collections.sort(pl, new Comparator<Place>() {
public int compare(Place pl1, Place pl2) {
Double d1 = Math.hypot(Double.parseDouble(p1.getLongitude()), Double.parseDouble(p1.getLatitude()));
Double d2 = Math.hypot(Double.parseDouble(p2.getLongitude()), Double.parseDouble(p2.getLatitude()));
return d1.compareTo(d2);
}
});
Upvotes: 0
Reputation: 1680
You could make it like
Collections.sort(pl, new Comparator<Place>() {
public int compare(Place pl1, Place pl2) {
// Write your logic here.
return Math.sqrt(pl1.longitude * pl1.longitude + pl1.latitude * pl1.latitude) <
Math.sqrt(pl2.longitude * pl2.longitude + pl2.latitude * pl2.latitude);
}});
Upvotes: 1