【问题标题】:deleting old google maps marker after user refreshes page用户刷新页面后删除旧的谷歌地图标记
【发布时间】:2018-10-25 19:15:00
【问题描述】:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <!-- Place this inside the HTML head; don't use async defer for now -->

    
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/geofire/4.1.2/geofire.min.js"></script>

  <script>
        
        var config = {
    apiKey: "",
    authDomain: "carrier-35d7c.firebaseapp.com",
    databaseURL: "https://carrier-35d7c.firebaseio.com",
    projectId: "carrier-35d7c",
    storageBucket: "carrier-35d7c.appspot.com",
    messagingSenderId: "827792028763"
  };
        if (!firebase.apps.length) {
            firebase.initializeApp(config);
        }
        
        //Create a node at firebase location to add locations as child keys
        var locationsRef = firebase.database().ref("locations");
        
        // Create a new GeoFire key under users Firebase location
        var geoFire = new GeoFire(locationsRef.push());
      </script>


  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      var lat, lng;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 18
          //mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        infoWindow = new google.maps.InfoWindow;
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            lat = position.coords.latitude;
            lng = position.coords.longitude;
            var pos = {lat: lat, lng: lng };
                _setGeoFire();
              var locationsRef = firebase.database().ref("locations");
locationsRef.on('child_added', function(snapshot) {
  var data = snapshot.val();
  var markerLabel = document.cookie;
  var marker = new google.maps.Marker({
    position: {
      lat: data.User.l[0],
      lng: data.User.l[1]
    },
    map: map,
    label: markerLabel
  });
  bounds.extend(marker.getPosition());
  marker.addListener('click', (function(data) {
    return function(e) {
      infowindow.setContent(this.getPosition().toUrlValue(6) + "<br>" + data.User.g);
      infowindow.open(map, this);
    }
  }(data)));
  map.fitBounds(bounds);
});
          
            infoWindow.setPosition(pos);
            infoWindow.setContent('Current Location');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }
      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
      function _setGeoFire(){
    geoFire.set("User", [lat, lng]).then(()=>{
            console.log("Location added");
        }).catch(function(error) {
            console.log(error);
        });
}
    </script>
    <script 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2nPlSt_nM7PSKD8So8anbUbBYICFWcCA&callback=initMap">
    </script>
  </body>
</html>

我正在使用 google maps API 在地图上显示用户当前位置。每次用户刷新页面时,它都会使用用户的当前位置创建一个新标记,但也会将旧标记保留在那里。我希望每次用户刷新页面时都删除旧标记,以便每个用户只有一个标记而不是 50 个。我尝试使用此代码。

if (marker&& marker.setPosition) {
    // marker exists, move it
    marker.setPosition(lat,lng);
} else { 
// create the marker
    marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        
    });
}

我似乎无法让它工作。如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

  • 在每次页面刷新时,您都会将新位置推送到数据库中,然后您会读回这些值。当您刷新页面时,浏览器数据消失了(没有标记,没有谷歌地图)。问题不在于标记,而在于每次刷新页面时添加位置。另外,也许您不想发布您的 google api 键映射配额是一种宝贵的资源。
  • 那么,如果您说每次刷新页面时添加位置都有问题,我将如何在每次刷新页面时删除旧位置?谢谢你的直升机

标签: javascript html google-maps-api-3 google-maps-markers geofire


【解决方案1】:

这实际上取决于您要达到的目标。当用户关闭或刷新浏览器时,您可以删除该位置。 例如:

//Create a node at firebase location to add locations as child keys
  var locationsRef = firebase.database().ref("locations");
  var pushRef = locationsRef.push()
// Create a new GeoFire key under users Firebase location
// replace var geoFire = new GeoFire(locationsRef.push()); with
var geoFire = new GeoFire(pushRef); 

稍后在您的代码中:

function _setGeoFire(){
geoFire.set("User", [lat, lng]).then(()=>{
  console.log("Location added");
  pushRef.child("User").onDisconnect().remove();
}).catch(function(error) {
  console.log(error);
});
}

【讨论】:

  • 该代码到底应该放在哪里?我试图在页面刷新时删除旧标记
  • 我已经编辑了我的答案,指出您要更改代码的位置
  • 现在标记没有显示以显示所有其他用途的位置
  • 对不起,我真的不知道你想在这里实现什么。
  • 我的原始代码用于在地图上显示所有当前用户的位置,并为每个用户提供标记。每次我刷新页面时,它都会为用户创建一个新标记,但也会保留旧标记。我想要的只是当我刷新你的页面并尝试你的代码时删除旧的标记,现在没有一个标记没有显示出来。我要上传一张我的应用最初所做的图片。
猜你喜欢
  • 2019-03-07
  • 2013-08-28
  • 2015-05-09
  • 2012-10-17
  • 2015-01-30
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多