Thursday, 18 August 2016

How to get visitor location with JavaScript ?

How to get visitor location with JavaScript ?

Today there are lots Free/Paid API avaiable which give you client information.
Following are two example which give you client information like city, country, country code, ip, local date time, timezone etc with javascript.
Question: How to get visitor location javascript with freegeoip.net?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready( function() {
   $.getJSON("http://freegeoip.net/json/", function(result){
       console.log(result);                        

       });
   });

Output
{  "ip": "112.196.3.177",
  "country_code": "IN",
  "country_name": "India",
  "region_code": "PB",
  "region_name": "Punjab",
  "city": "Mohali",
  "zip_code": "",
  "time_zone": "Asia/Kolkata",
  "latitude": 30.78,
  "longitude": 76.69,
  "metro_code": 0
}



Question: How to get visitor location javascript with ipinfo.io?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready( function() {
   $.getJSON('http://ipinfo.io', function(data){
    console.log(data)
  })
    }); 
</script>

Output
  {"ip": "112.196.3.177",
  "hostname": "No Hostname",
  "city": "Mohali",
  "region": "Punjab",
  "country": "IN",
  "loc": "30.7800,76.6900",
  "org": "AS17917 Quadrant Televentures Limited"
}