是的,当然,Google Maps JS API v3 确实提供了 IP 位置地理编码服务。您可以使用此代码根据用户的 IP 地址获取用户位置:
// If ClientLocation was filled in by the loader, use that info instead
if (google.loader.ClientLocation) {
zoom = 13;
latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
location = "Showing IP-based location: <b>" + getFormattedLocation() + "</b>";
}
除了纬度/经度之外,google.loader.ClientLocation
返回一个地址,其中包括城市、国家、国家代码、地区等...
另外,看看这里的例子 http://gmaps-samples-v3.googlecode.com/svn/trunk/commonloader/clientlocation.html.
即使地址为空,您始终可以将返回的纬度/经度与地理编码服务 https://developers.google.com/maps/documentation/javascript/geocoding获取详细地址。
然而,正如文中提到的官方网站 https://developers.google.com/maps/articles/geolocation:
...我们不建议使用这种方法(使用 IP 地址来检测用户的位置)进行地理定位。 W3C 方法是最简单且支持最全面的方法,因此应优先于其他方法。
也在问题跟踪器 https://code.google.com/p/google-ajax-apis/issues/detail?id=586:
...我们几年前就停止记录它,并推荐基于 HTML 的解决方案,因为它们提高了准确性,但该功能本身并没有从加载器中删除...
最好的方法是使用基于HTML5 http://www.w3schools.com/html/html5_geolocation.asp方法。但是,如果您使用基于 IP 的服务,请确保您意识到 Google 可以随时放弃对它的支持。