Encountered an issue while attempting to append to my Leaflet map's LayerGroup

I've encountered an issue while trying to integrate LayerGroup into my map in order to enable Leaflet Control Search for city-based searches. The problem seems to be related to an undefined return value or something similar. Since I'm relatively new to Leaflet, I'm not entirely certain if that's the root cause of the problem.

I am using vue-leaflet for the map display. Below is the code snippet:

HTML:

<template>
  <div id="actingMapDiv" class = "vh-100 d-flex justify-content-center align-items-center">

    <div style="height: 900px; width: 90%" class = "map d-flex flex-column justify-content-center align-items-center">
      <h2>Check in our map the situation of requests in your area</h2>
      <div class = "void05"></div>

      <l-map ref="map" 
        v-if="showMap"
        :zoom="zoom"
        :center="center"
        :options="mapOptions"
        style="height: 80%"
        @update:center="centerUpdate"
        @update:zoom="zoomUpdate"

        class = "d-flex flex-column justify-content-center align-items-center"
      >
        <l-tile-layer :url="url" :attribution="attribution" />
      </l-map>
      </div>
    </div>
</template>

The script:

<script>

import { latLng } from "leaflet";
import { LMap, LTileLayer } from "vue2-leaflet";

import L from 'leaflet';

export default {
  name: "Example",
  components: {
    LMap,
    LTileLayer
  },
  data() {
    return {
      zoom: 8,
      center: latLng(42.886027, -7.970126),
      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      attribution:
        '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      mapOptions: {
        zoomSnap: 0.5
      },
      showMap: true
    };
  },


  methods: {
    zoomUpdate(zoom) {
      this.currentZoom = zoom;
    },
    centerUpdate(center) {
      this.currentCenter = center;
    }
  },

  mounted: function() {
    var map = this.$refs.map;

    console.log("My Map", map);
    console.log("L", L);

    var searchLayer = L.layerGroup().addTo(map);
    map.addControl( new L.Control.Search({layer: searchLayer}) );
  }
}
</script>

Console errors:

TypeError: "t is undefined"
    addLayer leaflet-src.js:6665
    addLayer LMap.js:357
    addTo leaflet-src.js:6559
    mounted actingMapPage.vue:74
    VueJS 12

This error then lead me to the following line:

var searchLayer = L.layerGroup().addTo(map);

AFTER FIX:

Additional imports were added:

import 'leaflet-search';
import "leaflet-search/dist/leaflet-search.src.css";

Furthermore, here is the fix solution provided by the verified answer:

mounted: function() {
    var map = this.$refs.map.mapObject;

    var searchLayer = L.layerGroup().addTo(map);
    map.addControl( new L.Control.Search({layer: searchLayer}));
  }

Answer №1

One potential challenge arises when using vue2-leaflet, where accessing the mapObject is necessary.

To remedy this, follow these steps:

var map = this.$refs.map.mapObject; // HERE!
var searchLayer = L.layerGroup().addTo(map);
map.addControl(new L.Control.Search({layer: searchLayer}));

Additionally, ensure that you have imported the required css and js files for leaflet-search.

This should hopefully resolve any issues you encounter!

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

Discussing the importance of setting up variables in an Angular Factory

I am trying to develop a factory that will generate a PlayerList, but I am encountering issues with accessing the variables I have defined in the initialize function. Below is the code snippet: app.factory("PlayerList", function(){ // Define the Play ...

Only encountering a 401 error with API requests in the production environment

Having an issue where Laravel 6 API requests are functioning smoothly on the local server, but encountering a 401 error on the remote server. Both servers are nginx-driven with php-fpm setup. Authentication is done using Laravel Passport ...

Filtering an array using Vue.js

I'm currently working on filtering an array using a computed property in vue.js. My goal is to search across multiple fields such as name, state, and tags. Here is my data: events: [ { id: 1, name: 'Name of event', url: &apos ...

The process of assigning a class to a specific range of elements using nth-child

I'm attempting to apply a class to a range of nth-child elements using this code, but it doesn't seem to be working: $('.station li:nth-child(' + strno + '):nth-child(' + endno + ')').attr('class', 'c ...

Use an external javascript file in AngularJS if permitted

To ensure that my HTML page only loads an external JavaScript file when the variable $scope.jsallowed is set to true, I attempted the following code implementation within my AngularJS based page: <script src="assets/js/slider.min.js" data-ng-if="jsallo ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

A guide on organizing the visible items in a vue table

I need help with two issues related to this code snippet. 1. The first problem arises when I have an array containing four items with IDs [1, 2, 4, 5, 7]. If I select to display 2 items per page and click on the sort function, it shows entries with IDs 1& ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

Always make sure to call for files using their respective names in

Here is how my project structure looks like: . ├── node_modules ├── package.json ├── www │ ├── css │ ├── js │ ├── file.js │ ├── folder │ ├── file2.js │ ├─ ...

Vue components: Using `object[key]` as a prop does not trigger reactivity

I'm attempting to bind a value from an Object into the prop of a Component, but unfortunately it is not reacting as expected. Despite using $this.set, the reactivity issue persists. Below is my template: <div class="grid"> <emoji-card v-fo ...

Error TS2304: Unable to locate identifier 'RTCErrorEvent'

I am currently working on a WebRTC application using Quasar, typescript and Vue. In my code snippet below, I am encountering an issue where I don't get any errors in WebStorm (as it uses the project's eslint config), and I can navigate to the def ...

No entries found in the Nuxt/content module's array

<template> <div> <input v-model="searchQuery" type="search" autocomplete="off" placeholder="Search Articles" /> <ul v-if="articles.length"> ...

Reverse the text alteration when the user leaves the field without confirming

Upon exiting a text box, I aim to display a confirmation dialogue inquiring whether the user is certain about making a change. If they select no, I would prefer for the text box to revert back to its original state. Is there an uncomplicated method to ach ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

Utilizing Odoo Point of Sale feature on product selection

Can someone help me identify the function that is triggered when a product is clicked on at the point of sale? I am looking to add some code that will automatically apply a discount when a product is added to an order. Appreciate any assistance! ...

How to print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected. function convertToBase64() { var selectedFile = document.getElementById("inputFile").files; if (selectedFile.length > 0) { var fi ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Is there a specific HTML tag available to instruct the browser to cache my HTML and/or CSS files for future use?

Up to this point, my research has indicated that enabling JavaScript and CSS browser caching typically requires server side settings such as .htaccess. Is there any HTML tag or configuration within the HTML page or JavaScript that can instruct the browse ...

Having trouble activating a function through the context API using React hooks

I'm attempting to initiate a function via my CartContext API upon a click event, but it doesn't seem to be functioning correctly. I have verified that the method is operational, however, when I introduce the context function, nothing occurs. See ...

What type of response does XHR provide when there is no connection available?

Imagine I launched Google Chrome and its corresponding extension. The extension relies on the XmlHttpRequest object for functionality. However, upon starting the browser, I realized there is no internet connection available. In this scenario, what will t ...