Get current location Latitude and Longitude in HTML 5 – Tutorial!

html5-geo

This post is about to teach you how to get the latitude and longitude of the current location!. Its pretty simple in HTML 5. You actually don’t need any 3rd party API’s to get the current location instead you are going to use Web API.

HTML 5 got some amazing stuffs and can be get it done using JavaScript along with that.

But, this script will work only in modern Browsers, don’t expect to work in old browsers, that’s a waste of time.
And one more thing, keep in mind!. This script needs a Server to Run!!. Any servers IIS or Apache etc.,

getCurrentPosition is the method that we are going to use in our JavaScript

Syntax

Three parameters:

success, error, options – where success is the mandatory parameter here, the other two are optional.

I don’t want to bore you explaining what are these parameters do!!.
If you wish to read about those you can go to the mozilla developer website and check it out:
https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition#PositionError

Lets start the coding part:

This script tells you whether geolocation is supported in the browser or not:

And here is the JavaScript part which will get you the Latitude and Longitude:

In the above code: position is the Object and coords, latitude, longitude, accuracy are the properties.

And here is your expected part, the Entire code to test it yourself 🙂

NOTE: When you run this code, Your browser will ask you whether to Allow this script to get the current location or not. Please click ‘Allow’ to Run this script!

Moreover here is the demo link:

Demo

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *