One of my client wanted to display the current visitor’s location on his website. So I coded a simple script to get the visitor’s location through HTML GeoLocation API and subsequently plot the location on Google Maps. Its a simple and handy code which I have decided to share over here.
Feel free to copy and use it, also I look forward to hearing your use cases as well as your comments.
<input class="simple-button" type="button" value="See your location" onClick="dispayPosition()" /> <div id="map-canvas" style="width: 400px; height: 350px; display: none;"></div>
The div ‘map-canvas’ is where position will be displayed while the button initiates the function ‘displayPosition()’, You can initiate this JavaScript function on page load or hook it to any browser event as per your requirement. The ‘displayPostion’ and other functions are discussed below
function displayPosition() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'callback=doneLoading'; document.body.appendChild(script); } function doneLoading(){ document.getElementById('map-canvas').style.display = "block"; var mapOptions = { zoom: 14 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Try HTML5 geolocation if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var infowindow = new google.maps.InfoWindow({ map: map, position: pos, content: 'Current Location' }); map.setCenter(pos); }, function() { document.getElementById('map-canvas').innerHtml = "You didn't allow position retrieval"; }); } else { // Browser doesn't support Geolocation document.getElementById('map-canvas').innerHtml = "GeoLocation not supported by browser."; } }
This function basically loads up the Google Maps Javascript API and once it loaded it calls the main function : doneLoading()
This function retrieves the user location in browser through HTML 5 GeoLocation API and once position is retrieved it fires up the Google Maps and load the map for coordinates as retrieved from GeoLocation API.
Visit Display Website Visitor's Current Location using Google Maps for demo.