2016-04-30 82 views
-2

我想获取我的网页上客户的位置。如何获取位置--php

我可以用PHP或Javascript来做到这一点。

我目前正试图通过客户端的IP地址和PHP的geoip扩展来获取位置。

但它需要一个数据库,我不希望这样。

有没有其他方法可以找到客户的位置?

+0

没有任何一个护舷帮你吗?请标记他们接受。 – Ofir

回答

1

您可以使用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"); 
0

您可以使用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> 
+1

随着经纬度的增长,您可以使用Google API执行反向搜索并获取城市 –