【问题标题】:Get the current LatLng dynamically (Google Map)动态获取当前的 LatLng(谷歌地图)
【发布时间】:2015-05-22 01:37:19
【问题描述】:

我有以下代码:

 <!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。谢谢!

【问题讨论】:

标签: javascript html geolocation


【解决方案1】:

如果您使用 Google Loader 加载 Google 地图,则可以使用 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 示例很有帮助。

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 2021-09-11
    • 2012-11-26
    • 2014-08-03
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多