Getting visitor current location is now very easy by HTML5 Geolocation and google map api, In just few lines of javascript code you can easily get the visitor current location, Most of the time your project required to get user current location so that you can display visitor near by search result, Most of the websites using this feature to enhance their search query by visitor location based.



But Here we are using HTML5 Geolocation api so visitor must have to share their location with your server, As soon as your server try to get the visitor current location as browser popup will open to ask permission for sharing their location, So only if visitor allow location sharing then only you can get the co-ordinates and sent them to google map api to get full address or city, state, county, zipcode etc.
get-visitor-current-location

Get visitor location using HTML5 Geolocation and google map api in jquery

First check whether clients browser support HTML5 Geolocation or not.

$(function(){
    if (navigator.geolocation) {
       // Wow your browser support geolocation api
    } else { 
        // Sorry..!! Geolocation is not supported by your browser.
    }

After that get visitor co-ordinates by html5 navigator property

$(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getLocation);
    } else { 
        // Sorry..!! Geolocation is not supported by your browser.
    }
 
   function getLocation(loc) {
        	var latitude = loc.coords.latitude;
                var longitude = loc.coords.longitude;
                console.log("latitude="+latitude);
                console.log("longitude="+longitude);
   }
 });




Finally put these co-ordinates on google map api and It will return full details of location in json format.

<script>
 $(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getLocation);
    } else { 
        // Sorry..!! Geolocation is not supported by your browser.
    }
 
   function getLocation(loc) {
        	var latitude = loc.coords.latitude;
            var longitude = loc.coords.longitude;
            $.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="+latitude+","+longitude, function(data) {
              console.log(data);
 
            }); 
   }
 });
 
</script>

In browser console you can see lot’s of location parameter like visitor current city, state, country, zipcode full address and many more..


DEMO


DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff