Reputation: 2269
If I call the Link http://freegeoip.net/json/ than it shows my Country correct. But if I call it on my Website by JavaScript than its shows me USA (Cloudflare Server). How can I pass this to show the correct country?
<script>
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
$("div.country").html(location.country_name);
}
});
</script>
<div class="country"></div>
Upvotes: 0
Views: 1530
Reputation: 541
if you making the call from your server it get their ip you need to do something like that to get your user ip and sent it to freegeoip
<script>
function myIP() {
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
xmlhttp.send();
hostipInfo = xmlhttp.responseText.split("\n");
for (i=0; hostipInfo.length >= i; i++) {
ipAddress = hostipInfo[i].split(":");
if ( ipAddress[0] == "IP" ) return ipAddress[1];
}
return false;
}
var ip = myIP();
jQuery.ajax( {
url: 'http://freegeoip.net/json/'+ip.replace(' ',''),
type: 'POST',
dataType: 'jsonp',
success: function(location) {
$("div.country").html(location.country_name);
}
});
</script>
<div class="country"></div>
becaus the example above depends to a service http://api.hostip.info/get_html.php
you could add your own a simply php script to get your user ip address wil be
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
echo $ip;
update again you could get all the info without their ip just with geolocation and reverse geocoding example app
frontend
<script>
$( document ).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
jQuery.ajax( {
url: 'geocoder.php',
type: 'POST',
data:position,
dataType: 'json',
success : function(response) {
$(".country").text(response.address.country);
$(".postal_code").text(response.address.postcode);
}
})
}
})
</script>
<div class="country"></div>
<div class="postal_code"></div>
geocoder.php
<?php
$lat = $_POST['coords']['latitude'];
$long = $_POST['coords']['longitude'];
$url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=".$lat."&lon=".$long;
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'examples');
$query = curl_exec($curl_handle);
curl_close($curl_handle);
$jsondata = json_decode($query,true);
echo json_encode($jsondata);
?>
Upvotes: 1