Calculate the distance between cities and find nearby cities based on GeoPT, in Python in the Google App Engine

I have a city model defined that preserves geoname_idand location(like GeoPt) cities. There are two things that I want to achieve.

  • I want to get all the cities within the radius 500kmof this city.
  • I want to calculate the distance in kmbetween two given cities.

What would be the best way to achieve this, bearing in mind that I have a very large database of cities and I don’t want to sacrifice a lot of the performance factor. Any help or advice is appreciated.

+5
source share
3 answers

This works fine, but slower:

. , , Geopt():

def HaversineDistance(location1, location2):
  """Method to calculate Distance between two sets of Lat/Lon."""
  lat1, lon1 = location1
  lat2, lon2 = location2
  earth = 6371 #Earth Radius in Kms.

 #Calculate Distance based in Haversine Formula
 dlat = math.radians(lat2-lat1)
 dlon = math.radians(lon2-lon1)
 a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
 d = earth * c
 return d

. , :

def get_closest_cities(self, kms):
  cities = []
  #Find surrounding Cities of a given city within a given radius
  allcities = self.country.city_set
  for city in allcities:
    distance = HaversineDistance((self.location.lat, self.location.lon),(city.location.lat, city.location.lon))
    if not distance >= kms:
      cities.append((city.name, int(distance)))
  cities.remove(cities[0])
  return cities
+7
+3
+2
source

All Articles