Getting position data with GeoLocation
We are going to look at the window object navigator now to see whether we can locate the user of the browser. This can be useful for many things, for example, suggesting restaurant locations nearby the user. We can have a look at the GeoLocation
by inspecting navigator.geolocation
. This is one way to do it:
<!DOCTYPE html>
<html>
<body>
<script>
window.onload = init;
function init() {
console.dir(navigator.geolocation);
}
</script>
</body>
</html>
If you check out the log, you can see what the GeoLocation
object contains, and one of these methods is to get the current position of the user. Here is how to use it:
<!DOCTYPE html>
<html>
<body>
<script>
window.onload = init;
function init() {
navigator.geolocation.getCurrentPosition(showGeoPosition);
}
function showGeoPosition(data) {
...