-2

I was wondering how I could get the nearest location from given float values.

I have an ArrayList of Cities which have lat/long. What I would like to do is to find the nearest city from given coordinates.

public class City {
       private float lat;
       private float lng;
       //getters & setters
   }

   List < City > cities; // at this point "cities" contains several "city"
   City city;



   city = findNearest(lat, lng);
   private City findNearest(float lat, float lng) {
       for (City c: cities) {}
   }
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Helvin
  • 53
  • 2
  • 9
  • just calculate the differnce between point X and point Y with [math](https://www.mathsisfun.com/algebra/distance-2-points.html) and store the smallest one in a variable. – SomeJavaGuy Aug 09 '16 at 14:33
  • Use a variable to keep track of which one you think is closest and update it as you go through the loop. For each city, find the distance. If it is closer than the one that you previously thought was closest, assign it to the variable. Also, don't post fragments of code that don't make any sense. – khelwood Aug 09 '16 at 14:36
  • What's your approach? Finding the distance between 2 geo coordinates is a little trickier than @KevinEsche mentioned, but the simple distance is a good start. – f1sh Aug 09 '16 at 14:38
  • on top of what @khelwood said, take a look at this http://stackoverflow.com/questions/929773/calculating-the-distance-between-two-points (just in case) – Olian04 Aug 09 '16 at 14:40
  • I guess I am terrible in maths because I don't seem to get it well – Helvin Aug 09 '16 at 14:46
  • My problem is because there are a combination of two values to determinate which City is the nearest that's what I can't still understand – Helvin Aug 09 '16 at 14:50
  • Did you try your favourite search engine? I found http://andrew.hedges.name/experiments/haversine/ among others. – Ole V.V. Aug 09 '16 at 14:54

1 Answers1

4

Try to calculate simple deviation:

  private City findNearest(float lat, float lng) {
       float minDist = Float.MAX_VALUE;
       City resCity = null;
       for (City c: cities) {
          float dist = Math.pow(c.getLat() - lat, 2) + Math.pow(c.getLng() - lng, 2);
          if (dist < minDist){
            minDist = dist;
            resCity = c;
          }
       }
     return resCity;
   }

you could take Math.sqrt from dist, but actually there is no sense.

shure
  • 361
  • 3
  • 7