diff --git a/src/fellchensammlung/models.py b/src/fellchensammlung/models.py index a3089a1..c619b11 100644 --- a/src/fellchensammlung/models.py +++ b/src/fellchensammlung/models.py @@ -10,7 +10,7 @@ from django.db.models.signals import post_save from django.contrib.auth.models import Group from django.contrib.auth.models import AbstractUser -from fellchensammlung.tools import misc +from fellchensammlung.tools import misc, geo from notfellchen.settings import MEDIA_URL @@ -71,6 +71,26 @@ class Location(models.Model): longitude = models.FloatField() name = models.CharField(max_length=2000) + def __str__(self): + return f"{self.name} ({self.latitude:.5}, {self.longitude:.5})" + + @staticmethod + def get_location_from_string(location_string): + geo_api = geo.GeoAPI() + get_geojson = geo_api.get_geojson_for_query(location_string) + result = get_geojson[0] + if "name" in result: + name = result["name"] + else: + name = result["display_name"] + location = Location.objects.create( + place_id=result["place_id"], + latitude=result["lat"], + longitude=result["lon"], + name=name, + ) + return location + class RescueOrganization(models.Model): def __str__(self): diff --git a/src/fellchensammlung/tools/geo.py b/src/fellchensammlung/tools/geo.py index d7ffc8f..7bf03ad 100644 --- a/src/fellchensammlung/tools/geo.py +++ b/src/fellchensammlung/tools/geo.py @@ -3,7 +3,6 @@ import logging import requests import json from notfellchen import __version__ as nf_version -from fellchensammlung.models import Location from notfellchen import settings from math import radians, sqrt, sin, cos, atan2 @@ -69,7 +68,7 @@ class GeoAPI: result = self.requests.get(self.api_url, {"q": location_string, "format": "jsonv2"}, headers=self.headers) return result.content - def get_location_from_string(self, location_string): + def get_geojson_for_query(self, location_string): try: result = self.requests.get(self.api_url, {"q": location_string, @@ -81,19 +80,7 @@ class GeoAPI: if len(result) == 0: logging.warning(f"Couldn't find a result for {location_string} when querying Nominatim") return None - - result = result[0] - if "name" in result: - name = result["name"] - else: - name = result["display_name"] - location = Location.objects.create( - place_id=result["place_id"], - latitude=result["lat"], - longitude=result["lon"], - name=name, - ) - return location + return result if __name__ == "__main__":