JQuery的新手。
看了看 iPhone: Sorting based on location
但它没有回答我的问题。
我有以下数组“MyStoreArray”,并希望确定哪个站点最接近我当前位置并检索该站点的“storenum”元素。并使用该元素联系该网站。
样本数组:
myStoreArray: (
{
StoreName = StoreName1;
Latitude = "-26.01672";
Longitude = "28.127379";
StoreNum = "0113675700";
},
{
StoreName = StoreName2;
Latitude = "-26.018744";
Longitude = "28.007777";
StoreNum = "0115535800";
},
)
答案 0 :(得分:0)
我最近为一个网站做了一个商店定位器,我感觉很慷慨。试试这个。
<强> Working jsfiddle example 强>
首先,将您的商店放入一系列对象......
var _stores = [{
storeName: "StoreName1",
latitude: -26.01672,
longitude: 28.127379,
storeNum: "0113675700"
}, {
storeName: "StoreName2",
latitude: -26.018744,
longitude: 28.007777,
storeNum: "0115535800"
}];
然后我们需要包含google脚本以获取用户的当前位置...
var _position = {};
function success(position) {
console.log(position);
_position = position.coords;
sortStoresByDistance(); // this is explained further down
alert("Your nearest store is " + _stores[0].storeName +
" (" + _stores[0].storeNum + ")");
}
function error(err) {
alert("Geolocation error : " + err);
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 10
};
function googleCallback() {
navigator.geolocation.getCurrentPosition(success, error, options);
}
$.getScript("https://www.google.com/jsapi", function () {
google.load("maps", "3", {
other_params: "sensor=false",
streetViewControl: false,
callback: function () {
googleCallback();
}
});
});
现在我们拥有所有必需的信息,按距离对商店列表进行排序......
if (typeof (Number.prototype.toRad) !== "function") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
function sortStoresByDistance() {
for (var i = 0; i < _stores.length; i++) {
_stores[i].distance = getDistance(_position, _stores[i]);
}
_stores.sort(function (a, b) {
return a.distance - b.distance;
});
}
function getDistance(position1, position2) {
var lat1 = position1.latitude;
var lon1 = position1.longitude;
var lat2 = position2.latitude;
var lon2 = position2.longitude;
console.log(lat1, lon1, lat2, lon2);
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
一旦运行,商店将按距离排序,因此_stores[0]
是您最近的商店,而您正在寻找_stores[0].storeNum