Sunday, 20 July 2014

Modernizr Series: Detect HTML5 Geolocation support


Looking at your positive response towards our Geolocation tutorials on Stronia. I've decided to extend you're knowledge of Geolocation by making a tutorial on detecting HTML5 Geolocation support using modernizr.

Quoting modernizr: "Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user’s browser."

Modernizr logo
Modernizr to the rescue!
In our previous tutorial about Geolocation we learned everything it can do for us including how to test Geolocation support. Then why do we need Modernizr?

Well, in short, Modernizr is meant for testing whether some HTML5 API is supported by the browser or not, so it's a kind of a specialist in doing that.

Why do I say that? Well, here's a list of companies that use Modernizr to detect browser support:
  • Twitter
  • Google
  • Microsoft
  • The Economist
  • About.com
  • theknot.com
  • GOOD.is
  • Posterous.com
If you have intentions of working with Twitter, Google or Microsoft or any the above mentioned companies, you should know to use Modernizr or else you'll be blank there.

You could just as-well stick to the good old navigator.geolocation way of testing support, but if you want to learn something new and you want to use the specialist to detect browser support, here you go!

Getting Modernizr

All you have to do is, go to modernizr.com, go to the download section and uncheck everything except Geolocation in the Misc. section, click on generate and copy the code.

After that, you can just create a new file called 'modernizr_geolocation.js' or something and paste the code in your file.

Detecting Geolocation Support

The first thing you'll have to do to test Geolocation Support in your HTML5 app is to import the source for Modernizr that you just pasted into your file.
<script src="modernizr_geolocation.js"></script>

Now, to the meat of this tutorial,  detecting Geolocation support!

This is as simple as:
if(Modernizr.geolocation){
    // The browser supports Geolocation 
}else{
    // Oops... Bad luck... 
}

Well, that's pretty much it for this tutorial! 

No comments:

Post a Comment