1
我想要做這樣的事情,在下面的代碼片段的SPAN標籤來顯示各列表項英里的距離,但我不知道怎麼樣。該腳本分類精細,並且已經計算距離,我只是不知道如何將它寫入頁。我覺得這很簡單,所以我希望有人能幫助我!顯示距離上一個地理位置排序
<li>
<div class="name">
Moe Bar <span class="miles"></span></div>
<div class="long">
47.60357999999998</div>
<div class="lat">
-122.329454</div>
</li>
全碼 工作實例在http://demos.thebeebs.co.uk/bars-in-seattle/
<!DOCTYPE html>
<html>
<head>
<title>Local Bars</title>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.min.js"></script>
<script>
function findMe() {
if (navigator.geolocation != undefined) {
navigator.geolocation.watchPosition(onFound, onError);
}
}
function onFound(pos) {
var userLat = pos.coords.latitude;
var userLong = pos.coords.longitude;
$('ul li').each(function (index) {
var locationLat = $(this).find('.lat').html();
var locationLong = $(this).find('.long').html();
var distance = getDistance(userLat, locationLat, userLong, locationLong);
$(this).data("distance", distance);
})
reOrder();
}
function onError(pos) {
alert("Something Went wrong");
}
function reOrder() {
$('ul li').sort(sortAlpha).appendTo('ul');
}
function sortAlpha(a, b) {
return $(a).data('distance') > $(b).data('distance') ? 1 : -1;
};
function getDistance(lat1, lat2, lon1, lon2) {
var R = 6371; // km
var d = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.cos(lon2 - lon1)) * R;
return d;
};
</script>
<style>
ul .long, ul .lat
{
display: none;
}
</style>
</head>
<body>
<div>
<a href="#" onclick="findMe()">Find Closest Pub</a>
<ul>
<li>
<div class="name">
Moe Bar</div>
<div class="long">
47.60357999999998</div>
<div class="lat">
-122.329454</div>
</li>
<li>
<div class="name">
Frontier Room</div>
<div class="long">
47.61469022047056</div>
<div class="lat">
-122.34816509008769</div>
</li>
<li>
<div class="name">
See Sound</div>
<div class="long">
47.6156159656448</div>
<div class="lat">
-122.32593494177237</div>
</li>
</ul>
</div>
</body>
</html>
Balexandre,很不錯!感謝您抽出寶貴的時間。它似乎只適用於Chrome,儘管...嘗試Firefox和Safari沒有運氣。有什麼想法嗎? – echristo66 2013-04-03 21:26:56
是的,我知道爲什麼...它的假設,鉻是否良好,但有些則需要設置明白,他們從谷歌API接收的數據類型是'json',所以我們需要使用'$阿賈克斯'而不是''.get'。示例已更新。 – balexandre 2013-04-03 22:36:21
真棒!你一直非常樂於助人,謝謝!最後一個問題。如果我不希望在網頁加載中分享您的位置,而只是想點擊「按距離最近的酒吧排序」來獲得您的位置,那麼我該如何實現這一目標?理解我會失去有關'看起來您靠近......」 – echristo66 2013-04-04 14:34:28