我想在我的网页上获取客户端的位置。
我可以用PHP或Javascript来完成。
我目前正试图通过客户端的IP地址和PHP的geoip扩展来获取位置。
但它需要一个达加巴色,我不想要。
有其他方法可以找到客户的位置吗?
您可以使用http://ipinfo.io/该数据库是第三方数据库。
该数据库不需要任何插件,因此很容易与PHP一起使用。
$ip = $_SERVER['REMOTE_ADDR']; // get client's IP
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));// Send to ipinfo
echo $details->city; // Gives you the city of the client.
echo $details->country; // Gives you the country of the client.
编辑:我还看到你添加了一个javascript标记,你也可以用jQuery来完成。
$.get("http://ipinfo.io", function(response) {
console.log(response.city);
}, "jsonp");
您可以使用javascript获取纬度和经度。
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>