Switching Visibility of Map Layers through an External Component

Let me start by mentioning that I am a design student utilizing Vue.js for prototyping my senior project. This is merely a prototype of a diary app and not an actual working project.

The issue at hand involves a map component created with Vue2Leaflet, which includes a Tile Layer. On top of the Tile Layer, I have rendered a GeoJSON file containing two sets of coordinates.

In addition, there is a datepicker component that emits values through an EventBus.

The goal is to toggle the visibility of different <l-geo-json> components based on the emitted value from the datepicker. The visibility parameter of each <l-geo-json> is controlled by changing it according to the boolean value from the datepicker. While this parameter does change dynamically, it does not reflect in the map rendering.

I suspect that this might be due to the map component not re-rendering properly.

This is how my map component looks:

<template>
  <div v-if="refresh" id="MapView2">
    <i class="material-icons geoLocate" v-on:click="geoLoc">location_searching</i>
    <l-map :zoom="zoom" :options="{ zoomControl: false }" class="map" :center="center">
      <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
      <l-geo-json :visible="yesterday.day" :geojson="bus.geojson" :options="bus.options"></l-geo-json>
      <l-geo-json :visible="today.day" :geojson="today.geojson" :options="today.options"></l-geo-json>
    </l-map>
  </div>
</template>

... more code ...

Furthermore, my geojson.js file includes:

    import Vue from 'vue';
    export const EventBus2 = new Vue();
    export const data = {
      today: {
        "type": "FeatureCollection",
        "id": "0520",
        "visible": false,
        "features": [ // geojson features and coordinates ]
      },

      yesterday: {
        "type": "FeatureCollection",
        "id": "0520",
        "visible": false,
        "features": [ // geojson features and coordinates ]
      }
  }

The datepicker emits values in MMDD format and the switch statement checks these values against the id property in the GeoJSON data. If a match is found, the corresponding visible property is changed. Although this property is updated upon emission from the datepicker, the changes are not reflected in the map display.

How can this issue be resolved? Is using watch or another method advisable, and if so, how should it be implemented?

Answer №1

To effectively update your instance, you should directly modify the data.

To avoid confusion, consider importing from a different file as data2, instead of using the same name which might be causing issues.

import { data as data2, EventBus2 } from '../assets/geojson/sample-geojson.js';

If your GeoJSON layers do not dynamically change visibility, it's because you initialize your data and day properties using information from data2, but they are not bound to future changes in data2.

A simple solution would be to toggle the data and day properties in your event listener for "mapDay", instead of referring to data2.

EventBus2.$on('mapDay', pickerValue => {
  switch (pickerValue) {
    case data2.today.id:
      this.yesterday.day = true;
      this.today.day = false;
    break;
    case data2.dun.id:
      this.yesterday.day = false;
      this.today.day = true;
    break;
  }
});

In cases where you want both data and data2 to be synced, you can toggle them together. However, keep in mind that changing data2 in another component will not reflect here.

Alternatively, simplify your logic by storing pickerValue in the data instance and comparing it to geojson.id within the binding expression:

:visible="pickerValue === yesterday.geojson.id"

For a more modular approach, expose the pickerValue as a prop so you can modify it at the parent level without relying on events like "mapDay".

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

What is the best way to extract the lodash score from a URL using JSON parsing?

Can someone help me figure out how to extract and store the names from a URL into an array, then parse JSON data to retrieve the lodash score and convert it into a whole number? Any assistance would be greatly appreciated. <head> <title> ...

Utilize external URL in trigger.io's custom UIWebView component

I'm in the process of transitioning my existing backbone application, designed for a native iOS UIWebView, over to trigger.io in order to utilize its image caching and camera access features. The goal is to make this migration quickly and efficiently. ...

Implementing SSL with Vue CLI for local development: A step-by-step guide

I've been exploring how to enable HTTPS with Vue CLI and have come across a method that involves setting "https: true" under devServer in a vue.config.js file. However, I also understand that I need to obtain a self-signed certificate for this setup. ...

Can you explain the process of extracting images from JSON data using AJAX and jQuery?

Hello, I'm looking for guidance on incorporating jquery with AJAX to fetch images from a JSON file and showcase them on my website. Below is the code snippet I have put together. function bookSearch(){ var search = document.getElementById('sea ...

Refreshing AngularJS: How to reload Ngtable with previous data

Currently, I am utilizing NGTable to exhibit data on my webpage. The data is stored in an array and passed through the dataset parameter. However, when I dynamically modify a value in the array, the changes are accurately reflected in the table BUT if I na ...

Tips for personalizing Twitter Bootstrap popover concealment animation

Currently, I am interested in creating a unique hide animation for my popover. Instead of directly modifying bootstrap.js, I would like to implement my own custom code. $.fn.popover = function (option) { return this.each(function () { ...

"Selecting an element through Drag/Drop will result in the element being

INQUIRY I've encountered an issue with a draggable element ($("#draggable")) that interacts with a checkbox ($('#checkable')). When the $('#draggable') is dragged onto a box ($('#droppable')), it checks $(&apos ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

Utilize vue-youtube exclusively within a single Vue Single File Component

I recently started using this package and according to the documentation, it needs to be imported in the main.js file. import VueYoutube from 'vue-youtube' Vue.use(VueYoutube) However, I would like to know how to import this package only in spec ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Tips on accessing information from a JSON file

I am facing an issue while trying to extract data from a JSON object that was passed from the servlet. The keys in my JSON object are numbered, and I need to append these numbers to the names of the keys. The structure of my response is as follows: {"sha ...

The animation is not updating quickly enough

I'm working on a navigation bar that sticks to the top of the page. As the user scrolls down, I want the bar to shrink, and when they scroll back up, it should return to its original size. Issue: The problem I'm facing is that when the user quic ...

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

flatpickr allows you to synchronize the dates of two date pickers by setting the date of the second one to match the date

Currently utilizing flatpikr from . I'm looking to have the initial date of the return picker set to the same date as the outbound picker upon closing the outbound picker. The code I've written achieves this functionality, but there's an iss ...

What is the method for implementing an 'AND' condition in Firebase or its equivalent?

I have a query requirement where I am looking to display only specific data by using an 'AND' statement or its equivalent. To better explain, I am referencing the example given in the Firebase Documentation. // Find all dinosaurs whose height is ...

Run a section of code located in a different file

I have defined some global functions in main.js like this: Vue.prototype._isMobile = function () { return $(window).width() < 768 } //Few more similar functions Now, I want to move these functions to a separate file called util.js: return (function ...