Skip to content
Sign UpLog In
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
3

🌐|| How to use the Geolocation api || Get the users location! || 🌎

EpicGamer007
EpicGamer007

How to use the HTML5 Geolocation api

Get the location of the user!

Here is a great thing I found while researching some HTML

The geolocation api!

Using it, you can find the location of the user, which can be really useful sometimes!

Here is a basic tutorial describing how to use it

Setting up

Let's first create a basic HTML file to present the data

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Geolocation Try</title> <script src="script.js"></script> <link rel="stylesheet" href="style.css"> </head> <body> <h1 id="location">Your Location Will Go here.</h1><br> <h2 id="Accuracy">Accuracy will go here</h2> </body> </html>

and the css:

body{ background-color: rgb(49, 46, 46); color: ghostwhite; text-align: center; font-family: Verdana, Geneva, Tahoma, sans-serif; }

So thats the basic stuff. No geolocation yet. By now, it should look like this:

image

javascript + the geolocation api || The fun stuff

What is the geolocation api and how does it work?

The geolocation api is a built in api in almost all modern browsers which can be used to get the location of the user

It gets the location in 4 ways:

  • IP Address
  • GPS
  • WiFi

And if you are using a mobile device

  • Cell phones(Through cell phone towers)

Unfortunately, we will not be able to know which way the browser is using

Things to know:

  • Don't do anything illegal or anything bad in general with any geolocation api please
  • It should work on repl.it because it serves files from a server
  • If you are serving the page as a file on your computer, it might not work.
  • If you are using a local computer, either use node and start up a server or find a way to use localhost
Steps to host on localhost

This is for vscode users only.

Go to the marketplace and search up Live Server, you should find this:

image

Click install. After it has installed, go to your page(index.html) then on the bottom right, click on Go Live:

image

After that, you have started a live server on localhost and there should be no problems with this!

Anyways, back to the js

Let's go into our js file and start!

The first step is to check if the geolocation api is there:

For our simple project we will create in this tutorial, we will do asign it to window.onload.

window.onload = () => { let h1 = document.getElementById("location"); // So that we can change the location later let h2 = document.getElementById("accuracy"); // So that we can change the accuracy later if(navigator.geolocation){ //If this exists in the browser, yay! }else{ //If the browser does not support geolocation :( alert("No Geolocation support :("); h1.innerText = "No Geolocation support :("; } }

This is an optional step because pretty much all modern browsers will have the geolocation api but it is a good step just in case.

Now that we set up the api, let us start using it!

In this tutorial, we will be going over how to get the latitude and longitude.

I am pretty sure we all know what latitude and longitude is but in case you need an explanation:

Latitude is how far you are from the equator. It goes into the negatives south and positives up.

Longitude is how far you are from the prime meridian. It goes into the negatives west of the prime meridian and into the positives east.

Adding on to our last code snippet

window.onload = () => { let h1 = document.getElementById("location"); let h2 = document.getElementById("accuracy"); if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((position) => { let latitude = position.coords.latitude; // This gets us the latitude let longitude = position.coords.longitude; // This gets us the longitude h1.innerText = "You are at latitude " + latitude + " and longitude " + longitude + "."; // Changes the text of the <h1> to be this string literal }); }else{ alert("No Geolocation support :("); h1.innerText = "No Geolocation support :("; } }

That is it! You have successfully built your first geolocation project!

You are now getting the latitude and longitude of the user!

But what if there is an error. The user can easily stop the browser from tracking your location

image

How do we handle this error?

Easy, add another function to the getCurrentPosition function

Like this:

window.onload = () => { let h1 = document.getElementById("location"); let h2 = document.getElementById("accuracy"); if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((position) => { let latitude = position.coords.latitude; // This gets us the latitude let longitude = position.coords.longitude; // This gets us the longitude h1.innerText = "You are at latitude " + latitude + " and longitude " + longitude + "."; // Changes the text of the <h1> to be this string literal }, (error) => { }); }else{ alert("No Geolocation support :("); h1.innerText = "No Geolocation support :("; } }

Before we go any further, let's define the 4 basic types of errors

  • Error 0: Unknown error
  • Error 1: Permission denied by user
  • Error 2: Position not available - This means that the browser cannot get location at the current time, like if you are not connected to the internet or something
  • Error 3: Request timed out - This means that it took too long trying to get the location so the api quit

Now that we know that, lets go back to our code:

window.onload = () => { let h1 = document.getElementById("location"); let h2 = document.getElementById("accuracy"); if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((position) => { let latitude = position.coords.latitude; let longitude = position.coords.longitude; h1.innerText = "You are at latitude " + latitude + " and longitude " + longitude + "."; }, (error) => { let errorTypes = { 0: "Unknown error", 1: "Permission denied by user", 2: "Position not available", 3: "Request timed out" }; //defining the 4 basic error types let errorMessage = errorTypes[error.code]; // getting the error based on the code if(error.code == 0 || error.code == 2){ //Optional step, usually, the error message for error's 0 and 2 usually provide extra useful information errorMessage += error.message; } h1.innerText = errorMessage; // Set the h1's text to the error message h2.innerText = errorMessage; // Set the h2's text to the error message }); }else{ alert("No Geolocation support :("); h1.innerText = "No Geolocation support :("; } }

That's it! You have made a functioning app with the geolocation api which prints out the users location!

But there is no avoiding it, the api is not perfect.

You can get the accuracy of the api by accessing a simple variable though!

Let's change the js so far.

window.onload = () => { let h1 = document.getElementById("location"); let h2 = document.getElementById("accuracy"); if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((position) => { let latitude = position.coords.latitude; let longitude = position.coords.longitude; h1.innerText = "You are at latitude " + latitude + " and longitude " + longitude + "."; //NEW CODE h2.innerText = "Your location is being mapped with " + position.coords.accuracy + " meters accuracy."; }, (error) => { let errorTypes = { 0: "Unknown error", 1: "Permission denied by user", 2: "Position not available", 3: "Request not available" }; let errorMessage = errorTypes[error.code]; if(error.code === 0 || error.code === 2){ errorMessage = errorMessage + " " + error.message; } h1.innerText = errorMessage; h2.innerText = errorMessage; }); }else{ alert("No Geolocation support :("); h1.innerText = "No Geolocation support :("; } }

if the accuracy variable is lower, that means that the latitude and longitude should be within that many meters

So if it said 500, that means that the latitude and longitude calculated is within 500 meters from where you currently are
If it said 10, that means the calculated latitude and longitude is at most 10 meters away from wher eyou currently are

Ending

Yeah, that is all I have for this tutorial everyone!

I hope this tutorial was helpful for you and you learned many new things!

If this gets enough support(AKA upvotes), I might add a section covering how to use maps along with the api

Until next time,

Hope you enjoyed && Happy coding ;)

Oh yea, This is how your final product should look:

image

(I hid my latitude and logitude)

Edit: For the attached repl to work, open it in a new tab or click here

2 years ago
You are viewing a single comment. View All
1
1
EpicGamer007
EpicGamer007

@OrangeJooce123
. hope this helped!

2 years ago