Google IP Geolocation API [closed]
Asked Answered
W

3

11

Is there any way to use any of the Google APIs to get the IP Geolocation of my User in Live time?

I think it will use the Analytics Database and that is the only one, that tracks my user at city level that actually is correct (Any other IP-Location-API that I could test shows my IP address nearly 200km away from my real location. Google shows it 200m(!) away!)

I want to know the Location of my User (At Browser side and transmit it to my Server or at Server side) to serve City dependent content. But I don't want to get my users one of these annoying pop ups asking for using GPS, so I want to use the IP address.

Any suggestions?

Wire answered 10/12, 2012 at 1:5 Comment(0)
S
11

If you don't want to use HTML5 style client-enabled GeoIP information, you are going to need a GeoIP database like MaxMind's GeoIP Lite database, which is free and works well for 99% of use cases. Any other service with more accurate/detailed information is going to cost you a lot of money. MaxMind is praises by many people and works well for my needs, personally. It can give you Country/Region/City/Latitude-Longitude-Coordinates/Continent information.

Sonny answered 10/12, 2012 at 1:12 Comment(4)
Hmm... I Thought I could use Google's Data in any way. I think I'll use the IP database and provide a button "Location based" for the users, that enables the HTML5-Geolocation. Is there a Test-Page for the MaxMinds GeoIP DB to test the accuracy of my IP?Wire
Not that I'm aware of. The best way to test it is to download it and try it for yourself.Sonny
@user3705511 Maxmind offers a free version as well as a paid version of the database. Had you simply followed the link above you would have clearly seen that. I'm not sure what is meant by "it have some license agreement", but sure all things - even free things - have license agreements.Sonny
@Sonny I think Savan Paun's complaint meant "It's not free as in free speech," not "It's not free as in free beer."Pelias
G
6

You can use Google's geolocation API to get the lat and lon based on the user's IP address:

  var apiKey = "Your Google API Key";

  function findLatLonFromIP() {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: `https://www.googleapis.com/geolocation/v1/geolocate?key=${apiKey}`,
        type: 'POST',
        data: JSON.stringify({considerIp: true}),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: (data) => {
          if (data && data.location) {
            resolve({lat: data.location.lat, lng: data.location.lng});
          } else {
            reject('No location object in geolocate API response.');
          }
        },
        error: (err) => {
          reject(err);
        },
      });
    });
  }

Then you can use these coordinates to get the address of the user using the geocoding API. Here is an example that returns the country:

  function getCountryCodeFromLatLng(lat, lng) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${apiKey}`,
        type: 'GET',
        data: JSON.stringify({considerIp: true}),
        dataType: 'json',
        success: (data) => {
          console.log('reverse geocode:', data.results[0].address_components);
          data.results.some((address) => {
            address.address_components.some((component) => {
              if (component.types.includes('country')) {
                return resolve(component.short_name);
              }
            });
          });
          reject('Country not found in location information.');
        },
        error: (err) => {
          reject(err);
        },
      });
    });
  }

Above, just look through the data.results to find the information you need (City, Street, Country etc...) Use these two functions above together:

findLatLonFromIP().then((latlng) => {
  return getCountryCodeFromLatLng(latlng.lat, latlng.lng);
}).then((countryCode) => {
  console.log('User\'s country Code:', countryCode);
});
Guttural answered 28/5, 2018 at 18:58 Comment(1)
Perfect and accurate answer i was looking for. Can you tell me how can i give ip-address by myself as a parameter.Manhattan
G
0

You can use Google's geocoding API to get a real address for a location but the inputs required for that API are the latitude and longitude coordinates.

Example: http://maps.googleapis.com/maps/api/geocode/json?latlng=43.473,-82.533&sensor=false

You need to find and IP to Location API from some other vendor to get to a city level or keep the option to prompt them to grant you access for their geolocation.

IPInfoDB does a pretty good job at automatically narrowing down the location via IP without use input:

http://ipinfodb.com/ip_location_api.php

Gasser answered 10/12, 2012 at 1:12 Comment(2)
No Way! I am actually using IPInfoDB and the users from Unitymedia (a local ISP) can't use the location based services, because they just place them all in one City (that doesn't even show up in Google Analytics)Wire
The Unitymedia case may not be IPinfoDB's fault. If it's a specific ISP, they could be using Carrier Grade NAT, which effectively means people all over a region are using a small pool of IPs, making it impossible to untangle which session is where by IP address alone. Check this deck from Jason Fesler at Yahoo: meetings.apnic.net/__data/assets/file/0003/38298/…Neilson

© 2022 - 2024 — McMap. All rights reserved.