gpt4 book ai didi

HTML5 geolocation watchPosition 只被调用一次

转载 作者:太空狗 更新时间:2023-10-29 13:44:34 26 4
gpt4 key购买 nike

我正在使用 html 5 创建一个 android 应用程序,我想在用户移动时从用户那里访问 latlong。我使用过 watchPostion,但它只给我一次用户位置。

    var watchID;
var geoLoc;

function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

var ll=new google.maps.LatLng(latitude, longitude);
map.setCenter(ll);

console.log("Latitude : " + latitude + " Longitude: " + longitude);
}

function errorHandler(err) {
if(err.code == 1) {
console.log("Error: Access is denied!");
}else if( err.code == 2) {
console.log("Error: Position is unavailable!");
}
}
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation,
errorHandler,
options);


}else{
console.log("Sorry, browser does not support geolocation!");
}

最佳答案

几个月前我一直在做类似的事情。我记得有同样的问题。也许这会有所帮助。

$(document).ready(function(){  
initLocationProcedure();
}

function initLocationProcedure() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom : 17
});

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError, {
enableHighAccuracy : true,
timeout : 60000,
maximumAge : 0
});
} else {
alert("Your phone does not support the Geolocation API");
}
}

function displayAndWatch(position) {
// set current position
setUserLocation(position);
// watch position
watchCurrentPosition();
}

function setUserLocation(pos) {
// marker for userLocation
userLocation = new google.maps.Marker({
map : map,
position : new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
title : "You are here",
icon : "../img/user-location.svg",
// scroll to userLocation
map.panTo(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
});

这就是你要找的

function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
}

function setMarkerPosition(marker, position) {
marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
console.log(position);
}

fiddle
http://jsfiddle.net/XEFks/

关于HTML5 geolocation watchPosition 只被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23700986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com