【发布时间】:2019-03-28 14:54:29
【问题描述】:
我有一组位置对象,其中 GPS 位置与这些对象相关联。我想根据用户当前位置过滤数组并比较用户位置和位置对象之间的距离。
我有一个当前功能可以完成此操作,但我知道这效率不高。我宁愿过滤数组而不是创建一个临时变量并将临时变量分配给数组。
//sample data
public getLocation = [
{
"ID": "1",
"Name": "Test Location 1",
"Lat": "32.16347467",
"Lon": "-103.67178545"
}, {
"ID": "2",
"Name": "Test Location 2",
"Lat": "32.16347451",
"Lon": "-103.67178544"
}, {
"ID": "3",
"Name": "Test Location 3",
"Lat": "32.13559815",
"Lon": "-103.67544362"
}, {
"ID": "4",
"Name": "Test Location 4",
"Lat": "32.40144407",
"Lon": "-103.13168477"
}, {
"ID": "5",
"Name": "Test Location ",
"Lat": "32.14557039",
"Lon": "-103.67011361",
}
]
grabLocation(){
this.platform.ready().then(() => {
this.geolocation.getCurrentPosition().then((resp) => {
this.userLocation = [parseFloat(resp.coords.latitude.toFixed(4)),parseFloat(resp.coords.longitude.toFixed(4))];
this.userLocation = [resp.coords.latitude,resp.coords.longitude];
var getLocation
getLocation = this.asyncLocations.grabUserLoc(this.userLocation[0],this.userLocation[1]);
console.log(getLocation);
}).catch((error) => {
this.presentToast(error);
});
});
}
//asyncLocations.ts
grabUserLoc(lat,lon){
var tempLocation= [];
for(let i=0;i<this.getLocation.length;i++){
if((this.getLocation[i]['Lat']!="") && this.getLocation[i]['Lon']!=""){
let R = 6371;// km
let RinM = (R*0.621371);
let Lat1 = (parseFloat(lat.toFixed(5)));
let Lon1 = (parseFloat(lon.toFixed(5)));
let Lat2 = (parseFloat(this.getLocation[i]['Lat']));
let Lon2 = (parseFloat(this.getLocation[i]['Lon']));
let dLat = this.toRad(Lat2-Lat1);
let dLon = this.toRad(Lon2-Lon1);
let RLat1 = this.toRad(Lat1);
let RLat2 = this.toRad(Lat2);
let a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(RLat1) * Math.cos(RLat2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
//let d = R * c;
let e = RinM * c;
if(e < 5){
tempLocation.push(this.getLocation[i]);
}
}
}
this.getLocation = tempLocation;
return this.getLocation;
}
// Converts numeric degrees to radians
toRad(Value)
{
return Value * Math.PI / 180;
}
我目前的位置检查距离为 5 英里。
任何帮助将不胜感激。
【问题讨论】:
-
由于您没有指出代码不起作用,这听起来更像是您需要code review
-
我投票结束这个问题,因为它要求代码审查
-
谢谢!我会在那里尝试。我假设该网站可以帮助解决我的问题
-
是的,这个站点通常是针对不工作的代码 - 另一个站点是针对工作但需要改进的代码。不过,也请参阅下面我的答案中的链接。
-
好的,我会注意的。谢谢!我会的!
标签: javascript arrays geolocation ionic3