页面刷新后删除旧Google Maps Marker的问题求助
解决Google Maps刷新页面重复标记的问题
看起来你遇到的核心问题有两个:一是每次刷新页面都会在Firebase的locations下新增一个位置节点,导致历史记录堆积;二是页面加载时会监听所有child_added事件,把所有历史位置都渲染成标记,所以才会出现一堆重复标记。
我来帮你调整代码,实现每次刷新只保留当前用户的最新标记:
关键修改点
- 用唯一标识绑定用户位置:不要每次刷新都创建新的Firebase节点,而是用用户的唯一标识(比如你现在用的Cookie)作为节点ID,每次刷新直接覆盖这个节点的位置,这样Firebase里只会保留该用户的最新位置。
- 维护全局标记实例:在全局声明一个标记变量,当加载位置时,如果标记已存在就更新它的位置,不存在再创建新的,避免重复创建。
- 优化监听逻辑:改用
value事件监听当前用户的节点数据,确保只处理当前用户的最新位置,不会触发历史记录的渲染。
修改后的完整代码
<!DOCTYPE html> <html> <head> <title>Geolocation</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } </style> <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); } // 获取用户唯一标识(复用你当前的Cookie) var userUniqueId = document.cookie || "default_user_id"; // 绑定到固定节点,不再每次生成新节点 var userLocationRef = firebase.database().ref("locations/" + userUniqueId); var geoFire = new GeoFire(userLocationRef); </script> </head> <body> <div id="map"></div> <script> var map, infoWindow; var userMarker = null; // 全局维护当前用户的标记实例 var bounds = new google.maps.LatLngBounds(); var infowindow = new google.maps.InfoWindow(); function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 18 }); infoWindow = new google.maps.InfoWindow; // 尝试HTML5定位 if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; var pos = {lat: lat, lng: lng }; // 更新当前用户的位置到Firebase(直接覆盖旧数据) _setGeoFire(lat, lng); // 监听当前用户节点的位置变化(首次加载+后续更新) userLocationRef.on('value', function(snapshot) { var data = snapshot.val(); if (data && data.User) { var userPos = { lat: data.User.l[0], lng: data.User.l[1] }; // 更新或创建标记 if (userMarker) { userMarker.setPosition(userPos); } else { userMarker = new google.maps.Marker({ position: userPos, map: map, label: userUniqueId }); // 标记点击事件 userMarker.addListener('click', function() { infowindow.setContent(this.getPosition().toUrlValue(6) + "<br>" + data.User.g); infowindow.open(map, this); }); } bounds.extend(userPos); map.fitBounds(bounds); map.setCenter(userPos); } }); infoWindow.setPosition(pos); infoWindow.setContent('Current Location'); infoWindow.open(map); map.setCenter(pos); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } else { 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(lat, lng){ geoFire.set("User", [lat, lng]).then(()=>{ console.log("Location updated"); }).catch(function(error) { console.log(error); }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2nPlSt_nM7PSKD8So8anbUbBYICFWcCA&callback=initMap"> </script> </body> </html>
代码说明
- 固定节点存储:通过
userUniqueId绑定到Firebase的固定节点,每次刷新页面都会覆盖该节点的旧位置数据,不会产生历史冗余记录。 - 单标记管理:用
userMarker全局变量跟踪当前用户的标记,位置更新时直接调用setPosition移动标记,而非重复创建新标记。 - 精准监听:改用
value事件监听当前用户的节点,只会触发最新的位置数据,不会加载历史的位置记录,从根源避免重复标记。
这样修改后,每次刷新页面时,Firebase里只会保留你最新的位置,页面上也始终只会显示一个标记,不会再出现重复的情况啦!
内容的提问来源于stack exchange,提问作者BIlly BOB
相关产品推荐
相关产品推荐

