地理定位有时不起作用

时间:2015-01-07 09:42:27

标签: php geoip freegeoip

我在我的网站上使用地理位置脚本来创建一个国家/地区和城市位置,只要用户访问我的网页,就会在一个句子中显示。 但是,该功能没有按预期工作,有时会给错误的国家和城市。

这是地理位置脚本的代码:      <script>jQuery.ajax({url:"//freegeoip.net/json/",type:"POST",dataType:"jsonp",success:function(b){jQuery("#findcity").html(b.city);jQuery("#region-code").html(b.region_code);jQuery("#region-name").html(b.region_name);jQuery("#areacode").html(b.areacode);jQuery("#ip").html(b.ip);jQuery("#zipcode").html(b.zipcode);jQuery("#longitude").html(b.longitude);jQuery("#latitude").html(b.latitude);jQuery("#findcountry").html(b.country_name);jQuery("#country-code").html(b.country_code)}});</script>

下一行代码是在body标签的句子中突出显示国家/地区和城市 <h4 itemprop=headline align=center>Hello my <span id=findcountry></span> friend, how is <span id=findcity></span> today have got an awesome offer for you.</h4>

目前freegeoip.net是调用国家和城市数据的地方,但它们目前经常停机并因此而导致句子拼写错误。

那里有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

  

注意:从HERE

创建api密钥
        $remoteIp = $_SERVER['HTTP_HOST'];
        $geoLocationUrl="http://api.db-ip.com/addrinfo?   addr=$remoteIp&api_key='YOUR API KEY'";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $geoLocationUrl);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $auth = curl_exec($curl);
        if($auth)
        {
        $json = json_decode($auth,true); 
        echo $address =  $json['address'];
         echo $country =$json['country'];
         echo $state =$json['stateprov'];
         echo $city =$json['city'];
        }
        else{
        echo 'ERRROR';

        }