刷新/删除谷歌地图API上的标记

Refreshing/deleting markers on Google Maps API

本文关键字:API 删除 谷歌地图 刷新      更新时间:2023-09-26

我使用标记在我的网站上显示带有当前用户位置的谷歌地图(然后,我将添加其他功能)。我可以做到:每次用户移动时,都会在地图上用户的新位置插入另一个标记,但上一个标记没有删除,所以我添加了越来越多的标记,在刷新用户位置之前无法删除上一个。我尝试过使用定时器和其他策略,但没有成功:marker.setVisible(false),marker.setMap(null).

代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <style>
      body,html {height:100%}
      #map {width:100%;height:100%;}
    </style>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
    <script>  
      var map;
      function initGeolocation() {
        if (navigator && navigator.geolocation) {
        var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, {enableHighAccuracy:true,timeout:5000,maximumAge:0});
        } else {
          console.log('Geolocation not suported');
        }
      }
      function errorCallback() {}
      function successCallback(position) {
        var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        if(map == undefined) {
          var myOptions = {
            zoom: 18,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          }
          map = new google.maps.Map(document.getElementById("map"), myOptions);
        }
        else map.panTo(myLatlng);
        markerUser = new google.maps.Marker({
          position: myLatlng,
          map: map,
          icon: 'img/iconFox.png',
          title:"You're here!"
        });        
    }
    </script>
  </head>
  <body onload="javascript:initGeolocation()">
    <div id="map">
    </div>    
  </body>
</html>

在全局范围(定义map变量的地方)中定义标记变量,如果标记已经存在,则移动它,否则创建它。

if (markerUser && markerUser.setPosition) {
    // marker exists, move it
    markerUser.setPosition(myLatlng);
} else { // create the marker
    markerUser = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: 'img/iconFox.png',
        title: "You're here!"
    });
}

代码片段:

var map;
var markerUser;
function initGeolocation() {
  if (navigator && navigator.geolocation) {
    var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    });
  } else {
    console.log('Geolocation not suported');
  }
}
function errorCallback() {}
function successCallback(position) {
  var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  if (map == undefined) {
    var myOptions = {
      zoom: 18,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);
  } else map.panTo(myLatlng);
  if (markerUser && markerUser.setPosition) {
    // marker exists, move it
    markerUser.setPosition(myLatlng);
  } else { // create the marker
    markerUser = new google.maps.Marker({
      position: myLatlng,
      map: map,
      icon: 'http://maps.google.com/mapfiles/ms/micons/blue.png',
      title: "You're here!"
    });
  }
}
google.maps.event.addDomListener(window, 'load', initGeolocation);
body,
html {
  height: 100%
}
#map {
  width: 100%;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map">

以下是Google Map JavaScript API教程。您应该根据需要为addremove标记创建函数:

        //Create array of markers as global variable
        var markers = [];
        //And when you add marker onto your map, you push them into array
        markerUser = new google.maps.Marker({
          position: myLatlng,
          map: map,
          icon: 'img/iconFox.png',
          title:"You're here!"
        });
        markers.push(markerUser);
       // Sets the map on all markers in the array.    
        function setMapOnAll(map) {
          for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
          }
        }
        // Removes the markers from the map, but keeps them in the array. It will hide all markers.
        function clearMarkers() {
          setMapOnAll(null);
        }
        // Shows any markers currently in the array.
        function showMarkers() {
          setMapOnAll(map);
        }
        // Deletes all markers in the array by removing references to them.
        function deleteMarkers() {
          clearMarkers();
          markers = [];
        }