Introducing Geolocation in your PWAs

Onejohi
5 min readFeb 27, 2018

For those who are in darkness and need a little light, a PWA is a progressive web app (PWA). Progressive WebApps are all the rage now, and it seems with the advent of fantastic frameworks like Ruby on Rails, Angular5, VueJS and React just to mention a few, Web Development will never be the same.

A PWA can access capabilities that were previously only accessible to native source codes. Things like the battery, geo location, camera, vibrator (not what you’re thinking lol), notifications panel and so much more. Such capabilities are needed in today's websites to give users a look and feel that can only match native experiences.

So why would you want to add geolocation capability on your site? Analytics. This is a very important matter that a lot of developers overlook. Once you’re done with your site, you may need to know where your clients actually reside or access your site from so as to offer them better services. Getting the user geographical position can compromise on his/her privacy so it’s impossible to access their location if the user doesn’t approve it. Geolocation is also used to track up-to-date local information, turn-by-turn GPS navigation to guide your users to a specific location or show points of interest that exist within the user’s reach.

Upon entry into your site, users will be presented with a popover much like the one below asking if your site can access their location, if they do not trust your site they may revoke the permission and there’s simply nothing you can do about it.

w3schools try it option where you can allow or block the request.

Browser support

A lot of browsers support this recent feature and these include Chrome, Edge, Firefox, Safari and Opera. In IE, you’ll have to battle a few configurations to make it work and I always believe it’s seriously not worth it coz, who uses IE anyways??

Something to note is that as from Chrome version 50.0, Geo Location is only supported over a secure connection that implements an SSL layer (HTTPS). Geo Location will not work over non-secure origins such as HTTP.

Getting a users geographic position

You need a solid understanding of JavaScript to work with Geo Location as it is implemented in JS. Here is the code you require to log out the user position onto the console.

//function that gets the location and returns itfunction getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geo Location not supported by browser");
}
}
//function that retrieves the position
function showPosition(position) {
var location = {
longitude: position.coords.longitude,
latitude: position.coords.latitude
}
console.log(location)
}
//request for location
getLocation();

The above code will output your coordinates. Just tap the F12 key or right click inside your browser and select the element inspector or developer tools. Here is my end result from my browser console.

To prove how accurate it is, I actually entered my location on google and searched for them and the results were conclusive. I am currently located at Vision Towers, Muthithi Road, Westlands. The blue dot you see centrally placed on the map below is my actual location.

Pretty awesome, right…? Yeah I know.

Errors

We all hate having to handle these little bastards that pop up when you least expect them. Error handling is something I always hate having to do, it’s tiresome, mind bending and requires a lot of attention to detail. It also involves you trying to be a user and doing the dumbest things users do to see if your scripts will crash. Or the smartest things users can do to “hack” or compromise your app.

A bunch of errors can pop up when trying to get the location of a user, a user can deny access of location which throws a PERMISSION_DENIED error. The position of a user is not always available as not all devices are equipped with GPS capability hence the app will throw a POSITION_UNAVAILABLE exception. Slow connections can also be a bummer as your app will throw a TIMEOUT exception if the connections are lagging too slow. There’s also a “universal” error handler for geolocation when the computer has no idea what’s the issue, this tends to throw an UNKNOWN_ERROR exception. To handle these errors you can add the following code block to your getLocation() function.

function locationError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
return "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
return "Location information is unavailable."
break;
case error.TIMEOUT:
return "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
return "An unknown error occurred."
break;
}
}

Using Maps

Here’s another scenario, what if I want to make a site that pinpoints the location of a user and shows it either in his map or mine? Google Maps is the way to go. Google maps has a unique URL that let’s you add coordinates parameters directly into it and display the coordinates in a map. You will however need an API key for authentication where you can easily get one by creating a Google Developer Account here. In the code example below, I used the latitude and longitude to show the location on a map using a static image.

function showInMap(pos) {
var latlon = pos.coords.latitude + "," + pos.coords.longitude;

var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_:KEY";
var map = document.querySelector("mapholder");
map.innerHTML = "<img src='"+img_url+"'>";
}

Finally, the Geolocation object.

The navigator class contains a geolocation object that has two more interesting methods that you can manipulate. The first is the watchPosition() method. This method accepts one parameter that carries the position of the user. The method then acts like an observer where it “watches” the user and “tracks” them as they actively navigate and constantly updates you (the function that called it). This can be helpful in tracking car movements or users in departments like sales and delivery. The second parameter is the clearWatch() that stops the watchPosition() method.

Geolocation works best in devices with GPS like iPhones and most of today’s smartphones.

--

--

Onejohi

Creative 🚀 | Gamer 🎮 | Web & App developer 💻📱 | Graphics Designer 📏📝 | Entrepreneur 💶 | Cool AF 😎🤓 https://onejohi.com | WhatsApp +254727321766