简体   繁体   English

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

[英]How to update google maps marker position?

So I'm trying to set up a website for a school project and part of it requires obtaining user location and displaying it on a map.所以我正在尝试为学校项目建立一个网站,其中一部分需要获取用户位置并将其显示在地图上。 I've managed to get the user location using the geolocator api but can't seem to update the marker as even after getting new lat long it remains in the default location.我已经设法使用 geolocator api 获取用户位置,但似乎无法更新标记,因为即使在获得新的纬度后它仍保留在默认位置。 Any help would be greatly appreciated :)任何帮助将不胜感激 :)

I've taken a default location (California) to display on loading the website (which it does successfully) and managed to get user location (verified using console to display results) but the code still displays the California marker.我采用了默认位置(加利福尼亚)在加载网站时显示(它成功)并设法获取用户位置(使用控制台验证以显示结果),但代码仍显示加利福尼亚标记。

<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>

I would expect the marker to change as the initMap function's currloc values have changed however on the map it doesn't show the new location.我希望标记会随着 initMap 函数的 currloc 值发生变化而发生变化,但是在地图上它没有显示新位置。

getLoc() is asynchronous. getLoc() 是异步的。 Currloc changes after the callback is called.调用回调后 Currloc 发生变化。 I am assuming you called mapInit synchronously.我假设您同步调用了 mapInit。 Call the marker inside the callback在回调中调用标记

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

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