There are many occasions where you might need to obtain a web visitor’s location details. In this short lesson, I will show you how to get the latitude and longitude of the user’s location.
STEP 1
The first thing to deal with is to set up a basic HTML page. I am using Visual Studio Code which has Emmet installed. It is simply a case of typing in an exclamation mark, !, and pressing the tab or enter key.
STEP 2
Change the title on Line 7 to something relevant e.g. Location Data.
Also, since we will be using jQuery, let’s grab the CDN location of the jQuery library and add this to the HEAD of the page as follows:
STEP 3
We will now set up a button that, when pressed, will grab the user’s location.
STEP 4
Now we will set up a div that will show the location data.
STEP 5
We will now add the jQuery code to grab the user’s location data. Note, this code has been stripped back to the bare minimum.
Let’s go through the lines of code.
Line 20: if the button is clicked then we run a function
Line 21: check if the navigator geolocation function is able to be used in the browser
Line 22: get the longitude and latitude
Line 24: present a message if the browser does not support geolocation
Line 28: define the locationSuccess function
Line 29: define the latitude variable
Line 30: define the longitude variable
Line 31: update the locationData div with the location data
STEP 6
We will now add a Google map to show the user’s location.