watchPosition - как постоянно отслеживать месторасположение клиента в javascript
Компьютеры / Программирование / javascript (джаваскрипт)
Тэги: javascript javascript полезные скрипты javascript API Geolocation
Тэги: javascript javascript полезные скрипты javascript API Geolocation
📅3-05-2018 👁355
Для этого нужно использовать метод watchPosition.
в хэд вставляем:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
После запуска передвигаетесь и вы увидите свои перемещения на карте и меняющиеся координаты.
</head>
<body>
<div id="loc">
<p id="latt"> </p>
<p id="long"> </p>
<p id="accuracy"> </p>
<p id="err" style="color:red"> </p>
</div>
<br>
<div id="map" style=" width:600px; height:600px;"></div>
<script>
var watchId = null;
var map;
getloc();
function getloc(){
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(positionCallback, onerror);
// чтобы повысить точность определения, заменить на:
// watchId = navigator.geolocation.watchPosition(positionCallback, onerror,{enableHighAccuracy:true,maximumAge:40000});
}else{
alert ("нет Loc");
}
}
function positionCallback(pos){
document.getElementById("latt").innerHTML = "lattitude: " + pos.coords.latitude;
document.getElementById("long").innerHTML = "longitude: " + pos.coords.longitude;
document.getElementById("accuracy").innerHTML = "longitude: " + pos.coords.accuracy + " metres accuracy";
console.log (pos.timestamp);
if (map == null){
showGoogleMap(pos.coords);
prevCoords = pos.coords;
}else{
var meters = computeDistance (pos.coords,prevCoords)*1000; // вычисляем расстояние между между прошлым и текущим расположением
// если расстояние больше 20 метров то ставим маркер и обновляем карту
if (meters > 20) {
scrollMapToPosition (pos.coords);
prevCoords = pos.coords;
}
}
}
function onerror(error){
document.getElementById("err").innerHTML = "error: " + error.code + " " + error.message;
}
function showGoogleMap(coords){
var googlecoords = new google.maps.LatLng (coords.latitude,coords.longitude);
var mapOptions ={
zoom:18,
center: googlecoords,
mapTypeId: 'roadmap'
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map (mapDiv, mapOptions);
addMarker (map, googlecoords, "Your location: "+ coords.latitude + ", " +coords.longitude, "you are here");
}
function scrollMapToPosition (coords){
var latlong = new google.maps.LatLng (coords.latitude,coords.longitude);
map.panTo (latlong);
addMarker (map, latlong, "You moved to: "+ coords.latitude + ", " +coords.longitude, "Your new location");
}
function addMarker (map, latlong, title, content) {
var markerOptions = {
position: latlong,
map: map,
title: title,
clickable: true
};
var marker = new google.maps.Marker (markerOptions);
var infoWindowOptions = {
content: content,
position: latlong
};
var infoWindow = new google.maps.InfoWindow (infoWindowOptions);
google.maps.event.addListener (marker, "click", function() {
infoWindow.open (map);
});
}
function computeDistance(startCoords, destCoords) {
var startLatRads = degreesToRadians(startCoords.latitude);
var startLongRads = degreesToRadians(startCoords.longitude);
var destLatRads = degreesToRadians(destCoords.latitude);
var destLongRads = degreesToRadians(destCoords.longitude);
var Radius = 6371; // radius of the Earth in km
var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) +
Math.cos(startLatRads) * Math.cos(destLatRads) *
Math.cos(startLongRads - destLongRads)) * Radius;
return distance;
}
function degreesToRadians(degrees) {
radians = (degrees * Math.PI)/180;
return radians;
}
Оставить свой ответ: