javascript - 使用观察位置功能实时移动谷歌地图标记
问题描述
<!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: "AIzaSyCWZjRe2CK8Hu2VN35AgZOQ7lQZKcI-UWM",
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
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.watchPosition(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>
我需要帮助实时更新我的谷歌地图标记。我正在使用 watchPosition 自动保持实时更新,但是我希望地图标记也随着用户实时移动而移动。我不想让用户重新加载页面以看到它移动。我之前使用过 getcurrentlocation,但我了解到它不会实时更新,所以我将其更改为 watchPosition。几年前,另一位用户也遇到了同样的问题。地理位置:仅移动谷歌地图标记而不重新加载地图 似乎代码现在已经过时了,所以它对我不起作用任何帮助将不胜感激
解决方案
在 initMap() 尝试添加如下内容:
window.setTimeout(function() {
moveMarker(map, marker);
}, 3000);
moveMarker() 应该是这样的:
function moveMarker(mapS, markerS){
markerS.setPosition( new google.maps.LatLng( latx, longx ) );
mapS.panTo( new google.maps.LatLng( latx, longx ) );
window.setTimeout(function() {
moveMarker(mapS, markerS);
}, 3000);
}
使用 latx,longx 会收集您从 watchPosition 获取的数据。
它有点脆弱,但它应该可以工作。
推荐阅读
- wso2is - msf4j JWTAccessTokenBuilder 抛出 ClassNotFoundException
- python - numpy fft 幅度不例外
- python - 如何解决:使用 Spotipy 的 Python 中客户端范围不足
- angular7 - 如何在运行时更改 msal 权限?
- sparql - 匹配多个谓词的 SPARQL 语法
- javascript - 如何使用while循环将php中的数据传输到javascript
- angular - 如何切换和取消切换特定行并在 *ngFor 中更改其背景
- gcc - 快速加载困难:Windows 上带有 Quicklisp 的 CL21 系统
- linux - 如何通过 ZIP 进行管道传输并在存档中拥有可用的文件名
- javascript - 打开另一个手风琴时如何自动关闭手风琴?