In this blog post, you will learn how to get current location google maps javascript using your browser’s HTML5 Geolocation feature along with the Google Maps JavaScript API.
Note: The current location of a user will only display when you allow location sharing as shown below:-

- Keep reading on Calculate distance between two points Google Maps JavaScript, How to get location from ip address
Get current location Google Maps
The geolocation coordinates specify the geographic location of the device. Go to https://console.developers.google.com and get a free API key for Google Map. Add this key to the code to work Geolocation with it.
You can find the below code snippet to show the current location using Html5 Geolocation with Google Maps.
<!DOCTYPE html> <html> <head> <title>Get current location google maps javascript</title> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> // Note: This example requires that you consent to location sharing when // prompted by your browser. If you see the error "The Geolocation service // failed.", it means you probably did not give permission for the browser to // locate you. var map, infoWindow, marker; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: { lat: 28.635, lng: 77.208 }, zoom: 6 }); infoWindow = new google.maps.InfoWindow; // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infoWindow.setPosition(pos); infoWindow.setContent('Your current location is here.'); infoWindow.open(map); map.setCenter(pos); }, function () { handleLocationError(true, infoWindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); } } function handleLocationError(browserHasGeolocation, infoWindow, pos) { infoWindow.setPosition(pos); infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.'); infoWindow.open(map); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YourAPI&callback=initMap"> </script> </body> </html>
Output

Conclusion
I hope you liked this article on how to get the current location in google maps using javascript. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply