The error message "Cannot read property 'properties' of undefined" is being thrown by the leaflet-search plugin

I attempted to implement the leaflet-search feature using a Vue-cli component.

However, when I initiate a search, I encounter the following error message specifically related to the leaflet search function:

Uncaught TypeError: Cannot read property 'properties' of undefined at NewClass._searchInLayer (leaflet-search.src.js:569) at leaflet-search.src.js:634 at NewClass.eachLayer (leaflet-src.js:6693) at NewClass._recordsFromLayer (leaflet-search.src.js:633) at NewClass._fillRecordsCache (leaflet-search.src.js:774) at leaflet-search.src.js:736

Initializing the map -

initMap() {
  this.map = L.map('map', {
    center: [55.75, 37.61],
    zoom: 11,
    layers: this.layer
  })
  this.tileLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution:
      '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy;'
  })
  this.tileLayer.addTo(this.map)

  // add marker
  this.createMarkerLayer(this.marker)
  })
},

Creating the marker layer -

createMarkerLayer(data) {
  const promiseMarkerArray = this.createMarkerArray(data)
  promiseMarkerArray
    .then(res => {
      this.markersArray = res
      this.markerLayer = L.layerGroup(this.markersArray)
      this.addMarker()
    })
    .catch(err => {
      console.log(err)
    })
},

// create array of markers
createMarkerArray(data) {
  return new Promise((res, rej) => {
    return res(data.map(item => {
      let icon = null
      item.agent !== null ? icon = this.iconAgent : icon = this.iconDefault
      const marker = L.marker(item.coordinates, { title: item.title, icon: icon })
      marker.bindPopup('<p>' + item.title + '</p>').openPopup()
      marker.on('click', () => {
        this.sidebarToggle(item.id)
      })
      marker.alarm = item.alarm
      marker.agent = item.agent
      return marker
    }))
  })
},

Setting up the leaflet-search layer -

createSearch() {
  const markersLayerT = new L.LayerGroup()  
  this.map.addLayer(markersLayerT)

  this.searchLayer = new L.Control.Search({
    position: 'topleft',
    layer: markersLayerT,
    initial: true,
    zoom: 18,
    marker: false
  })
  this.map.addControl(this.searchLayer)

  for (const i in this.marker) {
    const title = this.marker[i].title  
    const loc = this.marker[i].coordinates      
    const marker1 = L.marker(loc, { 'title': title }) 
    marker1.bindPopup('title: ' + title)
    markersLayerT.addLayer(marker1)
  }
}

The issue may be with the layer.feature.properties not passing the value correctly to the function.

Answer №1

Upon inspection of the data used to populate the layer, it was noted that some leaflet searches returned empty title fields. To address this issue, a check for empty values and a default title were added.

item.title= item.title || 'Default title' // Check and set default value

for (const i in this.marker) {
    const title = this.marker[i].title  // Retrieved value
    item.title= item.title || 'Default title' // Check and set default value
    const loc = this.marker[i].coordinates      // Retrieved position
    const marker1 = L.marker(loc, { 'title': title }) // Search property
    marker1.bindPopup('Title: ' + title)
    markersLayerT.addLayer(marker1)
}

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

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Exploring ways to enhance Bootstrap Navigation by adding extra link options. Seeking a resolution using jQuery

Are you looking for a solution to handle site navigation with a larger number of links? When more links are added, they display in multiple lines which might not be the desired layout. You can view an example of this issue in the attached image: See here a ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Obtaining various values for checkboxes using dynamic data in a React application

Retrieve all checkbox values dynamically import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import FormControlLabel from "@mui/material/FormControlLabel"; import axios from "axios"; expor ...

Exploring jQuery's parent selector for traversing the DOM

I am currently working with an array that inserts articles into my website. I have a specific requirement where, upon clicking the title (h3), I need to display more information based on the article's index. To achieve this, I believe I should travers ...

Encountered a 404 error while trying to install body-parser

Hey there, I'm new to this and ran into an issue while trying to install the body-parser package. Can you please guide me on how to resolve this problem? D:\Calculator>npm install body-paeser npm ERR! code E404 npm ERR! 404 Not Found - GET htt ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

Function is not triggered in React component

When the LoginPage calls AuthForm, the structure is as follows: function mapDispatchToProps(dispatch: Redux.Dispatch<any>) { return { signUpWithEmail: function(email: string, password: string) { // bla bla }, }; } handleForm ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

AngularJS wildcards can be used in filters for a versatile approach

Is there a more efficient way to filter a list of values using wildcards? searchString = "ab*cd" The goal is to retrieve all values that begin with "ab" and end with "cd". One approach I've tried involves splitting the string into multiple substrin ...

Create a Jest unit test for a specific function

I started my first unit test in react with jest this afternoon. The initial 5 tests I need to do involve testing the return functions, which isn't too difficult. However, I'm struggling to understand how to perform unit testing on my login funct ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

dynamically change the information in AngularJS

I need to work with two different endpoints: http://localhost:3000/entry (POST) The keys required are: fname, lname, and age. To submit a form, we have to send a POST request to this URL. http://localhost:3000/entries (GET) This endpoint will retrieve ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

Issue with the AngularJS build in Yeoman

After setting up Yeoman and Bootstrap for an AngularJS project, I utilized the grunt server command for debugging and coding. However, when I tried using the 'grunt build' command, it generated a dist folder. Unfortunately, when I attempted to ru ...