Professional Documents
Culture Documents
3.3 Usage of The Geolocation API
3.3 Usage of The Geolocation API
3.3 Usage of The Geolocation API
Learning outcome1:
CHAP XIII:
Use of the Geolocation API
Table of Contents
1. Geolocation API ............................................................................................................ 3
1.1. Introduction ............................................................................................................................ 3
1.2. Interfaces ................................................................................................................................ 3
1.2.1. Geolocation ..................................................................................................................... 3
1.2.2. GeolocationPosition ........................................................................................................ 4
1.2.3. GeolocationCoordinates ................................................................................................. 4
1.2.4. GeolocationPositionError................................................................................................ 4
1.3. What Is the Geolocation API? ................................................................................................. 4
1.3.1. Using the Geolocation API .............................................................................................. 4
1.4. Exercises .................................................................................................................................. 5
1. Geolocation API
1.1. Introduction
Some applications require you to know your user's location, like food delivery or eCommerce apps.
So you'll need an efficient way to get this info.
The Geolocation API, which we will look at today, is a simple solution.
You can use it to determine your users' location, local currency, language, and other useful
information. You can then use this to provide them with the most relevant content based on
their location, or
It is a web API that allows websites and web applications to access the geographical location
information of a user's device. This API enables developers to retrieve information such as
latitude, longitude, altitude, speed, and heading from a user's device, which can then be
used to provide location-based services or customize content based on the user's geographic
location
1.2. Interfaces
1.2.1. Geolocation
The main class of this API — contains methods to retrieve the user's current position, watch for
changes in their position, and clear a previously-set watch.
It represents an object able to obtain the position of the device programmatically. It gives Web
content access to the location of the device. This allows a website or app to offer customized results
based on the user's location.
An object with this interface is obtained using the navigator.geolocation property implemented by
the Navigator object.
Note: For security reasons, when a web page tries to access location information, the user is notified
and asked to grant permission. Be aware that each browser has its own policies and methods for
requesting this permission.
1. Instance methods
Geolocation.getCurrentPosition()
Determines the device's current location and gives back a GeolocationPosition object with the data.
Geolocation.watchPosition()
Returns a long value representing the newly established callback function to be invoked whenever
the device location changes.
Geolocation.clearWatch()
1.2.2. GeolocationPosition
1.2.3. GeolocationCoordinates
1.2.4. GeolocationPositionError
The JavaScript Geolocation API provides access to geographical location data associated with a user's
device. This can be determined using GPS, WIFI, IP Geolocation and so on.
To protect the user's privacy, it requests permission to locate the device. If the user grants
permission, you will gain access to location data such as latitude, longitude, altitude, and speed. You
will also get the accuracy of the acquired location data and the approximate time when the position
was acquired.
Here are a few uses for geolocation:
The getCurrentPosition() method is used to return the user's position. The example below returns
the latitude and longitude of the user's position:
function displayCurrentPosition() {
navigator.geolocation.getCurrentPosition(function (position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
});
}
1.4. Exercises
(1) Write JavaScript code to retrieve the user's current position using the Geolocation API.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log("Latitude: " +position.coords.latitude +"Longitude: " +position.coords.longitude);
});
} else {
console.log("Geolocation is not supported by this browser.");
}
(2) Write JavaScript code to continuously monitor the user's position and log any changes.
if (navigator.geolocation) {
let watchId = navigator.geolocation.watchPosition(function (position) {
console.log("Latitude: " +position.coords.latitude + "Longitude: " +position.coords.longitude);
});
} else {
console.log("Geolocation is not supported by this browser.");
}
navigator.geolocation.clearWatch(watchId);
console.log("Watching position stopped.");
(4) Write JavaScript code to handle errors that may occur during geolocation retrieval.
function errorHandler(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
(5) Write JavaScript code to convert latitude and longitude coordinates into a human-readable address
(6) Write HTML and JavaScript code to display the user's current location on a map.
<div id="map"></div>
<script>
function initMap() {
navigator.geolocation.getCurrentPosition(function (position) {
const map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: position.coords.latitude,
lng: position.coords.longitude,
},
zoom: 15,
});
const marker = new google.maps.Marker({
position: {
lat: position.coords.latitude,
lng: position.coords.longitude,
},
map: map,
title: "My Location",
});
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
//Replace YOUR_API_KEY with your Google Maps API key
(7) Write JavaScript code to detect when the user's location changes and update the map accordingly.
(8) Write HTML and JavaScript code to display a route between two locations on a map.