Blog about, How to display your current Geo Location (Real time fetch from your browser) on Google Map.
First of all, You will need below points to be ready.
– Google API key
– Secure server URL with https.
Live Demo (This demo will not work on Google Chrome because URL is not fulfill with 2nd point)
Lets start code now…
1) Make map div for display map
<div id=”map” style=”width:1100px;height:450px;background:yellow;margin: 50px auto;”></div>
2) Make error div for display error if any
<div id=”error”></div>
3) Add Google Map library with your Google API key.
<script src=”https://maps.googleapis.com/maps/api/js?key=APIKEY” async defer></script>
4) Add below JavaScript code
<script> getLocation(); //For get permission to fetch Geo location from your browser. var x = document.getElementById("error"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { x.innerHTML = “Geolocation is not supported by this browser.”; } } function showPosition(position) { var myLatLng = {lat: position.coords.latitude, lng: position.coords.longitude}; var mapOptions = { center: myLatLng, zoom: 18, mapTypeId: google.maps.MapTypeId.roadmap } var map = new google.maps.Map(document.getElementById(“map”), mapOptions); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: ‘My Location’ }); } //For handle errors function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = “User denied the request for Geolocation.” break; case error.POSITION_UNAVAILABLE: x.innerHTML = “Location information is unavailable.” break; case error.TIMEOUT: x.innerHTML = “The request to get user location timed out.” break; case error.UNKNOWN_ERROR: x.innerHTML = “An unknown error occurred.” break; } } </script>
5) That’s it.
If you want to implement it on your website feel free to contact us.