Proper usage of a method within another method in a Vue component

Currently, I am extracting GPS data from an image using exifjs. My objective is to convert the latitude and longitude variables into a decimal variable as illustrated below:

<template lang="html">
  <div class="upload-wrap">
    <button class="btn">Choose a photo</button>
    <input ref="fileinput" @change="onChange" id="file-input" type="file" accept="image/jpeg"/>
  </div>
</template>

<script>
import EXIF from '../../node_modules/exif-js/exif'

export default {
  methods: {
    toDecimal(number) {
      return number[0].numerator + number[1].numerator /
          (60 * number[1].denominator) + number[2].numerator / (3600 * number[2].denominator);
    },

   onChange(image) {
     var input = this.$refs.fileinput

     if (image) {
       EXIF.getData(input.files[0], function() {

         var lat = EXIF.getTag(this, 'GPSLatitude');
         var long = EXIF.getTag(this, 'GPSLongitude');

         if (lat && long) {
          var lat_dec = toDecimal(lat);
          var long_dec = toDecimal(long);

          // eslint-disable-next-line
          console.log(lat_dec, long_dec);
         }
         else {
          // No metadata found
          clearFileInput(input);
          alert("No GPS data found in image '" + input.files[0].name + "'.");
        }
       })
     } else {
        // eslint-disable-next-line
       console.log(`No image selected?`);
     }
   },
    // Clear file input if there's no exif data
  clearFileInput(ctrl) {
    ctrl.value = null;
  }
 }
}
</script>

Yet, I encountered the following error:

ReferenceError: toDecimal is not defined

I wonder if I am utilizing the correct syntax or missing something crucial?

Edit: I attempted to use this.toDecimal(lat); but it led to

TypeError: this.toDecimal is not a function

Answer №1

If you need to utilize the this.toDecimal method, keep in mind that within the callback function, the this variable does not refer to the Vue instance. You can resolve this by using an arrow function or a small trick involving var self = this.

onChange(image) {
    var input = this.$refs.fileinput
    var self = this;
    if (image) {
        EXIF.getData(input.files[0], function() {

            var lat = EXIF.getTag(this, 'GPSLatitude');
            var long = EXIF.getTag(this, 'GPSLongitude');

            if (lat && long) {
                var lat_dec = self.toDecimal(lat);
                var long_dec = self.toDecimal(long);

                // eslint-disable-next-line
                console.log(lat_dec, long_dec);
            } else {
                // No metadata found
                clearFileInput(input);
                alert("No GPS data found in image '" + input.files[0].name + "'.");
            }
        })
    } else {
        // eslint-disable-next-line
        console.log(`No image selected?`);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a worldwide object in JavaScript

I am trying to create a global object in JavaScript. Below is an example code snippet: function main() { window.example { sky: "clear", money: "green", dollars: 3000 } } However, I am unable to access the object outside th ...

Designing an interactive region using HTML, CSS, and JavaScript

I recently created this code with some assistance: When I tried to format the code, it all ended up on one line and looked unreadable. To view the code properly, please visit this link: http://jsfiddle.net/QFF4x/ <div style="border:1px solid black;" ...

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

Using Node.js to read and replicate a JSON file

As someone who is relatively new to the world of NODE.JS, I am eager to level up my skills. Currently, I have a NODE.JS script that gathers data from a feed, resulting in a large JSON file. This file is then used by webpages and mobile apps to display con ...

Working with JSON data retrieved from a PHP and MySQL backend in an AngularJS application

Having difficulty handling the JSON response from PHP. I am using AngularJs to display the received JSON data. As a newcomer to Angular, I attempted a basic exercise and would appreciate some assistance. Thank you in advance. index.html <!DOCTYPE HTML ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

When running the command `npx create-react-app client`, an error is thrown stating "Reading properties of undefined is not possible (reading 'isServer')."

Installing packages. Please wait while the necessary packages are being installed. Currently installing react, react-dom, and react-scripts with cra-template... Encountered an error: Unable to read properties of undefined (reading 'isSer ...

When working with Vue JS, which is more performant and preferable to use: making direct changes to state in Pinia or using $patch()?

Hey guys, I've been working with Pinia and Vuejs 3, and I'm curious about the performance impact of using $patch(). Can anyone shed some light on this? What is considered the best practice when it comes to this situation? For instance, take a l ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

Exploring the power of intercepting response.send() and response.json() in express.js

Imagine having various instances where response.send(someData) is utilized. What if you wish to implement a universal interceptor that captures all .send functions and modifies someData? Is there a method within express.js to achieve this, such as hooks, ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

Node.js cannot access the uploaded image data as it has been defined as undefined

I have encountered an issue while sending an image file through ajax to my Node.js server. Upon attempting to view the file data, it returns 'undefined'. Here is a snippet from my app.js file: var express = require("express"); var app ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Guide to enabling TypeScript linting in .vue files using IntelliJ IDEA

Recently, I've been delving into the world of Vue and TypeScript, but I'm facing a roadblock that I just can't seem to overcome: When it comes to maintaining a consistent coding style across my TypeScript scripts, tslint does the job perfec ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch. // Update items in state when the pending time in queue has passed, set allowed: true items.map((item) => { const itemDate = new Date(item.adde ...