Листовка использует OverlappingMarkerSpiderfier (OMS) и пользовательские слои одновременно - PullRequest
0 голосов
/ 27 сентября 2018

Я создал карту Leaflet, в которой есть ряд слоев, которые я могу включать и выключать (данные извлекаются из базы данных с помощью серии вызовов getJSON).

У меня есть другая карта Leaflet, котораяиспользует те же данные и плагин OMS для маркеров пауков, когда они находятся близко друг к другу.

Я хотел бы использовать обе эти функции на одной и той же карте -> выбрать, какие слои отображать, а затем разбить любые маркеры, которые находятся рядом при щелчке.Кто-нибудь знает как это сделать?Добавление команд map.addLayer(marker); и oms.addMarker(marker); после определения маркеров не работает со слоями, которые я могу переключать.Я получаю ошибку TypeError: b.getLatLng is not a function. (In 'b.getLatLng()', 'b.getLatLng' is undefined)

со слоями:

<!DOCTYPE html>
<html>
<head>
   <title> Map with Layers</title>

   <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 = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>


  <script src="oms.min.js"></script> <!-- spiderfy plugin -->
   <style>
   #map {
      height:800px;
   }
   </style>

   <script type = "text/javascript">
   function init(){

      var osmLink = "<a href='http://www.openstreetmap.org'>Open StreetMap</a>"
      var map = new L.map('map',{minZoom:3,maxZoom:10}).setView([ -20.91, 142.70], 5);
      osmMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; ' + osmLink, maxZoom: 10,}).addTo(map);
      attrLink = 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'
      var terrainMap = L.tileLayer( 'http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg',{
         attribution: attrLink,
         maxZoom: 10,
      }).addTo(map);
      var baseLayers = {
         "Open Street Map":osmMap, "Stamen Terrain": terrainMap
      };

      L.control.layers(baseLayers).addTo(map);

         var oms = new OverlappingMarkerSpiderfier(map);

         showLayers(map);

      function showLayers(map) {

         const getData = () => Promise.all([$.getJSON("getData1.php"),$.getJSON("getData2.php")]);

         getData()
         .then(([data1,data2]) => {
            let jend = 2;
            let myLayerGroup1;
            let myLayerGroup2;

            var myIcon = L.icon({
               iconUrl: "./images/iconimage.png",
               iconSize: [24,24],
               iconAnchor: [12,24]
            });

            for (j = 1; j<= jend; j++){

                  let data = eval("data"+j);

                  let markerlist = [];

                  for (let i = 0; i< data.length; i++) {
                     let location = new L.LatLng(data[i].siteLatitude, data[i].siteLongitude);
                     let marker = new L.Marker(location, {
                        icon: myIcon,
                        title: 'thetitle' });

                        let studyTitle = "Paper Title"
                        let urlLink = "URL";

                        let content = "<h2>" + studyTitle + "</h2>" + "<p>" + '<a href='+urlLink+'>' + urlLink+ '</a>' + "</p>" + "<p> <b>" + "</b></p>";

                        marker.bindPopup(content, {
                           maxWidth: '400'
                        });
                        // map.addLayer(marker);
                        // oms.addMarker(marker);

                        markerlist.push(marker);

                     } // end loop through data to extract marker and content

                     // create the layers and add to the map:
                     switch(j){
                        case 1: myLayerGroup1 = L.layerGroup(markerlist);
                        map.addLayer(myLayerGroup1);
                        oms.addMarker(myLayerGroup1);
                        break;
                        case 2: myLayerGroup2 = L.layerGroup(markerlist);
                        map.addLayer(myLayerGroup2);
                        break;
                        default: alert("Error");
                     } // end switch
                  }; // end j loop through all the different datasets

                  var overlays = { //overlay controls on the map
                     "layer 1":myLayerGroup1,
                     "layer 2":myLayerGroup2,
                  };
                  L.control.layers(null,overlays).addTo(map);  // add control to the map
               }); // end of then
         } // end of function showLayers
      };// end of function init
      </script>
      </head>
      <h1>Page Heading</h1>
      <body onload=init()>
      <div id = "map"> </div>
      </body>
      </html>

со пауком:

<!DOCTYPE html>
<html>
<head>
   <title>Spidering Map</title>

   <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 = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>


  <script src="oms.min.js"></script> <!-- spiderfy plugin -->
   <style>
   #map {
      height:800px;
   }
   </style>

   <script type = "text/javascript">
   function init(){

      var osmLink = "<a href='http://www.openstreetmap.org'>Open StreetMap</a>"
      var map = new L.map('map',{minZoom:3,maxZoom:10}).setView([ -20.91, 142.70], 5);
      osmMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; ' + osmLink, maxZoom: 10,}).addTo(map);
      attrLink = 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'
      var terrainMap = L.tileLayer( 'http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg',{
         attribution: attrLink,
         maxZoom: 10,
      }).addTo(map);
      var baseLayers = {
         "Open Street Map":osmMap, "Stamen Terrain": terrainMap
      };
      L.control.layers(baseLayers).addTo(map);

      var oms = new OverlappingMarkerSpiderfier(map);
      var popup = new L.Popup({
        closeButton: false,
        offset: new L.Point(0.5, -24)
      });
      oms.addListener('click', function(marker) {
        popup.setContent(marker.desc);
        popup.setLatLng(marker.getLatLng());
        map.openPopup(popup);
      });
      oms.addListener('spiderfy', function(markers) {
        for (var i = 0, len = markers.length; i < len; i++) markers[i].setIcon(new lightIcon());
        map.closePopup();
      });
      oms.addListener('unspiderfy', function(markers) {
        for (var i = 0, len = markers.length; i < len; i++) markers[i].setIcon(new darkIcon());
      });

      showLayers(map);

      function showLayers(map) {

         const getData = () => Promise.all([$.getJSON("getMonitoring.php"),$.getJSON("getModelBased.php")]);

         getData()
         .then(([data1,data2]) => {
            let jend = 2;
            let myLayerGroup1;
            let myLayerGroup2;

            for (j = 1; j<= jend; j++){

               let data = eval("data"+j);

               let markerlist = [];
               // define the icon:
               var myIcon = L.icon({
                  iconUrl: "./images/iconImage.png",
                  iconSize: [24,24],
                  iconAnchor: [12,24]
               });

               for (let i = 0; i< data.length; i++) {
                  let location = new L.LatLng(data[i].siteLatitude, data[i].siteLongitude);
                  let marker = new L.Marker(location, {
                     icon: myIcon,
                     title: 'thetitle' });

                     // let studyTitle = "Paper Title"
                     // let urlLink = "URL";
                     let studyTitle = "Paper Title"
                     let urlLink = "The URL Link";

                     let content = "<h2>" + studyTitle + "</h2>" + "<p>" + '<a href='+urlLink+'>' + urlLink+ '</a>' + "</p>" + "<p> <b>" + "</b></p>";

                     marker.bindPopup(content, {
                        maxWidth: '400'
                     });
                     map.addLayer(marker);
                     oms.addMarker(marker);

                     markerlist.push(marker);

                  }
               };
            });
         }
      };
      </script>
   </head>
   <h1>Heading</h1>
   <body onload=init()>
      <div id = "map"> </div>
   </body>
   </html>
...