In this article I’ll show you how you can use the HTML5 Geolocation API in order to get user’s location.
Here is the HTML5 boilerplate code (location.html) :
<!doctype html> <html> <head> <meta charset="utf-8"> <title>HTML5 Geolocation API.</title> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script> <script src="location.js"></script> </head> <body> <p>Location :</p><div id="locationMessage"></div> </body> </html>
Here is the Geolocation Javascript code (location.js) :
$(document).ready (function () { var locationMessage = $("#locationMessage"); if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition ( function (position) { var longitude = position.coords.longitude; var latitude = position.coords.latitude; locationMessage.text ("Lat: " + latitude + ", Lng: " + longitude); }, function (error) { var errorTypes = { 0: "Unknown error", 1: "Permission denied by user", 2: "Position is not available", 3: "Request timed out" }; var errorMessage = errorTypes[error.code]; if (error.code == 0 || error.code == 2) { errorMessage += (": " + error.message); } locationMessage.text (errorMessage); }); } else { locationMessage.text ("Geolocation support is not available."); } });