Get current location of user using jQuery

Geolocation API is an important feature available in modern HTML5 web browsers, which allows us to request current location of the user using JavaScript, the location information is represented by latitude and longitude coordinates. For privacy reasons, the user permission is required to access its location information.

Browser Support

  • 9+
  • 5+
  • 44+
  • 5+
  • 36+
For more details here.

JavaScript and Geolocation

In our JavaScript, we can use getCurrentPosition() method to obtain user's current location, but first we need to know whether Geolocation API is available in browser before we can continue.
JS
  • 1
  • 2
  • 3
  • 4
  • 5
if ("geolocation" in navigator){ //check Geolocation available //things to do }else{ console.log("Geolocation not available!"); }
Now we can obtain the location of the user like so :
JS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
if ("geolocation" in navigator){ //check geolocation available //try to get user current location using getCurrentPosition() method navigator.geolocation.getCurrentPosition(function(position){ console.log("Found your location \nLat : "+position.coords.latitude+" \nLang :"+ position.coords.longitude); }); }else{ console.log("Browser doesn't support geolocation!"); }

jQuery

Once we know how to get the current location of the user, we can implement this JavaScript code in our jQuery click method.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
$("#find_btn").click(function () { //user clicks button if ("geolocation" in navigator){ //check geolocation available //try to get user current location using getCurrentPosition() method navigator.geolocation.getCurrentPosition(function(position){ $("#result").html("Found your location <br />Lat : "+position.coords.latitude+" </br>Lang :"+ position.coords.longitude); }); }else{ console.log("Browser doesn't support geolocation!"); } });
HTML
  • 1
  • 2
<button id="find_btn">Find Me</button> <div id="result"></div>

jQuery & Google Map JavaScript API

Here's how you can incorporate Google map into your JavaScript code.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
<script type="text/javascript"> var map; function initMap() { var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates map = new google.maps.Map($("#map")[0], { center: mapCenter, zoom: 8 }); } $("#find_btn").click(function (){ if ("geolocation" in navigator){ navigator.geolocation.getCurrentPosition(function(position){ infoWindow = new google.maps.InfoWindow({map: map}); var pos = {lat: position.coords.latitude, lng: position.coords.longitude}; infoWindow.setPosition(pos); infoWindow.setContent("Found your location <br />Lat : "+position.coords.latitude+" </br>Lang :"+ position.coords.longitude); map.panTo(pos); }); }else{ console.log("Browser doesn't support geolocation!"); } }); </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
HTML
  • 1
  • 2
<button id="find_btn">Find Me</button> <div id="map"></div>

Error Handling

To handle any errors, we can use second parameters of getCurrentPosition(). If anything fails, it will invoke the error callback, letting us update the user with corresponding error message. Let's break it down a bit for your understanding.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
<script type="text/javascript"> var map; function initMap() { map = new google.maps.Map($("#map")[0], { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); } $("#my_location").click(function (){ //user click on button if ("geolocation" in navigator){ navigator.geolocation.getCurrentPosition(show_location, show_error, {timeout:1000, enableHighAccuracy: true}); //position request }else{ console.log("Browser doesn't support geolocation!"); } }); //Success Callback function show_location(position){ infoWindow = new google.maps.InfoWindow({map: map}); var pos = {lat: position.coords.latitude, lng: position.coords.longitude}; infoWindow.setPosition(pos); infoWindow.setContent('User Location found.'); map.setCenter(pos); } //Error Callback function show_error(error){ switch(error.code) { case error.PERMISSION_DENIED: alert("Permission denied by user."); break; case error.POSITION_UNAVAILABLE: alert("Location position unavailable."); break; case error.TIMEOUT: alert("Request timeout."); break; case error.UNKNOWN_ERROR: alert("Unknown error."); break; } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCw-Viepxab4m9pRRQyjm_yRq1uhOj9iPc&callback=initMap" async defer></script>
HTML
  • 1
  • 2
<button id="my_location">Find Me</button> <div id="map"></div>
In the third parameter of getCurrentPosition(), the enableHighAccuracy attribute tries to provide best results, but this may cause slower response and can increase the power consumption of the device.

Conclusion

Geolocation can be used in many different ways, it can be used to store location info of pictures taken in various points, pinpoint exact location of a lost user in unfamiliar city or update user location on social media sites. But you should also be aware that the implementation of Geolocation varies device to device, some support this feature and others don't, the result entirely depends on hosting device and accuracy is not guaranteed!You should also be very responsible when using one's location data, since it discloses the location of the user, thereby potentially compromising the user's privacy. It's always a good idea to setup HTTPS on your website before making geolocation API requests. Goodluck!