2014-06-16 176 views
0

選擇記錄我已經經度和緯度存儲在數據庫中像與最接近的經度和緯度

表名:km_stores 領域:STORE_ID,store_long,store_lat,STORE_NAME

我如何使用他們拉最近的商店經度和緯度?

我使用的,因爲我正在使用的WordPress插件頁面PHP

<script> 
var x = document.getElementById("demo"); 

function getLocation() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } else { 
     x.innerHTML = "Geolocation is not supported by this browser."; 
    } 
} 

function showPosition(position) { 
    document.getElementById("km_long").value = position.coords.latitude; 
    document.getElementById("km_lat").value = position.coords.longitude;  
} 
</script> 
<strong>Long:</strong> <input type="text" id="km_long" /> <strong>Latitude:</strong> <input type="text" id="km_lat" /> 
[php] 

global $wpdb; 
$results = $wpdb->get_results('select * from km_stores', OBJECT); 
foreach ($results as $store) { 
      echo $store->store_name; 
} 
[/php] 

[php][/php]標籤。

+0

可能的重複:http://stackoverflow.com/questions/5031268/algorithm-to-find-all-latitude-longitude-locations-within-a-certain-distance-fro – hindmost

回答

0

使用畢達哥拉斯距離你的座標。

如果你的座標是5,15(出於參數的緣故),而你喜歡的第一個商店是10,20。

$distance = sqrt((5 - 10) * (5 - 10) + (15 - 20) * (15 - 20)) 

該公式可能會給你一個負數,但如果你忽略了 - ,你會得到距離。不好意思,這個答案有點粗糙。

0

現在你的選擇語句拉動所有的點,所以你想限制它只拉近點。最簡單的方法是在數據庫表中添加lat和lng值的搜索條件。

$query = 'SELECT * FROM km_stores WHERE lat BETWEEN ' . $lat - x . ' AND ' . $lat + x; 
$query = $query . ' AND lng BETWEEN ' . $lng - x . ' AND ' . $lng + x; 
$results = $wpdb->get_results($query, OBJECT); 

這是假設你有$定義表示要四處搜尋(它看起來像你稱它們爲km_lat和km_lng)點lat和$ LNG值。然後,您將用您希望點的緯度/經度距離替換x。玩這些值來決定什麼號碼適用於您的應用程序。