Get the Nearest Location (out of list) from another location

Discussion in 'Spigot Plugin Development' started by GermanHubertus, Jun 21, 2015.

  1. Hi,
    I want to get the Nearest Location from another Location.
    Something like this:
    Code (Text):
    Location playerloc = player.getLocation();
    List<Location> locs =  (Location) plugin.getConfig().getList("Something.Something");

    //Something like this?:
    Location nearestloc = playerloc.getNearest(locs);
    Do you know how this works?
    Thx,
    GermanHubertus
     
  2. What you do is you have one location variable that will be the nearest location and set that variable to the first location in the list. Then you use a for loop to go through every location in the list of locations, and you check if the distance of the location in the list and the playerLoc is smaller than the location saved in the variable and the playerLoc. if this is true than you set the location that is saved in the variable outside the for loop to the location that you just checked that is closer to the player. When the for loop is completed you have the nearest location.
     
  3. Can you please give me an Example on how to do this? I have no Idea how I could implement this.

    Thanks!,
    GermanHubertus
     
  4. Here's some pseudocode for you. You should be able to figure it out from this.
    Code (Text):
    for location in locations
        compare location to playerlocation
        if distance < distance from previous location
            closestLocation = location
        end
    end
     
    • Useful Useful x 1
  5. playerloc.distance(closestLocation), nuff' said.
     
  6. Wasn't aware of that method's existence, thanks!
     
  7. It'll be much more efficient to use distanceSquared, no other changes required.
     
    • Agree Agree x 1
  8. Sorry for late answer!
    Thanks for the solutions, got it now like this and its working :)
    Code (Text):
        public static Location getNearest(List<Location> zombiewarps,
                Location compareLoc) {

            int i = 1;

            zombiewarps.add(compareLoc);
            Location nearestLoc = zombiewarps.get(0);
            for (Location l : zombiewarps) {
                if (i != zombiewarps.size()) {
                    if (compareLoc.distance(l) < compareLoc.distance(nearestLoc)) {
                        nearestLoc = l;
                    }
                    i++;
                }

            }
            return nearestLoc;

        }
     
  9. Why do you use the i variable? In for each methods the use of that isn't necesary as it will loop for all the variables from your list and then continue