HTML and CSS Reference
In-Depth Information
var
geolocationID
;
(
function
getLocation
()
{
var
count
=
0
;
geolocationID
=
window
.
setInterval
(
function
()
{
count
++
;
if
(
count
>
3
)
{
//when count reaches a number, reset interval
window
.
clearInterval
(
geolocationID
);
getLocation
();
}
else
{
navigator
.
geolocation
.
getCurrentPosition
(
successCallback
,
errorCallback
,
{
enableHighAccuracy
:
true
,
timeout
:
10000
});
}
},
600000
);
//end setInterval;
})();
Another issue with the specific WebKit Geolocation implementation, is that accessing
geolocation activates the Geolocation service, which currently blocks page caching
(
https://bugs.webkit.org/show_bug.cgi?id=43956
). If you simply check the
geolocation
property, you can avoid this issue:
function
supports_geolocation
()
{
try
{
return
'geolocation'
in
navigator
&&
navigator
[
'geolocation'
]
!==
null
;
}
catch
(
e
)
{
return
false
;
}
}
You can view a live demo with all implemented workarounds at
http://html5e.org/exam
A Practical Use Case: User Tracking
To track a user over a set of latitude and longitude coordinates, you can use the Haversine
formula. With it, your application can calculate the shortest distance over the Earth's
surface and provide an as-the-crow-flies distance between the points. The code you need
is:
function
calculateDistance
(
lat1
,
lon1
,
lat2
,
lon2
)
{
var
R
=
6371
;
// km
var
dLat
=
(
lat2
-
lat1
).
toRad
();
var
dLon
=
(
lon2
-
lon1
).
toRad
();
var
a
=
Math
.
sin
(
dLat
/
2
)
*
Math
.
sin
(
dLat
/
2
)
+
Math
.
cos
(
lat1
.
toRad
())
*
Math
.
cos
(
lat2
.
toRad
())
*
Math
.
sin
(
dLon
/
2
)
*
Math
.
sin
(
dLon
/
2
);
var
c
=
2
*
Math
.
atan2
(
Math
.
sqrt
(
a
),
Math
.
sqrt
(
1
-
a
));
var
d
=
R
*
c
;