Я довольно новичок в JS и PHP, но я работаю над большим проектом, который имеет несколько функций в течение нескольких месяцев, и он неплохо продвигается.Программа в основном написана на PHP и JS и будет использоваться на компьютерах в парке транспортных средств.
Одна из функций программы будет использовать геозоны и geolocation.watchPosition для мониторинга местоположения пользователя GPS и отправки уведомления, если пользовательоставляет назначенную геозону.
То, что мне нужно сделать, - это способ постоянно отслеживать текущее местоположение пользователя с помощью geolocation.watchPosition и сохранять любые изменения в таблице mysql по мере их появления, чтобы, если пользователь покинул определенную геозону,области, они получают уведомление, что они покинули область.
Я могу получить местоположение пользователей, обновить базу данных с их местоположениями входа и выхода и вычислить разницу в расстоянии между двумя местоположениями.У меня уже настроены геозоны.
Как можно использовать geolocation.watchPosition, JS и PHP для обновления таблицы mysql каждый раз, когда изменяется местоположение gps пользователя?
Следующий пример кода - это то, что я используючтобы узнать местоположение пользователя и посмотреть его местоположение, но я не нашел способа обновлять таблицу mysql каждый раз, когда меняется переменная "info", которая содержит их местоположение.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<main class="container">
<div id="map" class="map"></div>
<!-- For displaying user's coordinate or error message. -->
<div id="info" class="info"></div>
</main>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[KEY]&callback=init"></script>
</body>
</html>
<script type="text/javascript">
const createMap = ({ lat, lng }) => {
return new google.maps.Map(document.getElementById('map'), {
center: { lat, lng },
zoom: 19
});
};
const createMarker = ({ map, position }) => {
return new google.maps.Marker({ map, position });
};
const getCurrentPosition = ({ onSuccess, onError = () => { } }) => {
if ('geolocation' in navigator === false) {
return onError(new Error('Geolocation is not supported by your browser.'));
}
return navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
const getPositionErrorMessage = code => {
switch (code) {
case 1:
return 'Permission denied.';
case 2:
return 'Position unavailable.';
case 3:
return 'Timeout reached.';
default:
return null;
}
}
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
getCurrentPosition({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
},
onError: err =>
alert(`Error: ${getPositionErrorMessage(err.code) || err.message}`)
});
}
// New function to track user's location.
const trackLocation = ({ onSuccess, onError = () => { } }) => {
if ('geolocation' in navigator === false) {
return navigator.geolocation.watchPosition(onSuccess, onError, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
};
// Use watchPosition instead.
return navigator.geolocation.watchPosition(onSuccess, onError);
};
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
// Use the new trackLocation function.
trackLocation({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
},
onError: err =>
alert(`Error: ${getPositionErrorMessage(err.code) || err.message}`)
});
}
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
const $info = document.getElementById('info');
trackLocation({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
// Print out the user's location.
$info.textContent = `Lat: ${lat} Lng: ${lng}`;
// Don't forget to remove any error class name.
$info.classList.remove('error');
},
onError: err => {
// Print out the error message.
$info.textContent = `Error: ${getPositionErrorMessage(err.code) || err.message}`;
// Add error class name.
$info.classList.add('error');
}
});
}
</script>