php - Angular httpClient使用经度纬度Haversine公式从JSON数组中获取用户
问题描述
我在 JSON 文件中有用户列表
[
{
"id": 1,
"first_name": "Maurise",
"last_name": "Shieldon",
"latitude": 34.003135,
"longitude": -117.7228641
},
{
"id": 2,
"first_name": "Bendix",
"last_name": "Halgarth",
"latitude": -2.9623869,
"longitude": 104.7399789
},
{
"id": 3,
"first_name": "Meghan",
"last_name": "Southall",
"latitude": "15.45033",
"longitude": "44.12768"
},
{
"id": 4,
"first_name": "Sidnee",
"last_name": "Silwood",
"latitude": -26.94087,
"longitude": 29.24905
},
{
"id": 5,
"first_name": "Rosita",
"last_name": "Ferrulli",
"latitude": 33.5719791,
"longitude": -84.3396421
}]
我正在使用 Haversine 公式来计算距离,因此我只能获得某些 LAT 和 LONG 值的用户,这种方法在我的api.service.ts
课堂上。
getDistanceFromLatLon(lat1: number, lon1: number, lat2: number, lon2: number): number {
var deg2Rad = deg => {
return deg * Math.PI / 180;
}
var r = 3959; // Radius of the earth in miles
var dLat = deg2Rad(lat2 - lat1);
var dLon = deg2Rad(lon2 - lon1);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2Rad(lat1)) * Math.cos(deg2Rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = r * c; // Distance in miles
return d;
}
然后在我的app.component.ts
文件中,我可以调用 JSON Array,它data.json
从上面的用户列表中为我提供了文件中所有用户的列表。
getUsers() {
this.httpClient.get('/assets/users.json').pipe(map(data => data as Array<Users>))
.subscribe(result => { console.log(result)}
在我从我的 JSON 文件中收到所有用户的列表之后。我正在尝试result
通过该方法运行 JSON 数组,getDistanceFromLatLon
以便只有具有 LONDON_LAT
并且LONDON_LONG
可以显示 的用户
//Latitude and longitude of London
LONDON_LAT = 51.509865;
LONDON_LONG = -0.118092;
miles;
const distance = this.apiService.getDistanceFromLatLon(result['latitude'], result['longitude'],
this.LONDON_LAT, this.LONDON_LONG);
if (distance <= this.miles) {
this.UsersByRadius = result;
}
});
}
通过 .getDistanceFromLatLon
my编译后this.UsersByRadius = result
是空的,我没有得到任何用户。我基本上是在尝试在我的 Angular 应用程序中复制这个PHP 应用程序。任何帮助都感激不尽。
解决方案
Angular SPA 通常在客户端生成。因此,在处理大型数组集时,所有的数学计算(单个除法运算的开销很大,更不用说所有的三角函数了)都会严重过载。您应该考虑在服务器端进行。
您正在检索一个数组。因此,您需要遍历它们中的每一个来调用该函数。
getUsers() {
this.httpClient.get('/assets/users.json').pipe(
map(data => data as Array<Users>)
).subscribe(result => {
console.log(result);
result.forEach(item => {
const distance = this.apiService.getDistanceFromLatLon(item['latitude'], item['longitude'], this.LONDON_LAT, this.LONDON_LONG);
if (distance <= this.miles) {
this.UsersByRadius.push({
id: item['id'],
first_name: item['first_name'],
last_name: item['last_name'],
latitude: item['latitude'],
longitude: item['longitute'],
city: 'London'
});
}
});
});
}
推荐阅读
- reactjs - Typescript:扩展外部包的类型定义(deck.gl)
- mongodb - 删除项目前需要终止所有图表应用程序
- rust - 如何在编译时避免堆栈溢出?
- python - 如何使用 buildozer 将可以显示图像的 pygame 转换为 apk
- python - 在python中计算文件中的新附加行
- android - Android 12:具有可访问性的跟踪器应用在主屏幕中显示为浮动图标
- c# - 将 Azure Keyvault 与依赖注入一起使用的正确方法
- c# - MediaElement 中的 C# 音量增益(+/- 12 Db)?
- html - 如何在下面的代码中添加 translate 属性。我将在 .po 文件中提供翻译
- apache-spark - 有没有办法检查火花流中的错误日志?