Display Website Visitor’s Current Location using Google Maps

Obtain your website visitor’s geolocation through HTML5 GeoLocation Object and plot the coordinates over Google Maps to show your website visitors their geographic location plotted over a map.

Display website visitor position over Google Maps

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.

HTML

 

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

Javascript

 

displayPosition()

This function basically loads up the Google Maps Javascript API and once it loaded it calls the main function : doneLoading()

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.

Demo