Created
July 19, 2025 20:56
-
-
Save Hamid-K/77a51190051e297f7ca247a793fc6a93 to your computer and use it in GitHub Desktop.
Geolocate CellID via Google GeoLocation API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Look-up the approximate position of a cell tower with Google’s Geolocation API | |
and print a Google-Maps link for easy visualisation. | |
pip install requests | |
""" | |
import json | |
import sys | |
import time | |
from typing import Dict, Any | |
import requests | |
# -------------------------------------------------------------------- # | |
# CONFIGURATION | |
# -------------------------------------------------------------------- # | |
API_KEY = "xxxxxxxxxxxxxx" # <<< REPLACE | |
HTTP_TIMEOUT = 10 # seconds | |
CELL_TOWER_DATA: Dict[str, Any] = { | |
"cellTowers": [ | |
{ | |
"cellId": 23100171, | |
"locationAreaCode": 10000, | |
"mobileCountryCode": 432, | |
"mobileNetworkCode": 11 | |
} | |
] | |
} | |
# -------------------------------------------------------------------- # | |
def geolocate(api_key: str, | |
payload: Dict[str, Any], | |
consider_ip: bool = False) -> Dict[str, Any]: | |
url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={api_key}" | |
body = dict(payload) | |
body["considerIp"] = consider_ip | |
r = requests.post(url, json=body, timeout=HTTP_TIMEOUT) | |
r.raise_for_status() | |
return r.json() | |
def pretty_output(result: Dict[str, Any]) -> None: | |
if "location" not in result: | |
print("Location not found:", result) | |
return | |
lat = result["location"]["lat"] | |
lng = result["location"]["lng"] | |
acc = result.get("accuracy", "n/a") | |
print(f"Latitude : {lat}") | |
print(f"Longitude: {lng}") | |
print(f"Accuracy : {acc} m") | |
# Google-Maps link | |
maps_url = f"https://www.google.com/maps/search/?api=1&query={lat},{lng}" | |
print("Google Maps:", maps_url) | |
def main() -> None: | |
try: | |
t0 = time.time() | |
res = geolocate(API_KEY, CELL_TOWER_DATA, consider_ip=False) | |
dt = time.time() - t0 | |
print("\n=== Geolocation result ===") | |
pretty_output(res) | |
print(f"(request took {dt:.2f} s)") | |
# full JSON, optional | |
print("\nRaw response:") | |
print(json.dumps(res, indent=2)) | |
except requests.HTTPError as e: | |
print("HTTP error:", e, file=sys.stderr) | |
if e.response is not None: | |
print(e.response.text, file=sys.stderr) | |
except requests.RequestException as e: | |
print("Request failed:", e, file=sys.stderr) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment