javascript - 动态获取当前 LatLng(Google map )

标签 javascript html geolocation

我有以下代码:

 <!DOCTYPE html>
 <head>
    <title>Geolocation Service</title>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
    <script>
        function initialize() {
            var lat = ???;
            var lng = ???;
            var map = {
                center:new google.maps.LatLng(lat,lng),
                zoom:5,
                mapTypeId:google.maps.MapTypeId.ROADMAP
            };
            var map=new google.maps.Map(document.getElementById("mapcontainer"), map);
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <div id="mapcontainer">
        <!--Map goes here-->
    </div>
</body>
<style>
   *
    {
        margin: 0;
    }

    #mapcontainer
    {
        width: 100vw;
        height: 100vh;
    }
</style>
</html>

在我的变量 latlng 中,我将它们设置为 ??? 因为我不知道如何获取当前位置。我刚刚开始学习 Google Geolocation API。谢谢!

最佳答案

如果您使用 Google Loader 加载 Google map ,您可以使用 google.loader.CurrentLocation 获取基于 IP 的位置,如 this answer 中所示。

另一种选择是利用HTML5 GeoLocation API :

function initialize() {

   // Is HTML5 geolocation supported
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position){

         var lat = position.coords.latitude;
         var lng = position.coords.longitude;
         //..

      });
   } 

}            

您可能会发现Google Maps JavaScript API - Geolocation示例很有帮助。

关于javascript - 动态获取当前 LatLng(Google map ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30368944/

相关文章:

javascript - 在警报中显示之前格式化字符串以添加\n?

javascript - 有没有办法在没有文档的情况下实例化 CanvasRenderingContext2D 对象以供网络 worker 使用?

ios - xamarin 形成使用位置 iOS 的权限

javascript - 如何将基于表单的身份验证从 iPhone 应用程序传递到网站?

javascript - 对象不支持此属性或方法 IE8 hasclass 方法

javascript - Bootstrap Navbar Logo 和 Menu CSS 类在滚动后发生变化

javascript - 我如何通过Javascript将多个html插入模态

javascript - 无法让我的 RouteProvider 和 Controller 一样工作

php - 为提供的纬度、经度查找最近的司机的程序

javascript - 谷歌地图 API V3 Over_Query_Limit