I am trying to make a python IP locator, which currently relies on this function:
def get_location(ip_address="", show_duplicates=True):
url = f"http://ip-api.com/json/{ip_address}"
try:
response = requests.get(url, timeout=5)
data = response.json()
if data["status"] == "success":
loc_key = (data['city'], data['regionName'], data['country'])
if show_duplicates or loc_key not in seen_locations:
print("\n=== Location Info ===")
print(f"IP Address: {data['query']}")
print(f"City: {data['city']}")
print(f"Region: {data['regionName']}")
print(f"Country: {data['country']}")
print(f"ZIP: {data['zip']}")
print(f"ISP: {data['isp']}")
print(f"Latitude: {data['lat']}")
print(f"Longitude: {data['lon']}")
print(f"Map: https://www.google.com/maps?q={data['lat']},{data['lon']}\n")
seen_locations.add(loc_key)
else:
print(f"{ip_address} - Duplicate location, skipped.")
else:
print(f"{ip_address} - No data.")
except Exception as e:
print(f"Error checking {ip_address}: {e}")
Is there an alternative method of doing this with ip-api that is more specific, or is this the optimum code?
This is how you can get your own location:
import geocoder
g = geocoder.ip('me')
location = g.address
latlng = g.latlng
You will need to pip install before you use geocoder via pip install geocoder
To get the location from ip:
import geocoder
g = geocoder.ip('199.7.157.0')
location = g.address
latlng = g.latlng