【问题标题】:I want to calculate distance between two locations in km in ionic 4. I use a function Which give me error [duplicate]我想计算离子4中两个位置之间的距离(以km为单位)。我使用了一个函数,它给了我错误[重复]
【发布时间】:2020-09-11 20:04:37
【问题描述】:
distance(lon1, lat1, lon2, lat2) {

       var R = 6371; // Radius of the earth in km

        var dLat = (lat2-lat1).toRad();  // Javascript functions in radians

         var dLon = (lon2-lon1).toRad(); 

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +

           Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 

            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 km

                 return d;

          }

如果我使用这个函数,我会使用 toRad() 函数。每次使用都会报错:

属性 toRad() 不存在类型号。

请帮助我,我必须导入一些东西的原因是什么?

【问题讨论】:

    标签: geolocation location ionic4 calculator distance


    【解决方案1】:

    您应该像这样编写自己的toRad 函数:

    function toRad(Value) {
            return Value * Math.PI / 180;
        }
    

    然后以功能方式使用它:

    function distance(lon1, lat1, lon2, lat2) {
            var R = 6371;
            var dLat = toRad(lat2 - lat1);
            var dLon = toRad(lon2 - lon1);
    
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(toRad(lat1)) * Math.cos(toRad(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; 
    
            return d;
        }
    

    顺便说一句,您是否使用 Ionic Angular 编写应用程序?你不应该使用 Typescript 而不是 JavaScript 吗?

    【讨论】:

    • 是的,我正在使用 Typescript,但我没有得到任何其他解决方案,所以我使用了这个。如果我通过地理编码器传递 lat , long 值,它不会给我答案
    • 您可以在 Typescript 中编写 Javascript,这将起作用,即我的解决方案应该在您的代码中起作用。我更喜欢 TS,因为尝试修复类型,您可以将函数的参数修复为number。此外,lint 将引用 let 而不是 var(只会影响范围,因此对您的 sn-p 没有影响)。
    猜你喜欢
    • 2011-08-10
    • 2017-08-22
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2015-10-26
    • 2011-12-24
    • 2018-09-21
    相关资源
    最近更新 更多