2015-02-10 63 views
0

我有一個存儲長和座標的數據庫表。用戶鍵入他們的郵政編碼,並應選擇一個範圍,例如5英里,然後應顯示存儲在數據庫中的5英里以內的所有座標。我已經設法將用戶類型的郵編轉換爲座標,但我發現很難做到下一部分只顯示選定里程內的結果。只顯示用戶選擇的範圍內的結果

<?php 
$postcode = urlencode("$_POST[postcode]"); // post code to look up in this case status however can easily be retrieved from a database or a form post 
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=true"; // the request URL you'll send to google to get back your XML feed 
$xml = simplexml_load_file($request_url) or die("url not loading");// XML request 
$status = $xml->status;// GET the request status as google's api can return several responses 
if ($status=="OK") { 
    //request returned completed time to get lat/lang for storage 
    $lat = $xml->result->geometry->location->lat; 
    $long = $xml->result->geometry->location->lng; 

} 
echo "$lat,$long"; 

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "test"; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 


$sql = "SELECT * FROM location"; 
$result = mysqli_query($conn, $sql); 

if (mysqli_num_rows($result) > 0) { 
// output data of each row 
while($row = mysqli_fetch_assoc($result)) { 
    echo " Hobby: " . $row["lat"]. " Location: " . $row["long"]. "<br>"; 
    $lat1=$row["lat"]; 
    echo $lat1; 
} 
} else { 
echo "Sorry, there are no meetups yet you can create one here "; 
} 

mysqli_close($conn); 

    ?> 
+0

你不應該真的'SELECT *'。你應該選擇你想要的列。 – kkuilla 2015-02-10 12:27:07

+0

聽起來像你需要Haversine公式 - http://stackoverflow.com/questions/14750275/haversine-formula-with-php – martincarlin87 2015-02-10 12:33:10

回答

0

如果你有一個mySQL數據庫,看看這些問題,他們處理同樣的問題。

Mysql within distance query

https://gis.stackexchange.com/questions/31628/find-points-within-a-distance-using-mysql

你需要創建一個SQL語句,其中一定距離內所有座標結果。它可能看起來像:

SELECT *, 
    (3959 * acos(cos(radians($lat)) 
    * cos(radians(lat)) 
    * cos(radians(lng) - radians($lng)) 
    + sin(radians($lat)) 
    * sin(radians(lat)))) AS distance 
FROM locations 
HAVING distance < $miles 
ORDER BY distance 
LIMIT 0, 20 

如果你有一個postgres數據庫,你可以使用postGIS的擴展。有一個函數ST_DWithin存在,如果座標在一定的距離內,則返回true。

+0

$ lat,$ long,$ miles是用戶的變量:lat,lng是名稱在您的數據庫中出現的列的錯誤 – Bine 2015-02-10 12:32:15

+0

由於某種原因,我總是收到一個錯誤「檢查對應於您的MySQL服務器版本的手冊,以使用接近long的正確語法) - 弧度(0.0116469))+ sin(弧度(51.5556739)) * sin(第4行的radi' – user4258493 2015-02-10 13:16:42

+0

檢查所有變量的正確拼寫以及是否所有括號都存在。似乎存在解釋錯誤 – Bine 2015-02-10 13:30:27