3.3 Usage of The Geolocation API

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

JavaScript

Learning outcome1:

Use Fundamental Features of JavaScript

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

The Geolocation interface doesn't inherit any method.

 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()

Removes the particular handler previously installed using watchPosition().

1.2.2. GeolocationPosition

Represents the position of a user. A GeolocationPosition instance is returned by a successful call to


one of the methods contained inside Geolocation, inside a success callback, and contains a
timestamp plus a GeolocationCoordinates object instance.

1.2.3. GeolocationCoordinates

Represents the coordinates of a user's position; a GeolocationCoordinates instance contains


latitude, longitude, and other important related information.

1.2.4. GeolocationPositionError

A GeolocationPositionError is returned by an unsuccessful call to one of the methods contained


inside Geolocation, inside an error callback, and contains an error code and message.

1.3. What Is the Geolocation API?

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:

 Show user's position on a map


 Get up-to-date local information
 Show local Points-of-interest (POI) near the user
 Enable Turn-by-turn navigation (GPS)
 Track a fleet or delivery vehicle
 Tag photographs with a location

1.3.1. Using the Geolocation API

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.");
}

(3) Write JavaScript code to stop watching the user's position.

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

function reverseGeocode(lat, lon) {


fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lon}`)
.then((response) => response.json())
.then((data) => console.log("Location: " + data.display_name))
.catch((error) => console.error("Error fetching location:", error));
}
// Example usage
reverseGeocode(40.7128, -74.006);

(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.

You might also like