You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NativeScript计算两地距离报错:Cannot create property 'android' on number

在NativeScript中计算位置距离的问题解决

嘿,我看到你在NativeScript里计算两个位置间距离时遇到了Cannot create property 'android' on number的报错,咱们来一步步把这个问题搞定~

问题根源

你当前的getDistance函数犯了两个关键错误:

  1. 错误处理坐标:你把经纬度直接相加变成了一个数字(loc1 = this.currentGeoLocation.longitude + this.currentGeoLocation.latitude),但地理距离计算需要的是包含latitude和longitude的坐标对象,不是简单的数值拼接。
  2. 错误处理数组数据:this.items是一个数组,你直接访问this.items.longitude会得到undefined——你需要遍历数组里的每个元素,才能拿到每个地点的经纬度。

这些错误导致后续的距离计算函数接收到了错误的参数类型,从而抛出了那个奇怪的报错。

修正方案

下面是完整的修正代码和步骤:

1. 确保正确导入Geolocation模块

首先确认你已经导入了NativeScript的地理定位模块:

import * as geolocation from "nativescript-geolocation";

2. 修正距离计算逻辑

替换你原来的getDistance函数,改成以下逻辑:

// 封装一个通用的距离计算函数,接收两个坐标对象
private calculateDistance(loc1: { latitude: number, longitude: number }, loc2: { latitude: number, longitude: number }): number {
    // 使用NativeScript Geolocation内置的distance方法,返回单位是米
    return geolocation.distance(loc1, loc2);
}

// 遍历所有获取到的地点,计算每个地点和当前位置的距离
private getDistance() {
    // 先判断当前位置是否已成功获取
    if (!this.currentGeoLocation) {
        alert("当前位置未获取到,请稍等重试");
        return;
    }

    // 遍历items数组,逐个计算距离
    this.items.forEach(item => {
        const distanceInMeters = this.calculateDistance(this.currentGeoLocation, item);
        // 可以转换成公里(可选)
        const distanceInKm = distanceInMeters / 1000;
        
        console.log(`地点 ${item.name} 和当前位置的距离:${distanceInMeters} 米 / ${distanceInKm.toFixed(2)} 公里`);
        // 把距离存到item对象里,方便后续页面展示
        item.distance = distanceInKm.toFixed(2);
    });
}

3. 调用时机注意

记得要在getallprod()的回调里调用getDistance,确保this.items已经有数据,同时this.currentGeoLocation也已经获取完成:

getallprod() {
    this.ws.getallprod().subscribe(
        items => {
            this.items = items;
            console.log("获取到地点数据:", this.items);
            // 数据加载完成后计算距离
            this.getDistance();
        },
        err => console.error("接口请求错误:", err),
        () => console.log("接口请求完成")
    );
}

额外注意事项

  • NativeScript的geolocation.distance()方法返回的距离单位是米,如果需要其他单位可以自行转换。
  • 确保位置权限已经成功获取,你原来的权限请求逻辑可以保留,但建议加上权限请求失败的处理(比如用户拒绝权限时的提示)。
  • 要保证this.currentGeoLocation在调用getDistance时已经被正确赋值,避免出现undefined的情况。

内容的提问来源于stack exchange,提问作者Alon Bi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:13:03