Geolocation sometimes does not work

647 views Asked by At

I am using a geo location script on my site to create a country and city location that shows within a sentence whenever users visit my page. However the function is not working as intended and sometimes gives the wrong country and city.

This is code for the geo location script: <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>

The next line of code is to highlight the country and the city in a sentence in the body tag <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>

Currently freegeoip.net is where the country and city data is being called from but they are currently down often and cause a typo on the sentence because of this.

Is there a better solution out there?

1

There are 1 answers

35
Priyank On

Try this code:

Note: create your api key from HERE

        $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';

        }