DEV Community

Cover image for Retrieving Client’s Current Position in the Browser
Eric
Eric

Posted on • Updated on

Retrieving Client’s Current Position in the Browser

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. 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! Here's a screenshot of how it currently looks.

Image description

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 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:

navigator.geolocation.getCurrentPosition( position => {
    console.log(position.coords));
}
Enter fullscreen mode Exit fullscreen mode

You should see this familiar pop-up:

Request permission for user's location data

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

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:

function error(error) {
    console.error(error);
}
Enter fullscreen mode Exit fullscreen mode

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 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 amazing free API's for getting weather forecasts. All I needed was a valid latitude & longitude, and with one call (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:

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);
}
Enter fullscreen mode Exit fullscreen mode

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 and his amazing video, JavaScript and Geolocation. The other is from one of my other favorite channels, The Coding Train and his wonderful video, 2.2 Geolocation Web API - Working with Data and APIs in JavaScript. 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


Credits

Top comments (0)