我正在创建一个传输应用程序,我想在将位置更改为MySQL数据库后立即保存用户的当前位置,稍后我将获取结果并在地图上绘制标记。 这是我当前位置的代码
var watchid;
$( document ).on( "pagecreate", "#map-page", function() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
watchid = navigator.geolocation.watchPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
}
});
答案 0 :(得分:0)
每1毫秒更新一次
var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
现在在onSuccess中获取位置
function onSuccess (position) {
var newLocation = position.coords;
if(newLocation .latitude === oldLocation.latitude && oldLocation.longitude === crd.longitude){
//donot save in DB
} else{
//save in db and draw it on map
var myLatLng = new google.maps.LatLng( position.coords.latitude,position.coords.longitude );
drawmap(myLatLng );
}
}
交换newLocation和oldLocation的值,其中oldLocation最初是当前位置,并且在每次位置更改后刷新newLocation的值并将您的位置设置为oldLocation。 希望它有所帮助。