In php many times need to know register user or some visitor location for some functionality improvement in website like if you want to access your website only from USA country than must know visitor is from which country and than display and message or restriction page.so there are two way for fetch current user location which is common or only two way for getting location.
one is from IP Address and second from latitude and longitude here discuss how get address,city,country of current user.
Get Current Address From IP
If you get user location from IP address than there are many websites provide API for that.
Here http://www.geoplugin.net/ is one of best and most use for provide that services in that only pass IP address and you got all related information about location below describe PHP code.
$ip = $_SERVER['REMOTE_ADDR']; //for get currunt IP
$unarr= @file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip);
$AddArr = unserialize($unarr); //get all variable.
From below code you got many parameters related to address and find your needed from them.This method only work on live server because IP address not fetch for localhost.
Get Current Address From Latitude and Longitude
If you want to get address from latitude and longitude that this method is useful in this also pass latitude and longitude variable and you got complete address.PHP code for that describe as below.Here also use JavaScript for get current latitude and longitude.
< script type="text/javascript" >
function onPositionUpdate(position)
{
var latitude = position.coords.latitude; //get latitude variable
var longitude = position.coords.longitude; //get longitude variable
document.cookie = "latitude ="+lat+";path=/";
document.cookie = "longitude ="+lng+";path=/"; //save in COOKIE
}
if(navigator.geolocation){navigator.geolocation.watchPosition(onPositionUpdate);}
else{alert("navigator.geolocation is not available");}
< /script >
//PHP code for getting address
$json = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_COOKIE['latitude']).','.trim($_COOKIE['longitude']).'&sensor=false');
$data= json_decode($json);
$status = $data->status;
if($status=="OK"){echo $data->results[0]->formatted_address}//display complete address
Here using below code you return difference address variable in `$data` so use that according to your use.
No comments :
Post a Comment