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

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

Developing a pagination element

I'm currently working on developing a pagination component. Let's say my API returns "pages": 9 For instance, if there are 9 pages to display, I want to limit the list to show only 5 pages and add three dots, as shown in the image. Is ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

How can I declare CSS variables in Next.js components' module.css just like in global CSS?

When writing CSS in our global file, we often define variables and styles like this: :root{ --orange:#e67e22; --black:#333; --light-color:#777; --border:.1rem solid rgba(0,0,0,.2); --box-shadow:0 .5rem 1rem rgba(0,0,0,.1); } *{ mar ...

What is the best way to retrieve and display a PDF file through an API in VueJS?

I am looking to display a file from my API in my VueJS client. Specifically, when accessing a certain URL, the file (pdf, text, or image) should open if the browser supports it (similar to how Chrome opens PDFs). I want to achieve this using VueJS or just ...

Create a new canvas for each iteration of a Vue.JS template loop

I'm having trouble figuring out how to initialize a local "signaturePad" canvas for each loop or required signature. Additionally, I am interested in binding "dataURL" to signaturePad.toDataURL("image/jpg"). This means displaying the dataURI for ever ...

Utilizing jQuery to generate dynamic nested divs within the ul li tags

I am looking to dynamically generate nested divs within a ul li. The goal is to create the following structure programmatically: <ul> <li> <div class="videoThumbnail"> <img src="./img6.jpg" /> &l ...

An error occurred: [object Object] does not contain the function 'bootstrapDatepicker'

After spending countless hours searching for a solution, I continue to encounter the dreaded 'Uncaught TypeError' without any successful resolutions. The issue seems to stem from a clash between tribe-events-ajax-calendar.js and foundation.min.j ...

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...

Creating a dynamic star rating system using CSS

A unique code pen project showcasing a pure css star rating interface can be found at: https://codepen.io/yaworek/pen/JJpEaZ Below is the custom css part: /*** * Custom Pure CSS Star Rating Widget for Bootstrap 4 * * www.TheMastercut.co * ***/ ...

Error: The 'then' method cannot be invoked on an undefined object in the Parse.File.save function

I am currently utilizing the Javascript API for parse.com within an Angular JS application. My goal is to successfully save or update the user's profile picture. Below is the code snippet that I have been working with: Some HTML . . . <input type ...

Error: Unable to find the specified "location.ejs" view in the views directory

I am encountering the following error - Error: Failed to find view "location.ejs" in views folder "e:\NodeJs_Project\geolocationProject\views" at Function.render Your help in resolving this issue would be greatly appreciated. server.js ...

How to Refresh EJS Template in an Express Node.js Application

Currently, I am integrating discord.js with express and facing a challenge. I want my webpage to automatically update whenever the client.on("message") event is triggered. According to my knowledge and research, it seems that rendering an ejs template is o ...

Error: JSON parsing failed due to an unexpected token 'S' at position 17

Trying to troubleshoot a syntax error in JSON.parse() within a product warranty registration process. Transitioning from Java to AngularJS for this project, I have an API built in PHP handling the back-end operations and a controller managing communication ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

Arrange JSON information in an HTML table with distinct header rows for every data category

I have a JSON object with a key:value pair named callRoot. Some examples of values for this pair are @S, @C, and @W. There are multiple objects that share the same value and I want to create an HTML table head row at the beginning of each group and repeat ...

Updating documents in a mongoDB collection can be done by simply

I require an update to my database that will modify existing data, as illustrated below: existing data => [{_id:"abnc214124",name:"mustafa",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:32,etc...}, {_id ...

Using TextField with nested Object for onChange Event

I have a question that needs some clarification. Here is the current structure of my object. Within "allgemein," there are currently two variables, but they will increase over time... { id: "Abadi", name: "Abadi", type: "SC", allgemein: { ...

Is there a way to retrieve text content from a modal using JavaScript?

I am using ajax to fetch values from my table. $(data.mesIzinTanimList).each(function (index, element) { if (element.izinTanimiVarmi == 'yok') tr = "<tr class='bg-warning text-warning-50' row='" + element. ...