Real-Time Location Tracker

 import tkinter as tk

from tkinter import messagebox

import requests

import folium

import webbrowser

from geopy.geocoders import Nominatim

import os


def get_location():

    try:

        response = requests.get("https://ipinfo.io/json")

        data = response.json()

        loc = data['loc'].split(',')

        latitude = float(loc[0])

        longitude = float(loc[1])

        city = data.get('city', 'Unknown')

        return latitude, longitude, city

    except Exception as e:

        messagebox.showerror("Error", f"Could not get location.\n{str(e)}")

        return None, None, None


def show_location():

    lat, lon, city = get_location()

    if lat is None or lon is None:

        return


    # Reverse geocode to get address

    geolocator = Nominatim(user_agent="geoapiExercises")

    location = geolocator.reverse((lat, lon), language="en")

    address = location.address if location else "Address not found"


    # Show location on map

    map_obj = folium.Map(location=[lat, lon], zoom_start=14)

    folium.Marker([lat, lon], popup=f"{address}", tooltip="You are here").add_to(map_obj)


    map_file = "real_time_location.html"

    map_obj.save(map_file)

    webbrowser.open(f"file://{os.path.abspath(map_file)}")


    location_label.config(text=f"City: {city}\nLatitude: {lat}\nLongitude: {lon}\n\n{address}")


# GUI

app = tk.Tk()

app.title("📍 Real-Time Location Tracker")

app.geometry("500x300")


tk.Label(app, text="Click the button to track your location", font=("Arial", 14)).pack(pady=20)


tk.Button(app, text="Track My Location", command=show_location, bg="#1E90FF", fg="white", font=("Arial", 12)).pack(pady=10)


location_label = tk.Label(app, text="", font=("Arial", 10), justify="left", wraplength=450)

location_label.pack(pady=20)


app.mainloop()


No comments: