繁体   English   中英

如何更新谷歌地图标记位置?

[英]How to update google maps marker position?

所以我正在尝试为学校项目建立一个网站,其中一部分需要获取用户位置并将其显示在地图上。 我已经设法使用 geolocator api 获取用户位置,但似乎无法更新标记,因为即使在获得新的纬度后它仍保留在默认位置。 任何帮助将不胜感激 :)

我采用了默认位置(加利福尼亚)在加载网站时显示(它成功)并设法获取用户位置(使用控制台验证以显示结果),但代码仍显示加利福尼亚标记。

<script type="text/javascript">
          var latitude = 36.8;
          var longitude = -119.4;
          var currloc;

          function getLoc() {

            if ("geolocation" in navigator) {
              navigator.geolocation.getCurrentPosition(function(position) {
                latitude = (Math.round(position.coords.latitude*100))/100;
                longitude = (Math.round(position.coords.longitude*100))/100;
                currloc = {lat: latitude, lng: longitude};
                console.log("Geolocation supported");

                console.log(latitude);
                console.log(longitude);
              });
            }
            else {
              latitude = 0.0;
              longitude = 0.0;
              console.log("Geolocation not supported");
            }
          }

          function mapInit() {
              currloc = {lat: latitude, lng: longitude};
              var map = new google.maps.Map(document.getElementById("map"), {zoom: 4, center: currloc, disableDoubleClickZoom: true,});
              var mark = new google.maps.Marker({
                position: currloc,
                map: map,
                title: latitude+', '+longitude
              });
            }

        </script>

我希望标记会随着 initMap 函数的 currloc 值发生变化而发生变化,但是在地图上它没有显示新位置。

getLoc() 是异步的。 调用回调后 Currloc 发生变化。 我假设您同步调用了 mapInit。 在回调中调用标记

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM