Properly including math.js library in a .js file

324 Views Asked by At

I want to use the math.js library in my javascript file - say it's called webpage.js. What I did so far is having a script tag in the main html file that calls math.js, and then another that calls webpage.js. The script tags are as follows:

<script
    src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/6.2.5/math.min.js"
    integrity="sha256-fWwwg2Pf3Ox5xhm9xCE7O+czkI2dSkqN6gUZumzGrx0="
    crossorigin="anonymous"></script>
<script src="js/lat-long.js"></script>

Is that it? Can I now go to my webpage.js file and use "Math.whatever" without having to 'import' or 'include' anything at the beginning of the file?

The reason I am asking this is because I have the following code which is not working properly (anything using Math.something is returning a NaN, which I assumed was because Math.js was not imported properly). Here is the code for reference:

function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat2 - lat1); // deg2rad below
    var dLon = deg2rad(lon2 - lon1);
    console.log("dLat------------------" + dLat);
    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 km
    console.log("d is " + d);
    return d;
}

function deg2rad(deg) {
    return deg * (Math.PI / 180);
}
var distance = getDistanceFromLatLonInKm(
    locationLatUser,
    locationLongUser,
    supplier.latLng.latitude,
    supplier.latLng.longitude
);

//all the values used in the function call exist and are defined.
console.log("distance between user and supplier: " + distance);

Console logging any value in the above code gives me a NaN.

0

There are 0 best solutions below