Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components.

Here is the code snippet:

<template>
    <div>
        <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map"></highcharts>
    </div>
</template>
<script>
import { mapState } from 'vuex'
 export default {
   created() {
        this.$store.dispatch('fetchCountries')
    },
    computed:{
        ...mapState(['countries', 'title'])
    },
    data() {
        return {
            mapOptions: {
                chart: {
                    map: 'myMapName'
                },
                title: {
                    text: this.title
                },
                credits: {
                    enabled: false
                },
                legend: {
                    title: {
                        text: 'Number of Confirmed cases'
                    }
                },
                mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'top'
                    }
                },colorAxis: {
                    min: 1,
                    max: 100000,
                    type: 'logarithmic'
                },

                series: [{
                    type: 'map',
                    data: this.countries,
                    joinBy: ['name', 'Country'],
                    name: 'Country: ',
                    minSize: 4,
                    maxSize: '12%',
                    states: {
                        hover: {
                            color: '#a4edba'
                        }
                    }
                }]
            }
        };
    }
};

I tried writing title: { text: this.title} but it didn't work as expected.

Although I am able to retrieve the title and countries state correctly from the $store, when I pass them to mapOptions, the data won't be passed.

The map gets rendered but without any data or title displayed.

Do you have any suggestions on how to resolve this issue?

Answer №1

Ensure that the mapOptions is defined as a computed property rather than directly in the data object. This will ensure proper initialization order:


computed:{
...mapState(['countries', 'title']),
 mapOptions(){ 

  return {
                chart: {
                    map: 'myMapName'
                },
                title: {
                    text: this.title
                },
                credits: {
                    enabled: false
                },
                legend: {
                    title: {
                        text: 'Number of Confirmed cases'
                    }
                },
                mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'top'
                    }
                },colorAxis: {
                    min: 1,
                    max: 100000,
                    type: 'logarithmic'
                },

                series: [{
                    type: 'map',
                    data: this.countries,
                    joinBy: ['name', 'Country'],
                    name: 'Country: ',
                    minSize: 4,
                    maxSize: '12%',
                    states: {
                        hover: {
                            color: '#a4edba'
                        }
                    }
                }]
            }}

}

Answer №2

When working with Vuex, it's important to remember that the `state` is asynchronous. Make sure you set the `data` only after receiving the updated value, not before.

async created() {
    this.$store.dispatch('fetchCountries')
    const title = await this.title
    this.mapOptions.title.text = title
}

Check out the complete code snippet below:

<template>
    <div>
        <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map"></highcharts>
    </div>
</template>
<script>
import { mapState } from 'vuex'
 export default {
   async created() {
        this.$store.dispatch('fetchCountries')
        const title = await this.title
        this.mapOptions.title.text = title
    },
    computed:{
        ...mapState(['countries', 'title'])
    },
    data() {
        return {
            mapOptions: {
                chart: {
                    map: 'myMapName'
                },
                title: {
                    text: ''
                },
                credits: {
                    enabled: false
                },
                legend: {
                    title: {
                        text: 'Number of Confirmed cases'
                    }
                },
                mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'top'
                    }
                },colorAxis: {
                    min: 1,
                    max: 100000,
                    type: 'logarithmic'
                },

                series: [{
                    type: 'map',
                    data: this.countries,
                    joinBy: ['name', 'Country'],
                    name: 'Country: ',
                    minSize: 4,
                    maxSize: '12%',
                    states: {
                        hover: {
                            color: '#a4edba'
                        }
                    }
                }]
            }
        };
    }
};

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

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

Facebook's Thumbs Down to My Code

I've been struggling to integrate a Facebook Like button on my blog using the following code: $("#fblike").append(" <iframe src='http://www.facebook.com/plugins/like.php?app_id=217624258276389&amp;" + window.location.href + "&amp;send ...

"Creating mobile apps with Cordova using Vue framework, running on Android Virtual

After following a tutorial, I successfully created my own Android Cordova app using this plugin: https://www.npmjs.com/package/vue-cli-plugin-cordova I stored all the images for my app in the public folder. The structure of my project folder is as follows ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

Does vite handle module imports differently during development versus production?

I am currently working on incorporating the jointjs library into a Vue application. It is being declared as a global property in Vue and then modified accordingly. Below is a basic example of what I am trying to achieve: import Vue from 'vue'; im ...

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

tips for getting two ajax json Data from .net

When working with .NET, I am encountering an issue where I need to send two sets of JSON data (test1 and test2) to a .NET controller using JavaScript (ajax). Here is the code snippet for sending the data: .ajax({ type: 'POST', url ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

Issue with Bootstrap alignment on the right side

Just finished creating my 'navbar' in bootstrap, but I'm having trouble aligning my unordered list to the right. It's staying in the middle no matter what I try. Can someone please help? Feeling really confused... HTML: <div class= ...

What is the origin of this MouseEvent attribute?

In my jsfiddle project, there is a white square that can be moved around by the mouse. When the mouse button is released, it displays the x and y coordinates of the square. To see the project in action, visit: http://jsfiddle.net/35z4J/115/ One part of t ...

Guide on redirecting a server URL to another URL when users access it through a static QR code

Can anyone help me with a dilemma I'm facing? I have static QR codes printed on thousands of boxes that direct to the wrong URL. The designer didn't make the code dynamic, so editing through the generator's interface is not an option. We ar ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...