Google Maps API v3 - IP-based Geolocation

前端 未结 2 594
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 08:16

Has anyone been able to get geo-location based on a person\'s IP to work using Google Maps API v3 JavaScript?

It seems to me that even the google provided example do

2条回答
  •  天命终不由人
    2020-12-06 09:07

    The web Google Maps API doesn't seem to offer an IP address geolocation service (the provided example suggests using the W3C Geolocation standard, which typically requires an action from the user).

    However! Google's Maps Geolocation API, typically used on mobile clients, can be used from the web and does return a latitude & longitude based on the requesting client's IP address.

    Here's a quick jQuery example that demonstrates its use:

      $.ajax({
        url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR-API-KEY',
        data: JSON.stringify({ "considerIp": "true" }),
        type: 'POST',
        contentType: 'application/json',
        success: function(data) {
          if(data.location) {
            alert(data.location.lat + ', ' + data.location.lng);
          } else {
            alert('not found');
          }
        }
      });
    

    Here's the curl equivalent:

    curl -H "Content-Type: application/json" -X POST -d '{"considerIp": true}' https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR-API-KEY
    

    Don't forget to swap in a real API key in the examples above AND to enable the Geolocation API for your Google API project.

提交回复
热议问题