Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
Bind more popups to the same marker or merge popups content

I have a JSON in which there are places with their coordinates and their textual content to be inserted in the relative marker's popup.

If in the JSON there is 2 times the same place (with the same coordinates), I have to bind 2 popups with their respective contents on the same marker (or at most I have to update the popup with the new content while keeping the old one).

<html>
<head>
    <!-- Libraries leaflet/jquery for may project-->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
   <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
</head>

<body>
     <div id="map" style="width:100%; height: 100%"></div>
     
     <script>
     // my json data
     var data = [
        {
          "name" : "Location A",
          "lat" :"27",
          "long" : "29",
          "popupContent" : "content 1"
        },
        {
          "name" : "Location B",
          "lat" :"51",
          "long" : "12",
          "popupContent" : "content 2"
        },
        {
          "name" : "Location A",
          "lat" :"27",
          "long" : "29",
          "popupContent" : "content 3"
        }
     ]


     //init leaflet  map
     var map = new L.Map('map');                       
            
     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
        maxZoom: 18
     }).addTo(map);
     var italy = new L.LatLng(42.504154,12.646361); 
     map.setView(italy, 6);



     //iterate my json data and create markers with popups
     for(let key in data){
       L.marker([data[key].lat,data[key].long]).bindPopup(data[key].popupContent).addTo(map)
     }
     </script>

</body>
</html>

With this code, the third place overrides the first, and I have a single marker and a single popup with written "content 3".

I would like 2 popups (one with written "content 1" and one with "content 3") or one single popup with all two contents.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The easiest way to address similar use case is simply to use a clustering plugin, typically Leaflet.markercluster, so that it separates your Markers which are on the same position or very close (actually your 3rd place does not "override" the first, in the sense of replacing, it just sits on top of it, in the sense of overlapping).

The added advantage is that it naturally separates Markers which are very close one to each other, but still at slightly different positions, which below heuristics will not catch.

var mcg = L.markerClusterGroup();

     //iterate my json data and create markers with popups
     for(let key in data){
       L.marker(latLng).addTo(mcg) // Add into the MCG instead of directly to the map.
     }

mcg.addTo(map);

Demo: https://plnkr.co/edit/B0XF5SSpQ27paWt1

Now in your case, you may not be wary of closeby Markers, but really have data that apply to same places (in your data, name and coordinates of items 1 and 3 are identical).

In that case, a solution could simply be to rework your data first (possibly in runtime) to merge the popup content of all items that have the same name and/or coordinates (depending on how exactly you can identify identical items).

For example using Lodash groupBy:

var groupedData = _.groupBy(data, "name"); // Depends on how you identify identical items

     //iterate my json data and create markers with popups
     for(let key in groupedData){
       var items = groupedData[key];

       // Coordinates of first item, all items of this group are supposed to be on same place
       var latLng = [items[0].lat, items[0].long];

       // Merge all popup contents
       var popupContent = items.map(item => item.popupContent).join("<br/>")
       L.marker(latLng).bindPopup(popupContent).addTo(map)
     }

Screenshot marker with open popup and merged content

Demo: https://plnkr.co/edit/D7TzdaBVRvJr2sid

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda