0

I have a sample code with data is cities include object(latitude, longitude)

This is my code

...
   methods: {
      mapDrag: function () {
         let lat = 100;
         let lng = 200;
         this.cities.forEach(function (city, index, array){
            let distance = this.calculateDistance(city.latitude, city.longitude, lat, lng)
            console.log(distance)
         });
      },
      calculateDistance: function (lat1, long1, lat2, long2) {
            //radians
            lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;
            long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;
            lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;
            long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;


            // use to different earth axis length
            var a = 6378137.0;        // Earth Major Axis (WGS84)
            var b = 6356752.3142;     // Minor Axis
            var f = (a-b) / a;        // "Flattening"
            var e = 2.0*f - f*f;      // "Eccentricity"

            var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));
            var cos = Math.cos( lat1 );
            var x = beta * cos * Math.cos( long1 );
            var y = beta * cos * Math.sin( long1 );
            var z = beta * ( 1 - e ) * Math.sin( lat1 );

            beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));
            cos = Math.cos( lat2 );
            x -= (beta * cos * Math.cos( long2 ));
            y -= (beta * cos * Math.sin( long2 ));
            z -= (beta * (1 - e) * Math.sin( lat2 ));

            return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);
        },
   },
...

When in function mapDrag on methods, error show:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'calculateDistance')"

1
  • this is related to he scope of the function here. Try this this.cities.forEach((city, index, array) => Commented Oct 14, 2022 at 10:01

1 Answer 1

2

Call using arrow function like.

this.cities.forEach((city, index, array) => {
    let distance = this.calculateDistance(city.latitude, city.longitude, lat, lng)
    console.log(distance)
});

this will be bounded with the scope from which the function is being called. So writing it as a normal function will take the scope of Array.forEach. To get the component scope you have to use it as an arrow function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.