用戶Ip地址和百度地圖api接口獲取用戶地理位置(經緯度坐標,城市)


<?php
 
//獲取用戶ip(外網ip 服務器上可以獲取用戶外網Ip 本機ip地址只能獲取127.0.0.1)
function  getip(){
     if (! empty ( $_SERVER [ "HTTP_CLIENT_IP" ])){
     $cip  = $_SERVER [ "HTTP_CLIENT_IP" ];
     }
     else  if (! empty ( $_SERVER [ "HTTP_X_FORWARDED_FOR" ])){
     $cip  = $_SERVER [ "HTTP_X_FORWARDED_FOR" ];
     }
     else  if (! empty ( $_SERVER [ "REMOTE_ADDR" ])){
     $cip  = $_SERVER [ "REMOTE_ADDR" ];
     }
     else {
     $cip  = '' ;
     }
     preg_match( "/[\d\.]{7,15}/" , $cip , $cips );
     $cip  = isset( $cips [0]) ? $cips [0] : 'unknown' ;
     unset( $cips );
     return  $cip ;
}
 
$ip =getip();
 
//根據百度地圖api得到用戶Ip地理經緯度和城市
 
$url  = "http://api.map.baidu.com/location/ip?ak=omi69HPHpl5luMtrjFzXn9df&ip=$ip&coor=bd09ll" ;
$ch  = curl_init();
curl_setopt( $ch , CURLOPT_URL, $url );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1);
$output  = curl_exec( $ch );
if (curl_errno( $ch ))
{ echo  'CURL ERROR Code: ' .curl_errno( $ch ). ', reason: ' .curl_error( $ch );}
curl_close( $ch );
$info  = json_decode( $output , true);
if ( $info [ 'status' ] == "0" ){
     $lotx  = $info [ 'content' ][ 'point' ][ 'y' ];
     $loty  = $info [ 'content' ][ 'point' ][ 'x' ];
     $citytemp  = $info [ 'content' ][ 'address_detail' ][ 'city' ];
     $keywords  = explode ( "市" , $citytemp );
     $city  = $keywords [0];
}
else {
     $lotx  = "34.2597" ;
     $loty  = "108.9471" ;
     $city  = "西安" ;
}
 
 
var_dump( $lotx ); //x坐標  緯度
var_dump( $loty ); //y坐標  經度
var_dump( $city ); //用戶Ip所在城市
  

  

 --------------------------------------------------

百度地圖api新增功能  有時間可以看看

http://developer.baidu.com/map/index.php?title=jspopular


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM