Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality works but the popup fails to open. Suspect there might be an error in the changeSelection function. Seeking suggestions for resolution.

The map is available on GitHub. You can access the map here to review the issue. Below is the JavaScript code snippet:

 function myFunction() {
  var map = L.map('map').setView([51.426002, 7.503215], 8);
  // enhance mobile experience
  if (map.tap) map.tap.disable();
  L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
    attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
    maxZoom: 16
}).addTo(map);
  map._layersMinZoom=8;

var selectedRadio = 0;

var RadioByName = {};

  var markersLayer = new L.LayerGroup();  

  map.addLayer(markersLayer);
  var controlSearch = new L.Control.Search({
    position:'topright',    
    layer: markersLayer,
    initial: false,
    zoom: 12,
    marker: false,
    textPlaceholder: 'Search...'
  });
  map.addControl(controlSearch);

var radioMarkers = [];

var icon = L.icon({
            iconUrl: 'icons/icon.png',
            iconSize:     [30, 32],
            iconAnchor:   [15, 32],
            popupAnchor: [0, -32]
          });

for(i=0; i<radio.length; i++) {
    RadioByName[radio[i].redaktion] = radio[i];

    var radio_marker = [];

    radio_marker.redaktion = radio[i].redaktion;  
    radio_marker.lat = radio[i].lat;
    radio_marker.long = radio[i].long;
    radio_marker.stadt = radio[i].stadt;
    radio_marker.redaktion_link = radio[i].redaktion_link;

    var title = radio_marker.redaktion,
        loc = [radio_marker.long, radio_marker.lat],    
        radio_marker = new L.marker(new L.latLng(loc), {
          icon: icon,
          title: title,
          stadt: radio_marker.stadt,
          redaktion_link: radio_marker.redaktion_link
      });

    markersLayer.addLayer(radio_marker);  


    radio_marker.on('click', function(e) {
        changeSelection(e.target.options.title);
        map.setView([e.target._latlng.lat, e.target._latlng.lng]);

        var myPopup = L.popup()
        .setContent("<strong>" + e.target.options.redaktion_link + "</strong> | " + 
          e.target.options.stadt);
          e.target.bindPopup(myPopup).openPopup();
    });

    radioMarkers.push(radio_marker);  
} 

function changeSelection(radioRedaktion) {
    if(selectedRadio == 0 || selectedRadio != radioRedaktion) {
        selectedRadio = radioRedaktion;

        for(i=0; i<radioMarkers.length; i++) {
            if(radioMarkers[i].options.title == radioRedaktion) {
                radioMarkers[i].openPopup();                    
            }
        }           
    }
    else {
        selectedRadio = 0;
    }
}
}

Answer №1

After examining the code in bindPopup, it appears that if a popup is already bound, subsequent calls to bindPopup will not have any effect.

For your click handler to work correctly, you need to make sure to include a call to unbindPopup as well:

radio_marker.on('click', function(e) {

  changeSelection(e.target.options.title);
  map.setView([e.target._latlng.lat, e.target._latlng.lng]);

  var myPopup = L.popup().setContent(
    "<strong>" +
    e.target.options.redaktion_link +
    "</strong> | " +
    e.target.options.stadt
  );
  e.target
    .unbindPopup()
    .bindPopup(myPopup)
    .openPopup();
});

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

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

How can we automatically delete a message in DiscordJS after a certain amount of time has passed?

I am inquiring about DiscordJS and have a specific question. My query is regarding how to correctly remove a message sent by the bot on Discord. Admittedly, I am new to DiscordJS so please bear with me if this is a basic question. I appreciate all respo ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

Is there a more effective way to structure my code than using multiple "IF/ELSE" statements?

Here is the current code snippet that I have: (category=="Ljud & Bild") ? byId("nav_sub_ljud_bild").style.display='block' : byId("nav_sub_ljud_bild").style.display='none'; (category=="Datorer") ? byId("nav_sub_datorer").style.disp ...

Encountering an unexpected issue with $urlMatcherFactory during an AngularJS service unit test

I am seeking guidance on writing a proper unit test for a service using the jasmine framework and karma as the test runner. Below is the implementation in example-service.js: export default class ExampleService { constructor($resource, $http, $urlMatcher ...

What is the best way to render components with unique keys?

I am currently working on a dashboard and would like to incorporate the functionalities of React-Grid-Layout from this link. However, I am facing an issue where the components are only rendered if they have been favorited. In order to utilize the grid layo ...

Updating website content dynamically using Javascript and JSON-encoded data

My programming code seems to be acting oddly. I have structured my data in a JSON object as follows: injectJson = { "title": "Champion Challenge Questions", "rules": [ { "idChrono": "chrono-minute", "text": "Top is missing!", ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

Retrieve content inside an iframe within the parent container

Hey there! I've been working on adding several iframes to my webpage. Each iframe contains only one value, and I'm trying to retrieve that value from the parent page. Despite exploring various solutions on Stack Overflow, none of them seem to be ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

Searching for an AngularJS and Bootstrap Dual Listbox Solution

I need a component like this to integrate into my project: I am hoping to add it using npm. However, I have tried some of the examples available but faced issues (encountered exceptions or only found bower instead of npm). The following are the examples ...

Tips for identifying and swapping values/parameters in a URL during redirect

To provide more clarity on my inquiry, I will outline the details below: There are three links: Link A, Link B, and Link C Link A: {c_val} Link B: {id} Link C: In the database, there is a value adgaf7g6adf6gadfg8a86fgs9f6g The main focus here is when ...

VueJS Unit Testing: Exploring the Content of Attributes- What to Test?

I'm currently facing some challenges with my initial VueJS unit tests using Jest. Although I grasp the concept and have already executed my first set of successful tests, I find myself pondering over the question of "What aspects should I test?" For ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

Execute a PHP function when a post is clicked using JavaScript

I have a script that shows an image depending on database results. When a user clicks the image, it changes to a new one. The green_star signifies that both $user_id and $thedb_id are in the database, while the grey_star indicates they are not. I want to b ...

What is the best way to add or delete data when specific radio buttons are chosen?

Hey there, I'm facing an issue where the data is being appended regardless of which radio button is selected. Can someone help me with a solution on how to properly add and remove data based on the selected radio button? $( document ).ready(functio ...

What is the best way to enable a DOM element's height to be resized?

I have a widget displayed in the corner of my browser that I would like to make resizable by dragging the header upwards to increase its height. The widget's position remains fixed with its bottom, left, and right properties unchanged, but I need the ...