Добавление markerclustergroup к наложению листовок не обновляется в приложении Vue. js - PullRequest
0 голосов
/ 16 января 2020

У меня есть элемент управления наложением на моей листовке в приложении vue. js. Он содержит два слоя. Слой ILZipCodes визуализируется отлично. Однако слой «маркеры» не отображается, когда я устанавливаю флажок в элементе управления слоем. Почему это? Я считаю, что я, возможно, настраиваю управление слоями и размещаю кластеры в неправильной последовательности.

Cheers

<template>
  <div>
    <div class="mx-auto my-6 loader" v-if="isSearching"></div>
    <div class="tooManyResultsError" v-if="tooManyResults">
      Your search brought back too many results to display. Please zoom in or refine your search with the text box and
      filters.
    </div>
    <div id="leafletMapId"></div>
  </div>
</template>

<script>

//The center coordinate and zoom level that the map should initialize to
// to capture all of the continental United States
const INITIAL_CENTER_LATITUDE = 34;
const INITIAL_CENTER_LONGITUDE = -96;
const INITIAL_ZOOM = 4;

/* Leaflet performs slowly with reactivity ("observable" data object variables).
 * To work around this, I removed myMap and markers from the data object.
 */

/* If the user zooms out or pans beyond the boundaries of the previous fetch's dataset, then
 * the client fetches location data from the server to replace the previous map data. If the user
 * zooms or pans but stays within the boundaries of the dataset currently displayed on the map, then
 * the client does not run another fetch.
 * */

import axios from "axios";
import store from "../store.js";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/leaflet.markercluster-src.js";
import "leaflet-ajax/dist/leaflet.ajax.js";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";



export default {
  name: "ContactsMap",

  mounted() {
    this.fetchAggregatedDistrictStats();
  },
  methods: {
    async fetchAggregatedDistrictStats() {
      axios.get(... // fetches some statistics for the other overlay layers
      );
    },
    createMapWithLeafletAndMapTiler() {
      var $this = this;
      var streetTilesLayer = L.tileLayer(MAPTILER_STREETS_URL, {
        maxZoom: 18,
        minZoom: 2,
        attribution: MAPBOX_ATTRIBUTION,
        tileSize: 512,
        zoomOffset: -1
      });

      // eslint-disable-next-line
      var satelliteTilesLayer = L.tileLayer(MAPTILER_SATELLITE_URL, {
        maxZoom: 18,
        minZoom: 2,
        tileSize: 512,
        zoomOffset: -1
      });

      var baseMaps = {
        Satellite: satelliteTilesLayer,
        Streets: streetTilesLayer
      };

      if (myMap != undefined) {
        myMap.remove();
      }
      var myMap = L.map("leafletMapId", {
        layers: [streetTilesLayer],
      }).setView(this.center, this.zoom);

      var markers = L.markerClusterGroup({
        iconCreateFunction: function(cluster) {
          var count = cluster.getChildCount();
          var digits = (count + "").length;
          return L.divIcon({
            html: "<b>" + count + "</b>" + digits,
            className: "cluster digits-" + digits,
            iconSize: 22 + 10 * digits
          });
        }
      });

      async function fetchLocations(shouldProgrammaticallyFitBounds) {
        markers.clearLayers();
        markers = L.markerClusterGroup({
          chunkedLoading: true,
          iconCreateFunction: function(cluster) {
            var count = cluster.getChildCount();
            var digits = (count + "").length;
            return L.divIcon({
              html: "<b>" + count + "</b>",
              className: "cluster digits-" + digits,
              iconSize: 22 + 10 * digits
            });
          }
        });

        axios
          .get("/maps/" + $this.list.list_id, {
              //fetches markerclusters 
          })
          .then(
            response => {
                $this.tooManyResults = false;
                var addressPoints = response.data.recordsList;
                for (var i = 0; i < addressPoints.length; i++) {
                  var a = addressPoints[i];
                  var title = a[2];
                  var marker = L.marker(L.latLng(a[0], a[1]));
                  marker.bindPopup(title);
                  markers.addLayer(marker); // This is where I'm adding the markers and markerclusters to the layer titled "markers"

                // myMap.addLayer(markers); //If I uncomment this, then the markers layer is always on the map, i.e. not as an overlay layer

              }
            },
            error => {
              $this.isSearching = false;
              document.getElementById("leafletMapId").style.display = "block";

              store.setErrorMessage("Network error searching list", error);
            }
          );
      }

      myMap.on("zoomend", handlerFunction);
      myMap.on("dragend", handlerFunction);

      var defaultPolygonStyle = {
        color: "black",
        weight: 1,
        opacity: 0.8,
        fillOpacity: 0.1
      };

      var NationalCongressional = new L.geoJson.ajax(
        "http://localhost:8080/assets/geo/NationalCongressional.json",
        {
          style: defaultPolygonStyle,
          onEachFeature: function(feature, layer) {
            layer.bindPopup(feature.properties.NAMELSAD);
            if (feature.properties.NAMELSAD == "Congressional District 8") {
              layer.setStyle({ color: "orange" });
            }
          }
        }
      );

      function getColorFromRedBlueRange(d) {
        return d > 0.8
          ? "#FF0000"
          : d > 0.7
          ? "#FF006F"
          : d > 0.55
          ? "#FF00EF"
          : d > 0.45
          ? "#DE00FF"
          : d > 0.3
          ? "#BC00FF"
          : d > 0.2
          ? "#6600FF"
          : "#00009FF";
      }
      var ILZipCodes = new L.geoJson.ajax(
        "https://raw.githubusercontent.com/OpenDataDE/State-zip-code-GeoJSON/master/il_illinois_zip_codes_geo.min.json",
        {
          // style: defaultPolygonStyle,
          onEachFeature: function(feature, layer) {
            layer.bindPopup(
              feature.properties.ZCTA5CE10 +
                ", " +
                $this.zipData[feature.properties.ZCTA5CE10]
            );
            layer.setStyle({
              color: getColorFromRedBlueRange(
                $this.zipData[feature.properties.ZCTA5CE10]
              ),
              weight: 0,
              fillOpacity: 0.3
            });
          }
        }
      );

      var overlays = {
        Voters: voterGroup,
        ILZipCodes: ILZipCodes,
      };

      L.control.layers(baseMaps, overlays).addTo(myMap);
      fetchLocations(true);
    }
  }
};

1 Ответ

0 голосов
/ 17 января 2020

Вы добавляете voterGroup в свой Layers Control вместо вашего markers.

Тогда просто не переназначайте MarkerClusterGroup в вашу переменную markers (после использования clearLayers), и вы должны будь в порядке.

...