Implementing calculation and sorting functionality in Vue.JS for multidimensional JSON objects

I have a complex JSON feed containing various events with multiple dates and locations. Each date for an event includes latitude and longitude, which I use to calculate distance using HTML5 geolocation. My goal is to add this calculated distance to the child object and sort not only by distance but also organize events based on the distances of their individual dates.

Previously, I attempted to sort inline using v-for in Vue2, but I realized it does not work as expected and doesn't address the sorting of parent events. Below is an example of my current approach:

HTML:

<div id="string">
  <p><strong>Current Geolocation:</strong> {{lat}}:{{lon}}</p>
  <ol v-for="seminar in seminars">
    <li>
      {{seminar.title}}
      <ul>
        <li v-for="event in seminar.events">
          {{event.webtitle}} <strong>{{calcDist(lat,lon,event.location.lat,event.location.lon,N)}} Miles Away</strong>
        </li>
      </ul>
    </li>
  </ol>
</div>

Methods:

methods: {
    getLocation: function () {      
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(this.showPosition, this.errorCallback);
      } else {
        this.error = "Geolocation is not supported.";
      }
    },
    showPosition: function (position) { 
      this.lat = position.coords.latitude;
      this.lon = position.coords.longitude;
      this.googleQuery(position.coords.latitude, position.coords.longitude);
    },
    calcDist: function (lat1, lon1, lat2, lon2, unit) {
      if ((lat1 == lat2) && (lon1 == lon2)) {
        return 0;
      } else {
        var radlat1 = Math.PI * lat1/180;
        var radlat2 = Math.PI * lat2/180;
        var theta = lon1-lon2;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
          dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return Math.round(dist);
      }
    }
  },
  beforeMount() {
    this.getLocation();
  }

Check out this JSFiddle Example showcasing Data Structure and Progress So Far

Answer №1

Utilizing computed properties seems to be the ideal solution for this scenario. Although there are some aspects of the question that remain unclear (such as the criteria for sorting seminars), the general approach outlined below should suffice. The code makes use of multiple computed properties to enhance clarity, but they can be consolidated if necessary.

computed: {
    seminarsWithDistance() {
        return this.seminars.forEach(seminar => {
            seminar.events.forEach(event => {
                event.distance = calcDist(/*...*/);
            });
        });
    },
    seminarsWithSortedEvents() {
        return this.seminarsWithDistance.forEach(seminar => {
            seminar.events.sort((a, b) => a.distance - b.distance);
        });
    },
    sortedSeminars() {
        return this.seminarsWithSortedEvents.sort((a, b) => {
            /* some compare function for two seminars a and b */
        });
    }
}

The next step involves incorporating the computed property in the template:

<ol v-for="seminar in sortedSeminars">

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

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...

Is there a way to define the width of an element within the display:flex property in CSS?

Could you please review the following: https://codepen.io/sir-j/pen/dyRVrPb I am encountering an issue where setting the input [type=range] to 500px doesn't seem to make a difference from 100px, 500px, or 800px. This leads me to believe that display ...

Guide to executing multiple AJAX requests within a single Django view

As I develop my personal spending diary, I encountered a dilemma. To enhance the user experience, I aim to streamline the process of adding new items without refreshing the page. Although I created a single ajax form, I now realize the necessity for two ...

Merging two JSON objects in the absence of one

function fetchData(url) { return fetch(url).then(function(response) { return response.json(); }).then(function(jsonData) { return jsonData; }); } try { fetchData(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).the ...

Explaining the functionality of jQuery validation code

While exploring online tutorials, I stumbled upon a fascinating guide that makes use of jQuery and a validation plugin to validate form input. You can view the live example here: http://jsfiddle.net/nK7Pw/. Everything seems to be working perfectly, but o ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

Issues with parsing XML data when using the xml2js library

I am looking to extract and populate values from a large XML dataset into a mySQL table. The XML data structure is as follows: <BMS version="1.0"> <Summaries> <Summary Booking_strId="CWBL00D7CB8J8U" Booking_lngId="466244159" Trans_lngId="4 ...

Tips for preserving cropped images

Obtained the code for cropping images from this specific link: The code snippet provided in the crop.php file is as follows: <?php /** * Jcrop image cropping plugin for jQuery * Example cropping script * @copyright 2008-2009 Kelly Hallman * More ...

Exploring the distinctions between Django template variables and JavaScript variables

I am currently trying to populate a table in a Django template. The challenge I am facing is comparing cell values between a JavaScript variable and a Django template variable within the same context. Is there a way to perform this comparison without conve ...

Securing API keys in JavaScript

Despite extensive research online, I have been unable to find a suitable solution to a common issue regarding API key protection. The website in question is completely public with no secure login area, relying on API calls to various third-party websites ...

The view "skills.ejs" could not be found in the views directory

Just one month into my full stack program, I am facing a challenge while trying to render index and details pages on a local server. It's been a frustrating experience so far. :) Despite all my efforts and days of troubleshooting, I can't seem t ...

Is there a way to effectively decode the JSON data from a response using the Retrofit

Is there a way to parse a JSON element using Retrofit within a JSON array? For example, if we have the following JSON response: { "trip_id": "trip101", "itinerary": [ { "day": 1, "name": "Arrive Srinagar 5200ft" }, { "da ...

Error: Mapping values to cards resulted in a TypeError: Property 'map' cannot be read from undefined source

After following a tutorial from this website, I attempted to map my post details to cards. However, the error "TypeError: Cannot read property 'map' of undefined" popped up. Despite searching on various platforms like Stack Overflow for a soluti ...

A React component that exclusively renders component tags

After successfully loading index.html with no JavaScript errors, I ran into an issue where nothing was rendering on the page. Upon inspecting the webpage, all I could see was a tag and nothing else. It turns out that I have a component called "list". The ...

Utilizing JSON instead of GeoJSON with AJAX in Leaflet

I am in search of a method to utilize JSON instead of GeoJSON with leaflet, making use of AJAX. The use of JSON and AJAX is imperative for this task. I have successfully called a JSON file using AJAX. However, I am now unsure about how to effectively util ...

Transforming vanilla JavaScript into jQuery

Is there a more efficient way to write this code using jQuery? It's functioning properly in Firefox but not in Safari or Chrome without any error messages, making it difficult for me to troubleshoot. Any suggestions or insights would be greatly appre ...

Trigger the click event on a specific class selector to extract the corresponding ID

I have an HTML Table with each row: <table> <tr><td><a href='#' id='1' class='delete'>delete</a></td></tr> <tr><td><a href='#' id='2' class='de ...

Typescript is unable to comprehend that the initial item in an array of strings is considered to be a string

Here are the functions I am working with: const transitionGroup = ( propertyName: string, durationMultiple = 1, timingFunction = 'linear', delayMultiple = 0, ): string => { // ...more logic here return [propertyName, duration, tim ...

What is the method for converting JSON into a flattened structure resembling a Map?

It is important to note that the JSON structure is unpredictable, as it can be completely arbitrary. We only know that it adheres to the JSON format. For instance, Consider the following JSON: { "Port": { "@alias": "defaultHttp", "En ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...