Как заставить Leaflet.markercluster работать с CMS в Webflow - PullRequest
0 голосов
/ 29 мая 2019

Я нашел скрипт Leaflet с интеграцией Webflow CMS от forresto на Webflow. ССЫЛКА: https://webflow.com/website/Geo-Components-for-Webflow

Я бы хотел включить в код javascript Leaflet.markercluster, так как у меня много мест, и он начинает запутываться.

Кто-нибудь может помочь с кодом?

Я попытался включить markercluster.js и L.markerClusterGroup

Первый код:

<script>
window.addEventListener('DOMContentLoaded', function() {

  var places = Array.from(document.querySelectorAll('[data-geo-place]'));
  places.forEach(function(el){
    var elCoords = el
      .querySelector('[data-geo-coordinates]')
      .textContent
      .split(',')
      .map(Number);
    var value = {coordinates: {
      latitude: elCoords[0], 
      longitude: elCoords[1],
    }}
    el.value = value;
    // Just for debug(?)
    el.setAttribute('data-geo-value', JSON.stringify(value));
  });

});
</script>

Второй код:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"
   integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
   crossorigin=""/>
 <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"
   integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA=="
   crossorigin=""></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.0.4/leaflet.markercluster.js"></script>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.0.4/MarkerCluster.Default.css" />

<script>
window.addEventListener('DOMContentLoaded', function() {

  Array.from(document.querySelectorAll('[data-geo-map]')).forEach(function(mapEl) {
    var mapId = mapEl.getAttribute('data-geo-map');
    var map = L.map(mapEl);

        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
         maxZoom: 18,
         id: 'mapbox.light',
          accessToken: 'NOT SHOWN HERE',
        style: 'NOT SHOWN HERE '
        }).addTo(map);

    var myIcon = L.icon({
    iconUrl: 'myIcon.svg',

    iconSize:     [38, 38], // size of the icon
    iconAnchor:   [19, 38], // point of the icon which will correspond to marker's location
    popupAnchor:  [0, 0] // point from which the popup should open relative to the iconAnchor

});

    var allCoordinates = [];
    var markers = []
    Array.from(document.querySelectorAll('[data-geo-place="' + mapId + '"]')).forEach(function(placeEl) {
      var coordinates = [placeEl.value.coordinates.latitude, placeEl.value.coordinates.longitude]
      allCoordinates.push(coordinates);
      var marker = L.markerClusterGroup(coordinates).addTo(map);
      var marker = L.marker(coordinates, {icon: myIcon}).addTo(map)
            .bindPopup(placeEl.innerHTML);
      markers.push(marker);
      // Click place element to pan map
      placeEl.addEventListener('click', function(event) {
        map.panTo(coordinates, {animate: true, duration: 0.5});
        // Close other popups
        markers.forEach(function(otherMarker) {
          otherMarker.closePopup();
        });
        marker.openPopup();
      });
    });

    // Zoom to the markers added
    map.fitBounds(L.latLngBounds(allCoordinates));
  });

});
</script>

1 Ответ

0 голосов
/ 06 июня 2019

Добро пожаловать в SO!

Похоже, вы просто перепутали MarkerClusterGroup с маркером.

В Leaflet у вас есть Группы слоев , которые содержат дочерние слои, такие как маркеры,Ваша MarkerClusterGroup является такой группой слоев.

Просто создайте экземпляр группы за пределами вашего цикла forEach (но внутри цикла карт, поскольку вам нужна хотя бы одна группа на карту).

Затем добавьтеваши маркеры в него, а не прямо на карту.

mapEls.forEach(mapEl => {
  const map = L.map(mapEl)

  const mcg = L.markerClusterGroup().addTo(map)

  placeEls.forEach(placeEl => {
    const coordinates = [placeEl.value.coordinates.latitude, placeEl.value.coordinates.longitude]
    const marker = L.marker(coordinates).addTo(mcg)
  })
})

Примечание: что касается прослушивателя щелчка, чтобы открыть всплывающее окно маркера, у вас будут проблемы, когда маркер будет скрыт под кластером.Используйте mcg.zoomToShowLayer(marker, cb) и откройте всплывающее окно tje в обратном вызове cb.У вас должны быть другие сообщения на эту тему.Не стесняйтесь, чтобы открыть новый вопрос, если вам нужна помощь.

...