Retrieving Client’s Current Position in the Browser
Tags: javascript, geolocation, navigator, beginners
Published: 2021-10-30 01:36:58

One of the projects that comes up in just about every YouTube video with a title like, “10 projects every beginner should make,” is a weather app. It’s a project that requires making a request for weather data from an API and displaying said data in the DOM. It’s actually the first real project I've attempted and it's the final project for phase one of my coding bootcamp. It helped me to learn the Fetch API and asynchronous JavaScript. I would definitely recommend it.

I wanted my weather app to automatically fetch and display the weather for the client’s current position, on page load. Learning to do so also taught me how to use the browser’s built in **Navigator** object to retrieve the latitude & longitude for the user's device. I thought it was pretty cool, so I wanted to share with y'all how I did it.

If you would like to check out my weather app, you can find it in GitHub, [here](https://github.com/theFlexOne/project-1-weather-app). As of being published, I'm nowhere close to being done building the app. It successfully fetches data from three separate external APIs, but there is much work to do, still, on the frontend. Let me know what you think! Like I said, it's the final project for the first phase of my coding bootcamp, so feel free to give me some feedback on [GitHub!](http://www.github.com/theflexone) Here's a screenshot of how it currently looks.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mlwchnv8xm20jfyzs6z7.png)

Note: You will need to generate your own API keys from openweathermap.org and console.developers.google.com/ if you would like to see it in action. I'm currently learning how to deploy the app on netlify.com, and I will post a link to the finished app when it's ready.

---

## **What is the *Navigator* Object?**

According to MDN:

> The **Navigator** interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

So, that’s clear enough... Honestly, I don’t really know what the Navigator object is. As far as I can tell, from perusing the MDN page on it, it’s a global(window) object that contains all kinds of information about the client’s device, like information about the network connection or the device’s battery life. It also contains the `navigator.geolocation` property, which is an object we can work with to obtain the latitude & longitude of the user's device.

To do this, we’ll use the **Geolocation** object’s built-in method “getCurrentPosition” (`navigator.gelocation.getCurrentPosition`). After this, check out the other properties of the [**Navigator**](https://developer.mozilla.org/en-US/docs/Web/API/Navigator) object, as well. They’re pretty cool.

If you pull up the console in the browser, you can enter the following code to retrieve your current position:

```javascript
navigator.geolocation.getCurrentPosition( position => {
    console.log(position.coords));
}
```

You should see this familiar pop-up:

![Request permission for user's location data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnurhzyzvenvub96v6gm.jpg)

Pretty cool right? It was to me, at least, when I first made this alert happen. My alert says it's from *www.google.com*, because that was the website I was currently at when I entered the above code into the console.

---

### **A Quick Aside**

Whatever you do with the user’s location data is 100% up to you. I do, however, want to emphasize the importance of using this data ethically. Obviously, we are just fiddling around here and not creating the next Facebook or Google, but, also, don’t trick anyone into using your app, just to get them to opt-in and give away their location (I was brainstorming ways to use what I’m demonstrating unethically, and that’s the best I could come up with).

Finally, ignorance does not excuse you from unethical behavior, so always be aware of the ethical implications of whatever you happen to be making at whatever company you happen to work for.

---

### **Back to the Code**

Click “Allow” to give yourself permission to know your own location and you should see this in your console:

![console log with latitude & longitude](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otpu99zhum65v5aogai2.png)

As you can see, a **GeoLocationCoordinates** object is logged with the latitude & longitude. Feel free to google those coordinates to check if it’s accurate.

---

## **Breaking it Down**

First off, the **Navigator** object is a property of the **Window** object, in the browser, similar to the **Document** object. It’s a global object, so we can just type `navigator` instead of `window.navigator`.

Inside `navigator.geolocation` lives the method **getCurrentPosition** (`navigator.geolocation.getCurrentPosition`). That’s the part of this code that actually does anything.

`getCurrentPosition` is an asynchronous function that takes in 1 _required_ argument and 2 _optional_ arguments.

The first argument is a callback function that executes once the location information is retrieved - this is where you have access to the location information and can choose what to do with it. Because it’s asynchronous, any code you want to execute afterwards is put inside this function, much like a regular fetch call chained with `.then()`. 

It takes one argument, a **GeolocationPosition** object. **GeolocationPosition** objects have only two properties: `coords` & `timestamp`. Above, in the code we ran inside the console, we logged the `coords` objects. Check out the second image and you'll see the `latitude` & `longitude` of the **GeolocationCoordinates** object `getCurrentPosition.coords` returned.

The second argument is another callback function that handles any errors while trying to retrieve the location information. It would normally look something like this:

```javascript
function error(error) {
    console.error(error);
}
```

Finally, the third argument is an object where you can specify certain options. I won’t be going over the options object at all, since I’ve never used it myself, but the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) explains all about it, if you want to check it out.

---

## **How I Used the Latitude & Longitude**

For my weather app, I used one of [OpenWeather's](http://www.openweathermap.org/api) amazing free API's for getting weather forecasts. All I needed was a valid latitude & longitude, and with one call ([One Call API](https://openweathermap.org/api/one-call-api)) I was able to get all the weather data I needed for a basic weather app. I destructed the lat & lon from the **GeolocationPosition** object returned from `getCurrentPosition`, and sent it away to OpenWeather.

Here's what the final code looks like:

```javascript
function getLatLon() {
    navigator.geolocation.getCurrentPosition(success, error)
}

function success(position) {
    const {latitude: lat, longitude: lon} = position;
    fetchWeather(lat, lon);
}

function error(error) {
    console.error(error);
}
```

`fetchWeather` is a function I made myself that actually makes the fetch call to OpenWeather.

---

## **I Guess That's All**

And that's how I did it. It was a super fun experience, figuring out how to do this, and I'm glad I could share it with someone else. There are two YouTube videos, in particular, that were instrumental in helping me understand this topic. The first is from my favorite channel for learning anything JavaScript, [Steve Griffith - Prof3ssorSt3v3](https://www.youtube.com/c/SteveGriffith-Prof3ssorSt3v3) and his amazing video, [JavaScript and Geolocation](https://www.youtube.com/watch?v=NIAqR34eg7I). The other is from one of my other favorite channels, [The Coding Train](https://www.youtube.com/user/shiffman) and his wonderful video, [2.2 Geolocation Web API - Working with Data and APIs in JavaScript](https://www.youtube.com/watch?v=3ls013DBcww). Thanks for reading!

---

## **Before You Go**

It's been 213 days since I first started learning how to code (from 3-30-21) and I'm coming up on the conclusion to phase one of five for my coding bootcamp, Flatiron. This is my first technical blog post (2nd ever) and, in fact, is a prerequisite to moving onto phase two (my weather app, mentioned at the top, is the biggest prerequisite). These last few months, since I started this journey, have been the best. I'm grateful to have stumbled onto something that, already, means so much to me.

I very serious about being the best programmer, period, so I'm completely open to, and encourage, constructive criticism, as long as it's well meant. And, of course, if anything I write is incorrect or if I failed to mention a critical piece of information, please let me know as well! I sincerely appreciate you reading this whole post. Thank you.

---

### **References and Resources**

- [MDN](https://developer.mozilla.org/)
  - [Navigator](https://developer.mozilla.org/en-US/docs/Web/API/Navigator)
  - [Geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation)
  - [`getCurrentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition)
  - [GeolocationPosition](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition)

---

#### **Credits**

- cover image from [browserstack](https://www.browserstack.com/blog/geolocation-takes-over-the-power-of-testing-websites-and-mobile-apps-around-the-world/)