php Google IP 地理定位 API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13793655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:04:47  来源:igfitidea点击:

Google IP Geolocation API

phpip-geolocation

提问by keykiller91

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

有什么方法可以使用任何 Google API 在实时获取我的用户的 IP 地理位置?

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!)

我认为它将使用分析数据库,这是唯一一个在城市级别跟踪我的用户实际上是正确的(我可以测试的任何其他 IP-Location-API 显示我的 IP 地址距离我的真实位置近 200 公里。谷歌显示它在 200m(!) 外!)

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.

我想知道我的用户的位置(在浏览器端并将其传输到我的服务器或服务器端)以提供与城市相关的内容。但我不想让我的用户出现这些要求使用 GPS 的烦人弹出窗口,所以我想使用 IP 地址。

Any suggestions?

有什么建议?

采纳答案by Sherif

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.

如果您不想使用HTML5 样式客户端启用的 GeoIP 信息,您将需要一个 GeoIP 数据库,如MaxMind 的 GeoIP Lite 数据库,它是免费的,适用于 99% 的用例。任何其他具有更准确/详细信息的服务都将花费您很多钱。MaxMind 受到很多人的称赞,并且非常适合我个人的需求。它可以为您提供国家/地区/城市/纬度-经度-坐标/大陆信息。

回答by Nicolas Garnier

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

您可以使用 Google 的地理定位 API 根据用户的 IP 地址获取纬度和经度:

  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:

然后您可以使用这些坐标通过地理编码 API 获取用户的地址。这是一个返回国家/地区的示例:

  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.resultsto find the information you need (City, Street, Country etc...) Use these two functions above together:

以上,只需翻阅data.results即可找到您需要的信息(城市、街道、国家等...) 一起使用上面的这两个功能:

findLatLonFromIP().then((latlng) => {
  return getCountryCodeFromLatLng(latlng.lat, latlng.lng);
}).then((countryCode) => {
  console.log('User\'s country Code:', countryCode);
});

回答by Kartik

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.

您可以使用 Google 的地理编码 API 来获取某个位置的真实地址,但该 API 所需的输入是纬度和经度坐标。

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

示例: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.

您需要从其他供应商处找到 IP 到位置 API 才能到达城市级别,或者保留提示他们授予您访问其地理位置的权限的选项。

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

IPInfoDB 在无需使用输入的情况下通过 IP 自动缩小位置范围方面做得非常好:

http://ipinfodb.com/ip_location_api.php

http://ipinfodb.com/ip_location_api.php