Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
HTML GeoLocation | JavaScript HTML5 APIs
HTML & JavaScript Interactivity for Beginners
course content

Course Content

HTML & JavaScript Interactivity for Beginners

HTML & JavaScript Interactivity for Beginners

1. DOM and HTML Manipulation
2. DOM Event Handling and Forms
3. JavaScript HTML5 APIs
4. Beginner Projects with HTML + JavaScript

bookHTML GeoLocation

HTML 5 Geolocation API (Application Programming Interface) is a browser API that gets your device's geographic coordinates (Latitude and Longitude). Thus it assists in detecting the user's geolocation or user on a website or a mobile app. Now let's find out how to get your geolocation using the interface's methods.

How to get your Geolocation?

First, you need to check if your browser supports the geolocation property. So here’s the code to find your current geolocation with a click of a button.

html

index

css

index

js

index

copy

Explanation of the above code:

  • The code first checks if the user's browser supports the geolocation;
  • If it supports, it calls the getCurrentPosition method by passing the callback function as an argument. If not, the code displays an error message to the user;
  • In a successful scenario, the callback function displays the latitude and longitude of your current location.

Handling Errors and Rejections in Geolocation API

Getting users' geolocation can be complicated, as there could be circumstances where the API cannot locate the precise location or timeout issues. So, in such cases, the code needs to catch and display them in a user-friendly manner. Let's find out how.

As you already know, the getCurrentPosition() has one parameter: the callback function to display the results. There is also another optional parameter which is the callback function, to handle the errors. Here is a code example:

html

index

css

index

js

index

copy

The other methods of Geolocation API to Look out for

  • watchPosition() - returns the user's current position and continues to return the updated position as the user doesn't remain stationary(similar to how you use a GPS in a car);
  • clearWatch() - clears the watchPosition() method.
Which method(s) get your current geolocation?

Which method(s) get your current geolocation?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 1
some-alt