我正在尝试计算坐标之间的直线距离。我可以使用硬编码值成功地做到这一点,但是当我有一个坐标列表时,我的问题就出现了。基本上,第一组坐标将始终是我可以成功获取的当前位置。第二组坐标来自 JSON 文件,如下所示。
[
{
"LocationID": 407,
"LocationName": "Free State",
"CustomerName": "Build It - Botshabelo ",
"ContactNo": "051 - 534 4072",
"Address": "75 Blue Street, Botshabelo",
"Zipcode": null,
"Longitude": "26,704671",
"Latitude": "-29,199533",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": "Closed "
},
{
"LocationID": 408,
"LocationName": "Free State",
"CustomerName": "Cashbuild - Thabanchu",
"ContactNo": "051 - 875 1590",
"Address": "Brug St, Thaba Nchu",
"Zipcode": null,
"Longitude": "26,779109",
"Latitude": "-29,196689",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": "Closed "
},
{
"LocationID": 409,
"LocationName": "Free State",
"CustomerName": "Ladybrand Mica",
"ContactNo": "082 - 568 5387",
"Address": "17 Joubert St, Ladybrand",
"Zipcode": null,
"Longitude": "27,458835",
"Latitude": "-29,191979",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": ""
}
]
我正在循环数组以获取纬度和经度
this.http.get('assets/stores.json').subscribe(data => {
this.places = data;
for(var i = 0; i < this.places.length; i++){
this.placePOS = this.places[i].Latitude, this.places[i].Longitude;
var distance = this.distance(this.currentLat, this.currentLon, this.places[i].Latitude, this.places[i].Longitude, 'K');
}
});
此处创建距离函数
distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var radlon1 = Math.PI * lon1/180
var radlon2 = Math.PI * lon2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
当我运行代码时,我得到一个 NaN。请帮忙
最佳答案
看来没有其他人发现它,.. @eohdev 现在已经离开了,认为结果是正确的,只是因为他们现在没有给出 NaN
,我将发布主要原因问题所在。
parseFloat
是一个很好的做法,但这不是导致问题的原因。Javascript 通常可以自动计算出类型。例如"20"/4
将等于 5
,即使 20
是一个字符串。 “20” - “5”
将等于 15。 JS 无法自动计算出来的是 "20"+ "5"
这将是 205.. 这是因为你可以连接字符串,并添加数字,所以它不能自动选择,这就是为什么 parseFloat 等是个好主意。
但回到这里的问题,这是源数据..
“经度”:“27,458835”
该数字不是有效的 float ,JS 中的 float 没有逗号。
那么为什么它看起来像 parseFloat 工作你问,.. 好吧 parseFloat("27,458835")
将导致 27
.. 哦,亲爱的..除非你的距离计算被 chop 到最接近的程度,否则它可能不是你想要的。
所以问题不是缺少 parseFloat,而是源数据使用逗号,而不是小数点的句号。因此,如果您将逗号更改为句号,您当前的代码将可以工作,但我也想说保留 parseFloats 以便更好地衡量。
关于javascript - 计算当前坐标和坐标列表之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49381007/