JavaScript30 - Day 21 (Geolocation)

This is day 21 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.

Yesterday we explored Native Speech Recognition. You can keep track of all the projects we're building here.

Today we're exploring geolocation.


Day 21 - Geolocation

Again, our web app will need to ask the users permission to access their data. This makes sense. For this project we are accessing their exact location. Don't want some evil dude to know where our users are (without their permission).

So we will need to run this via a local server (rather than opening the HTML file up in the browser). We are using browser-sync for this example.

Browser Sync ships with a self-signed certificate which allows us to access https via our localhost.

We're going to be using the Geolocation API to create a compass that not only guides us towards North but also show us how fast we are travelling.

Compass

Hooking up the Compass

First up, we need to chuck some event listeners in so that we can select the arrow in the compass & the 'km/h' speed. Both of these need to update based on the users location and speed:

<script>  
    const arrow = document.querySelector('arrow')
    const speed = document.querySelector('speed-value')
</script>  

Next up, we have to access the users location.

We will use geolocation. There are two methods that we could access Geolocation.getCurrentPosition() or Geolocation.watchPosition().

We are going to use watchPosition() because we want multiple updates (not just the one location).

This will return data about the users current location:

Position {  
  coords: {
    accuracy: 5
    altitude: null
    altitudeAccuracy: null
    heading: 320.62
    latitude: 37.40432366
    longitude: -122.18655336
    speed: 33.89
  }, 
  timestamp: 1504759013739
}

As you can see some of the data can be returned as null. So we will need to account for that when we use it in our project.

navigator.geolocation.watchPosition(  
  data => {
    //If we have the users speed then update the speed shown
    data.coords.speed ? (speed.textContent = data.coords.speed) : false
    //Rotate the arrow based on the datas heading
    arrow.style.transform = `rotate(${data.coords.heading}deg)`
  }
)

The final thing we need to do is log an error if the user doesn't allow us access to their location:

navigator.geolocation.watchPosition(  
  data => {
    //If we have the users speed then update the speed shown
    data.coords.speed ? (speed.textContent = data.coords.speed) : false
    //Rotate the arrow based on the datas heading
    arrow.style.transform = `rotate(${data.coords.heading}deg)`
  },
  err => {
    console.log(err)
    alert("Hey, you haven't allowed us access to your location.")
  },
)

Now we have a working compass and geolocator.

You can play around with the compass here.

You can keep track of all the projects in this JavaScript30 challenge here.