Find Your Position With HTML5 Geolocation

Find Your Position With HTML5 Geolocation

Hello Reader,

This is very exciting feature of HTML5 like Drag and Drop features of html5. With the help of html5 geolocation API, we can track user’s position or plot the user’s location on map based on the latitude and longitude coordinates.

Find Your Position With HTML5 Geolocation #html5 #geolocation Click To Tweet

HTML5 Geolocation

HTML5 Geolocation API lets you share your location with your favorite websites. For getting the user’s position, getCurrentPosition() method is used.

The below javascript code returns the latitude and longitude of the user’s position:

In the above example:

  • We are checking whether the geolocation is supported by the browser or not.
  • If it is supported then run the getCurrentPosition() method else display a message to the user saying – “Geolocation is not supported by this browser”.
  • Further, if the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (displayPosition).
  • The displayPosition() function outputs the Latitude and Longitude.

Note: The example above is a very basic Geolocation script, with no error handling.


Error Handling:

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user’s location:

To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

Geolocation is also very useful for location-specific information like:

  • Up-to-date local information
  • Showing POIs (points-of-interest) near the user
  • Turn-by-turn navigation (GPS)

⇒ HTML5 Geolocation Example

Note: Turn on your location service and allow the prompt when asked. Otherwise, it won’t work.

For me, it worked on IE and Firefox. However, it wasn’t working with chrome browser. I didn’t get the issue but will try to find it out why it is not working with chrome browser.

Learn Design!

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Reading!