Breaking

Followers

Friday, 17 March 2017

How to get GPS location from the web browser

Get Visitor Location using HTML5 and PHP.

The getCurrentPosition() method is used to return the user's position.

1. Step: Write the  jQuery script in head tag.


$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
} else { 
$('#location').html('Geolocation is not supported by this browser.');
}
});

function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type:'POST',
url:'getLocation.php',
data:'latitude='+latitude+'&longitude='+longitude,
success:function(msg){
if(msg){
$("#location").html(msg);
}else{
$("#location").html('Not Available');
}
}
});
}



<p>Your Location: <span id="location"></span></p>


2. Step: Write the  ajax code in getLocation.php file getting the user current address .
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        $location = $data->results[0]->formatted_address;
    }else{
        $location =  '';
    }
    //Print address 
    echo $location;
}



Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

No comments:

Post a Comment