File size: 2,201 Bytes
7ccc567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 streamlit as st
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

# Initialize Geolocator
geolocator = Nominatim(user_agent="geo_streamlit_app")

# Helper function to handle geocoding with error handling
def geocode_location(location):
    try:
        return geolocator.geocode(location)
    except GeocoderTimedOut:
        return None

def reverse_geocode_coordinates(lat, lon):
    try:
        return geolocator.reverse((lat, lon))
    except GeocoderTimedOut:
        return None

# Streamlit UI
st.title("Geocode Generator")
st.write("Generate geographic coordinates from an address or reverse geocode coordinates.")

# Tabs for different functionalities
tab1, tab2 = st.tabs(["Geocode Address", "Reverse Geocode Coordinates"])

with tab1:
    st.header("Geocode Address")
    address = st.text_input("Enter an address:")
    if st.button("Generate Coordinates", key="geocode"):
        if address:
            location = geocode_location(address)
            if location:
                st.success(f"Coordinates for '{address}':")
                st.write(f"Latitude: {location.latitude}")
                st.write(f"Longitude: {location.longitude}")
            else:
                st.error("Could not find coordinates. Please try another address.")
        else:
            st.warning("Please enter an address.")

with tab2:
    st.header("Reverse Geocode Coordinates")
    latitude = st.text_input("Enter Latitude:")
    longitude = st.text_input("Enter Longitude:")
    if st.button("Find Address", key="reverse_geocode"):
        if latitude and longitude:
            try:
                lat = float(latitude)
                lon = float(longitude)
                location = reverse_geocode_coordinates(lat, lon)
                if location:
                    st.success(f"Address for ({lat}, {lon}):")
                    st.write(location.address)
                else:
                    st.error("Could not find an address. Please try different coordinates.")
            except ValueError:
                st.error("Invalid latitude or longitude values.")
        else:
            st.warning("Please enter both latitude and longitude.")