In this article I will explain how to use the HTML5 GeoLocation API in browsers that support HTML5 GeoLocation feature and determine the current location i.e. Latitude and Longitude co-ordinates.
These Location coordinates i.e. Latitude and Longitude can be used to display the User’s current location in Google Maps in our website.
Note: The GeoLocation API is supported by the following browsers Internet Explorer 9+, Firefox, Chrome, Safari and Opera. But since the Desktops and Laptops do not have GPS the location might not be very accurate but if the same is accessed from a Mobile device with GPS it will give accurate results.
 
Show user’s current location on Google Map using GeoLocation API
Following is the script that will display the user’s current location using GeoLocation API.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (p) {
        var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        var mapOptions = {
            center: LatLng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude
        });
        google.maps.event.addListener(marker, "click", function (e) {
            var infoWindow = new google.maps.InfoWindow();
            infoWindow.setContent(marker.title);
            infoWindow.open(map, marker);
        });
    });
} else {
    alert('Geo Location feature is not supported in this browser.');
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
 
Explanation
First I have checked whether the browser supports GeoLocation if not then a JavaScript alert message is displayed conveying him that GeoLocation is not supported.
In case the browser supports GeoLocation, the location coordinates i.e. the Latitude and Longitude will be extracted and then assigned to the Google Maps LatLng object.
Then the map options are set, followed by marker creation and then a click event is assigned to the marker so that when it is clicked an InfoWindow will be shown.
 
Screenshots
GeoLocation is not supported by the browser
Show user’s current location on Google Map using GeoLocation API in website
 
Browser seeking permission to share location
Show user’s current location on Google Map using GeoLocation API in website
 
Google Maps displaying the current location using GeoLocation API
Show user’s current location on Google Map using GeoLocation API in website
 
Demo
 
Downloads