简体   繁体   English

在Google Maps API上刷新/删除标记

[英]Refreshing/deleting markers on Google Maps API

I'm showing Google Maps with the current user's location on my website (then, I'll add other features) by using a marker. 我正在使用标记在我的网站上显示具有当前用户位置的Google Maps(然后,我将添加其他功能)。 I'm able to do it: each time the user moves, another marker is inserted on the new position of the user on the map, BUT the previous marker is not removed, so I'm adding more and more markers and I can't delete the previous one before refreshing user's position. 我能够做到:每次用户移动时,都会在用户在地图上的新位置上插入另一个标记,但是不会删除先前的标记,因此我要添加越来越多的标记,并且我可以t在刷新用户位置之前删除前一个。 I've tried to use timers and other strategies without success: marker.setVisible(false), marker.setMap(null). 我尝试使用计时器和其他策略未成功:marker.setVisible(false),marker.setMap(null)。

Code: 码:

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

Following tutorial from Google Map JavaScript API . 遵循Google Map JavaScript API的教程 You should create functions for add , remove marker as you wish: 您应该根据需要创建用于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 = [];
        }

Define your marker variable in the global scope (where you define your map variable), if the marker already exists, move it, otherwise, create it. 在全局范围内定义标记变量(在其中定义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!"
    });
}

code snippet: 代码段:

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

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

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