如何根据用户位置(而不是html5地理定位)来中心谷歌地图? (angularJS)

时间:2016-01-21 15:19:47

标签: angularjs html5 google-maps geolocation

我正在关注this教程,在本部分的最后一步中,作者展示了一段代码:

// Get User's actual coordinates based on HTML5 at window load
geolocation.getLocation().then(function(data){

    // Set the latitude and longitude equal to the HTML5 coordinates
    coords = {lat:data.coords.latitude, long:data.coords.longitude};

    // Display coordinates in location textboxes rounded to three decimal points
    $scope.formData.longitude = parseFloat(coords.long).toFixed(3);
    $scope.formData.latitude = parseFloat(coords.lat).toFixed(3);

    // Display message confirming that the coordinates verified.
    $scope.formData.htmlverified = "Yep (Thanks for giving us real data!)";

    gservice.refresh($scope.formData.latitude, $scope.formData.longitude);

});

当我运行他的应用程序(您可以查看here)时,浏览器会询问我是否同意分享我的位置 - 如果我这样做 - 地图中心并关注我的真实位置。但是,当我否认时,地图显示我是美国的中心(我来自欧洲)。

所以我的问题是:如果他拒绝使用真实的GPS数据,是否有办法将地图置于用户位置附近?例如基于他的IP地址或主机?在这种情况下,我不需要确切的位置,但是城市或国家会很高兴。

1 个答案:

答案 0 :(得分:1)

如果用户拒绝浏览器中的位置,则无法获得任何内容。没有"一般位置"倒退。 IP可能是此时任何类型解决方案的唯一选择。我没有在用户代理中看到任何提供位置的内容。在创建Google地图时,您可以在实例化时指定地图的默认中心,在教程中他必须为美国完成。

修改

使用IP,你应该能够找到一个服务,将IP解析为这样的物理区域:

IP to Location

然后,您可以将该位置发送到Google地图地理编码器,以获得一个可以将地图居中的点,如下所示:

Google Maps Geocoding example