Using IP Geolocation with Google Maps
Use Google’s Geolocation API to estimate a location from a request IP, understand its accuracy radius, and display it on a Google Map.

Google Maps does not locate a person precisely from an IP address. Google’s Geolocation API can estimate a location from the IP address of the request when considerIp is enabled and it cannot locate Wi-Fi or cell-tower signals. The response contains latitude, longitude, and an accuracy radius in meters. Treat an IP result as an approximate region, not a device’s exact position. For a browser feature that needs the user’s current position, request permission with the browser’s Geolocation API and show the returned coordinates on a Google Map.
Google describes IP geolocation as its least accurate method; the uncertainty radius can reach thousands of meters. By comparison, two or more recognized Wi-Fi access points typically produce a radius around 20 meters, while macro-cell estimates commonly have radii of hundreds of meters and can reach several thousand in sparse coverage. These are typical ranges, not guarantees. Google’s Geolocation API request and response guide documents the inputs and accuracy field.
1. Choose the location source
First decide what the application needs. An IP estimate is useful for defaults such as country, region, language, rough fraud signals, or routing. It works without a browser permission prompt, but identifies the apparent network location, which can differ from where the device is. VPNs, corporate gateways, mobile carrier routing, and proxies can make that difference substantial.

Browser geolocation is usually the better option for directions, finding nearby devices or places, or any interaction where a user expects a current device location. It requires a secure context and permission. Explain why the location is needed before triggering the prompt, and provide a useful path when the user declines.
| Decision factor | IP geolocation | Browser geolocation |
|---|---|---|
| Precision | Coarse; show the API’s uncertainty radius | Often more useful for a current device position; depends on available signals and settings |
| Consent | No browser location prompt; disclose IP processing | Browser asks the user for permission |
| When permission is denied | Can still provide a rough network estimate | Unavailable if permission is denied |
| Implementation | Server request to Geolocation API, then map display | Browser API call, then map display |
| Good fit | Country or region defaults, rough routing | Nearby or navigation features where a more precise position matters |
2. Set up Google Maps Platform
- Create or select a Google Cloud project and enable the Geolocation API and Maps JavaScript API for the services you will use.
- Create separate credentials for server-side Geolocation API requests and browser map display. Apply API restrictions and application restrictions appropriate to each key.
- Keep the Geolocation API key on your server. Do not put a web-service key in browser JavaScript. Google warns that web-service keys are intended to remain a shared secret between your server and Google; see its Maps Platform security guidance.
- Provide a publicly accessible Terms of Use and Privacy Policy for applications using these APIs. Explain whether you process or retain IP addresses and location data, and for what purpose. Follow Google’s attribution and display rules; results used as map content must be displayed on a Google Map.
For production, configure API restrictions and server IP restrictions where practical. If your hosting environment has changing outbound IP addresses, use an appropriately secured server-side proxy and Google’s current key guidance. Never expose a proxy that lets arbitrary visitors relay arbitrary API requests.
3. Get an IP-based estimate on your server
The Geolocation API accepts a POST request to https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY. Set considerIp to true to make IP fallback explicit. With no Wi-Fi or cell tower fields, the API estimates from the IP address of the request it receives, which should be your server’s outbound request IP—not automatically the visitor’s address if your server proxies the request.
cURL
export GOOGLE_GEOLOCATION_KEY='YOUR_SERVER_SIDE_API_KEY'
curl --fail-with-body -sS \
-X POST \
"https://www.googleapis.com/geolocation/v1/geolocate?key=${GOOGLE_GEOLOCATION_KEY}" \
-H 'Content-Type: application/json' \
-d '{"considerIp":true}'
A successful response resembles {"location":{"lat":37.42,"lng":-122.08},"accuracy":1200}. Use the actual returned coordinates and radius rather than assuming the sample values. The radius is measured in meters.
Python
import os
import requests
key = os.environ["GOOGLE_GEOLOCATION_KEY"]
response = requests.post(
"https://www.googleapis.com/geolocation/v1/geolocate",
params={"key": key},
json={"considerIp": True},
timeout=15,
)
response.raise_for_status()
data = response.json()
location = data["location"]
print(location["lat"], location["lng"], data["accuracy"])
Node.js
const key = process.env.GOOGLE_GEOLOCATION_KEY;
if (!key) throw new Error('Set GOOGLE_GEOLOCATION_KEY');
const endpoint = new URL('https://www.googleapis.com/geolocation/v1/geolocate');
endpoint.searchParams.set('key', key);
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ considerIp: true }),
signal: AbortSignal.timeout(15000),
});
const data = await response.json();
if (!response.ok) throw new Error(JSON.stringify(data));
console.log(data.location.lat, data.location.lng, data.accuracy);
In each example the key comes from server configuration. For an application with a logged-in visitor, expose a narrow application endpoint that returns only the fields the map needs, rather than returning the Google key or permitting arbitrary upstream requests.
What considerIp changes
considerIp defaults to true. Setting it to false prevents IP fallback. That setting is useful when you submit Wi-Fi or cell-tower observations and need to know whether those signals alone were sufficient. With no useful radio signals and IP fallback disabled, the API may return a not-found response. The request fields for Wi-Fi access points and cell towers are not a shortcut for getting device signals from an ordinary web page: the application must actually have valid observations to submit.
4. Display the estimate on a Google Map
Return the estimate from your own backend to the page, then initialize a map with those coordinates. The browser map key is visible to visitors by design, so restrict it to your website origins and to the Maps JavaScript API. Keep the server key separate.
<div id="map" style="height: 420px"></div>
<p id="location-note"></p>
<script>
// The server endpoint calls Google Geolocation API with its server-side key.
async function showApproximateLocation() {
const response = await fetch('/api/approximate-location');
if (!response.ok) throw new Error('Location lookup failed');
const result = await response.json(); // { location: { lat, lng }, accuracy }
const point = result.location;
const map = new google.maps.Map(document.getElementById('map'), {
center: point,
zoom: 10,
mapTypeControl: false,
});
new google.maps.Marker({ position: point, map, title: 'Approximate network location' });
new google.maps.Circle({
map,
center: point,
radius: result.accuracy,
fillColor: '#3367d6',
fillOpacity: 0.12,
strokeColor: '#3367d6',
strokeOpacity: 0.7,
strokeWeight: 1,
});
document.getElementById('location-note').textContent =
`Approximate network location; uncertainty radius about ${Math.round(result.accuracy)} m.`;
}
showApproximateLocation().catch(() => {
document.getElementById('location-note').textContent =
'Approximate location is unavailable. You can still browse the map.';
});
</script>
Load the Maps JavaScript API using the current recommended loading approach in Google’s Maps JavaScript API documentation, and supply your restricted browser key. The map and uncertainty circle make the estimate’s limits visible. Choose a zoom appropriate to the radius; a city-level approximation should not be framed as a street address.
5. Prefer browser geolocation when the user needs their position
Call navigator.geolocation.getCurrentPosition() in response to a clear user action, such as clicking “Use my location.” The browser API requires a secure context (normally HTTPS) and permission. Google’s guide to displaying user or device position recommends the W3C Geolocation API for browser positioning and notes that IP detection is only a rough estimate.

function locateWithBrowser() {
const note = document.getElementById('location-note');
if (!('geolocation' in navigator)) {
note.textContent = 'This browser does not provide location services.';
return;
}
note.textContent = 'Requesting permission to use your location…';
navigator.geolocation.getCurrentPosition(
({ coords }) => {
const point = { lat: coords.latitude, lng: coords.longitude };
const map = new google.maps.Map(document.getElementById('map'), {
center: point,
zoom: 15,
});
new google.maps.Marker({ position: point, map, title: 'Your reported position' });
new google.maps.Circle({
map,
center: point,
radius: coords.accuracy,
fillColor: '#188038',
fillOpacity: 0.12,
strokeColor: '#188038',
strokeOpacity: 0.7,
strokeWeight: 1,
});
note.textContent = `Reported position; browser accuracy estimate about ${Math.round(coords.accuracy)} m.`;
},
(error) => {
const messages = {
1: 'Location permission was denied.',
2: 'The device could not determine a location.',
3: 'The location request timed out.',
};
note.textContent = messages[error.code] || 'Location is unavailable.';
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 },
);
}
enableHighAccuracy asks the browser to prefer a more accurate result where supported; it does not guarantee a particular precision and may take longer or use more device resources. timeout bounds how long the request waits, and maximumAge allows a recent cached device result. Surface coords.accuracy as well; browser positioning also has uncertainty.
6. Decide how the map should communicate uncertainty
- Draw a circle with the returned radius, or explicitly label the result “approximate.” A marker alone can imply false precision.
- Use the estimate only for decisions that tolerate its uncertainty. Do not use IP estimates to dispatch emergency services, navigate a user to a building, or make a high-impact decision about an individual.
- If the radius is too large for the feature, ask for browser location or let the user choose a place manually.
- Do not present an IP-based coordinate as the visitor’s home address or exact whereabouts. Network location can reflect an intermediary or shared gateway.
- Avoid saving coordinates or IP addresses longer than the product needs. Tell people what is collected and retained, and check the legal and policy requirements that apply to your users.
7. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Accuracy radius is very large | The service fell back to IP geolocation or received unrecognized radio observations. | Show the radius and label the result approximate. If testing radio data, set considerIp to false; a not-found response confirms the supplied signals could not be located. See Google’s Geolocation API troubleshooting guide. |
| Map key authorization error or blank map | The Maps JavaScript API is not enabled, the key is invalid, billing/project setup is incomplete, or key restrictions do not match the website. | Check the browser console and Cloud project. Enable the required API and adjust website and API restrictions for the correct production origin. |
| Geolocation API returns 403 | Key restriction, API enablement, quota, or project configuration issue. | Inspect the JSON error body and Cloud metrics; confirm the server key permits Geolocation API and the server egress IP is allowed if IP restricted. |
| Geolocation API returns 400 | Malformed JSON, wrong content type, or invalid field values. | Send a JSON body with Content-Type: application/json; check field names and types. |
| Browser says location unavailable or times out | Insecure context, disabled device location, unavailable signals, or restrictive browser settings. | Serve over HTTPS, explain the prompt, allow a reasonable timeout, and offer manual selection or a coarse fallback. |
| Location appears to be in another city | VPN, proxy, carrier gateway, corporate egress, or IP registry uncertainty. | Do not treat the estimate as exact. Offer browser geolocation or manual input if accuracy matters. |
| Map shows a marker but no uncertainty | The app discarded accuracy or rendered only a pin. |
Pass the radius through the backend response and draw a map circle with that radius in meters. |
8. Performance, reliability, and cost
IP lookup adds a server-to-server network request. Set a finite timeout, handle non-2xx responses, and avoid making page rendering depend on the lookup succeeding. A coarse fallback is often optional: render the rest of the page and let the user choose a location if lookup fails. Retry only transient failures, with a small bounded retry policy; repeating invalid-key or malformed requests will not help.
Keep the lookup behind your server so you can restrict the key, apply rate limits, and return only the fields the page needs. Apply per-user or per-session controls if an endpoint could otherwise be called repeatedly. Monitor quota and errors in the Google Cloud project. Google Maps Platform usage and pricing can change, so check the current official pricing and terms for your enabled services before estimating operating cost. Follow the applicable Maps content storage rules; do not assume geolocation or map content can be cached indefinitely.
Google requires attribution when displaying Maps content and generally limits pre-fetching, caching, and storage of Maps content, with documented exceptions. Consult the current Google Maps Platform Terms and API-specific policy pages for your deployment and region. Requirements may vary by geography, including the European Economic Area. Publish accessible Terms of Use and a Privacy Policy, disclose location processing, and request browser permission only when needed.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. It is for capturing web pages, not geolocating visitors or displaying an interactive map; use the methods above for location features. If your surrounding task is capturing a page that contains a map, one GET request returns a screenshot:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed; an MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.
FAQ
Can Google Maps locate someone by IP address?
Google’s Geolocation API can estimate coordinates from the request IP when IP fallback is enabled and it cannot resolve Wi-Fi or cell signals. It does not identify a person or guarantee their physical location.
Can I get an exact address from an IP?
No. The API returns coordinates and an uncertainty radius, and IP-based estimates can span kilometers. Do not convert the pin into a claim of an exact address.
Should I use IP geolocation or browser geolocation?
Use IP for broad defaults that work without a permission prompt. Use browser geolocation when the user’s current device position matters and they agree to share it.
Does the visitor need to share Wi-Fi or cell data for IP fallback?
No. The request can use IP fallback without those observations. If you do have valid Wi-Fi or cell data, the API can use it and return an accuracy radius; don’t fabricate signal inputs.
Why does the API result differ from the browser location?
They rely on different signals. IP estimates may point to a VPN, carrier gateway, or other network exit, while browser geolocation can use device location services and user permission.


