首页 > 解决方案 > 我想计算离子 4 中两个位置之间的距离(以 km 为单位)。我使用了一个给我错误的函数

问题描述

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() 不存在类型号。

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

标签: geolocationlocationionic4calculatordistance

解决方案


您应该像这样编写自己的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 吗?


推荐阅读