【问题标题】:watchPosition() refreshes the full map not only the markerwatchPosition() 不仅刷新了标记,还刷新了整个地图
【发布时间】:2017-10-08 03:11:23
【问题描述】:

我有一个代码,但问题是 watchposition() 正在重新加载完整的地图。我想要的是一个仅刷新标记位置的代码。这是我所做的:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geo Location</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas{ height: 100% }
</style>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;     
var myLatlng = new google.maps.LatLng(lat,lang);
    var mapOptions = {zoom: 4,center: myLatlng};
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var marker = new google.maps.Marker({position: myLatlng,map: map});     
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var watchID=navigator.geolocation.watchPosition(onSuccess,onError{timeout:30000 });
 </script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

【问题讨论】:

标签: javascript html google-maps-markers


【解决方案1】:

使用setPosition()
像这样吗?
https://plnkr.co/edit/UgCEnQ?p=preview

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <style>
    #map {
      width: 100%;
      height: 300px;
    }
  </style>
  <div id="map"></div>
  <script>
    var marker, map;

    function initMap() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

          var lat = position.coords.latitude;
          var lng = position.coords.longitude;
          var myLatLng = new google.maps.LatLng(lat, lng);
          map = new google.maps.Map(document.getElementById('map'), {
            center: myLatLng,
            zoom: 18

          });



          if (marker != undefined) {
            marker.setPosition(myLatLng);
          } else {
            marker = new google.maps.Marker({
              position: myLatLng,
              map: map
            });

          }


        });
      }



    }
  </script>
  <script src="https://maps.google.com/maps/api/js?callback=initMap" async defer></script>

</body>

</html>

【讨论】:

  • 这是一个 android 应用程序,当我在移动设备上测试它时,它不使用设备的 gps。
猜你喜欢
  • 2016-01-29
  • 2018-01-21
  • 2021-01-14
  • 2013-08-28
  • 2014-07-19
  • 1970-01-01
  • 2016-02-17
  • 2015-05-09
  • 2015-11-18
相关资源
最近更新 更多