HTML Geolocation API

In this article, we will be discussing over HTML geolocation . Location is determined by using the HTML Geolocation API.

Track User’s Position:

The HTML Geolocation API is used to obtain a user’s geographical location.

Due to privacy concerns, positions are only available if the user authorizes them.

Important: Smartphones with GPS provide the most precise geolocation.



Implementing HTML Geolocation

To get the user’s location, call the getCurrentPosition() method.

The user’s latitude and longitude can be obtained using the following example:

The following is an example of an HTML geolocation:

Example: 

<!DOCTYPE html> <html><body><br><br><br><br><p>Click the button to get your coordinates.</p><br><br><button onclick="getLocation()">Try It</button><br><br><p id="demo"></p><br><br><script><br>var x = document.getElementById("demo");<br><br>function getLocation() {<br> if (navigator.geolocation) {<br> navigator.geolocation.getCurrentPosition(showPosition);<br> } else { <br> x.innerHTML = "Geolocation is not supported by this browser.";<br> }<br>}<br><br>function showPosition(position) {<br> x.innerHTML = "Latitude: " + position.coords.latitude+<br>"Longitude: " + position.coords.longitude;<br>}<br></script><br><br><br> </body></html>

Example Explanation

  • Verify that Geolocation is supported.
  • If supported, call getCurrentPosition(). Display an error message if not.
  • A coordinates object will be returned if the getCurrentPosition() method is successful.
  • It prints out the longitude and latitude resulting from the showPosition() function.
Tip: A basic HTML geolocation script is shown above without error handling.

Displaying Outcome on Map

A map service, like Google Maps, is needed to view the results when it comes to HTML geolocation.

Here’s an example of using latitude and longitude to show the location on a Google Map (using a static image):

Example: 

<!DOCTYPE html> <html><body><br><br> <br> <title>Displaying Outcome on Map</title><br> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKtH6rX_O-dwNY-e6pXkOoPCXsVuiB7xg"></script><br> <script><br> function initMap() {<br> // Define the coordinates for the outcome<br> var outcome = {lat: 37.7749, lng: -122.4194};<br> <br> // Create a map centered on the outcome<br> var map = new google.maps.Map(document.getElementById('map'), {<br> zoom: 12,<br> center: outcome<br> });<br> <br> // Add a marker at the outcome location<br> var marker = new google.maps.Marker({<br> position: outcome,<br> map: map,<br> title: 'Outcome'<br> });<br> }<br> </script><br> <br> <br> <div id="map" style="height: 400px;"></div><br> <br> </body></html>

Managing Errors and Rejections

Errors are handled by the second parameter of getCurrentPosition(). If it cannot obtain the user’s location, it runs the following function:

Example: 

<!DOCTYPE html> <html><body><br><br><br><br><p>Click the button to get your coordinates.</p><br><br><button onclick="getLocation()">Try It</button><br><br><p id="demo"></p><br><br><script><br>var x = document.getElementById("demo");<br><br>function getLocation() {<br> if (navigator.geolocation) {<br> navigator.geolocation.getCurrentPosition(showPosition, showError);<br> } else { <br> x.innerHTML = "Geolocation is not supported by this browser.";<br> }<br>}<br><br>function showPosition(position) {<br> x.innerHTML = "Latitude: " + position.coords.latitude + <br> " Longitude: " + position.coords.longitude;<br>}<br><br>function showError(error) {<br> switch(error.code) {<br> case error.PERMISSION_DENIED:<br> x.innerHTML = "User denied the request for Geolocation."<br> break;<br> case error.POSITION_UNAVAILABLE:<br> x.innerHTML = "Location information is unavailable."<br> break;<br> case error.TIMEOUT:<br> x.innerHTML = "The request to get user location timed out."<br> break;<br> case error.UNKNOWN_ERROR:<br> x.innerHTML = "An unknown error occurred."<br> break;<br> }<br>}<br></script><br><br><br><br> </body></html>

Geographic information

The purpose of this page is to explain how to provide a map of a user’s location.

Location-specific information can also be obtained with geolocation, such as:

  1. Real-time local information
  2. Displaying points of interest nearby
  3. Location-based navigation (GPS)

The getCurrentPosition() Method – Return Data

In all cases, latitude, longitude, and accuracy are retrieved. On success, the getCurrentPosition() method returns an object. If available, other properties are returned as well:

PropertyReturns
coords.latitudeA decimal number representing the latitude (always returned).
coords.longitudeA decimal representation of the longitude (always returned).
coords.accuracyPosition accuracy (always returned).
coords.altitudeReturns the altitude above mean sea level in meters (if available).
coords.altitudeAccuracyAltitude accuracy of position (returned if available).
coords.headingA heading expressed in degrees clockwise from North (returned if available).
coords.speedReturns the speed in meters per second (if available).
timestampResponse date/time (if available).

Geolocation Object – More interesting Methods

Geolocation object also offers the following exciting methods:

  • watchPosition() – Finds the user’s location and updates it as the user moves (similar to a GPS in a car).
  • clearWatch() – Disables the watchPosition() method.

WatchPosition() is illustrated in the example below. To test this, you will need an accurate GPS gadget (such as a smartphone):

Example

<!DOCTYPE html> <html> <body> <p>The coordinates of your location can be obtained by clicking the button.</p> <button onclick="getLocation()">Try It</button> <p id="coordi"></p> <script> var a = document.getElementById("coordi"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else { a.innerHTML = "In this browser, geolocation is not compatible."; } } function showPosition(position) { a.innerHTML="Latitude: " + position.coords.latitude + "Longitude: " + position.coords.longitude; } </script> </body> </html>

Browser Compatibility

According to the table, the first browser version to provide geolocation is listed below.

API
Geolocation5.0 – 49.0 (http)
50.0 (https)
9.03.55.016.0

Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

Important: The Geolocation API will only operate in secure connections such as HTTPS as of Chrome 50. Requests to retrieve the user’s location will no longer work if your site is hosted on an insecure origin (such as HTTP).

Benefits of using HTML Geolocation

HTML geolocation is a feature that allows websites to identify the physical location of a user through their web browser. There are several benefits to using HTML geolocation:

  • Personalization: With geolocation, websites can provide personalized experiences for users based on their location. For example, a retail website can offer location-based promotions and discounts to users in a specific region.
  • Targeted Advertising: Geolocation can be used by advertisers to target users with relevant ads based on their location. This can increase the effectiveness of ad campaigns and improve the user experience by showing ads that are relevant to the user’s interests and needs.
  • Improved User Experience: Geolocation can be used to provide users with relevant information based on their location, such as local weather updates, nearby restaurants, or events. This can enhance the user experience and make the website more useful and engaging.
  • Location-Based Analytics: Geolocation data can be used to gain insights into user behavior and preferences based on their location. This information can be used to optimize website design, content, and marketing strategies.
  • Increased Security: Geolocation can be used as a security feature to prevent unauthorized access to sensitive information. For example, a website can require users to confirm their location before allowing them to access certain features or information.

If you find this article informative, do subscribe to our Newsletter below in order to get connected with the latest technical information on this site.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *