File size: 2,193 Bytes
2542be6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import locationtagger
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut, GeocoderUnavailable
from models.location_models import LocationData, Coordinates, ErrorResponse

class LocationService:
    @staticmethod
    def get_coordinates(data:dict) -> Coordinates | ErrorResponse:
        print("Inside get coordinates")
        print(data)
        try:
            location = data.get('location')
        except:
            return Coordinates(latitude=None , longitude=None)
        location_string=None
        city=None
        state=None
        country=None
        if location:
            place_entity = locationtagger.find_locations(text=location)
            
            extracted_cities = list(place_entity.cities)
            extracted_regions = list(place_entity.regions)
            extracted_countries = list(place_entity.countries)
            
            if extracted_cities:
                city = extracted_cities[0]
            if extracted_regions:
                state = extracted_regions[0]
            if extracted_countries:
                country = extracted_countries[0]
            
            # location_string = ' '.join(filter(None, [city, state, country]))
            
            if not location_string:
                location_string = location
        else:
            return ErrorResponse(error="No location information provided")

        geolocator = Nominatim(user_agent="Geolocation")
        print("Printing location string")
        print(location_string)
        if city or state or country :
            location_string = city
        elif country is None:
            location_string = city
        elif city is None:
            location_string = state
        elif state is None:
            location_string = city

        try:
            getLoc = geolocator.geocode(location_string)
            print(getLoc.latitude)
            print(getLoc.longitude)
            return Coordinates(
                latitude=getLoc.latitude,
                longitude=getLoc.longitude
            ) 
        except Exception as e:
            print(f"Error {e}")
            return Coordinates(latitude=None , longitude=None)