传单.js:单击面以移除图层并将其更改为新图层



我一直在制作传单地图一段时间,并试图找出制作方法,因此如果我单击 GeoJSON 图层中的一个多边形,它将删除当前图层并将其替换为另一个图层。

同样,如果我再次单击它,它将删除新图层并将其替换为以前的图层。

我一直在尝试修补不同的东西,但没有任何效果。这是我最近的一次尝试。

<script type="text/javascript" src="provinces.js"></script>
<script>
    var map = L.map('map').setView([-2.5, 119], 5);
    L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
        subdomains: 'abcd',
        maxZoom: 19
    }).addTo(map);

    // get color depending on population density value
    function getColor(d) {
        return d > 5000 ? '#800026' :
                d > 2500  ? '#BD0026' :
                d > 1000  ? '#E31A1C' :
                d > 500  ? '#FC4E2A' :
                            '#FFEDA0';
    }
    function style(feature) {
        return {
            weight: 2,
            opacity: 1,
            color: 'white',
            dashArray: '',
            fillOpacity: 0.7,
            fillColor: getColor(feature.properties.kode)
        };
    }
    function highlightFeature(e) {
        var layer = e.target;
        layer.setStyle({
            weight: 5,
            color: '#ccc',
            dashArray: '',
            fillOpacity: 0.7
        });
        if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
            layer.bringToFront();
        }
        info.update(layer.feature.properties);
    }
    var geojson;
    function resetHighlight(e) {
        geojson.resetStyle(e.target);
        info.update();
    }
    function zoomToFeature(e) {
        map.fitBounds(e.target.getBounds());
    }

    function addNewBoundary(e) { // this function doesn't do anything
            var newLayerBoundary = new L.geoJson();
            newLayerBoundary.addTo(map);
            $.ajax({
            dataType: "json",
            url: "province-details.geojson",
            success: function(data) {
                $(data.features).each(function(key, data) {
                    newLayerBoundary.addData(data);
                });
            }
            }).error(function() {});
    }
    function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: clearLayers // with this it just clears the layers before being clicked
    });
}
    geojson = L.geoJson(provinces, {
        style: style,
        onEachFeature: onEachFeature
    }).addTo(map);
</script>
    var layers = [firstLayer,secondLayer]
    function switchLayers(){    
      if(map.haslayer(layers[firstLayer])){
          map.addLayer(layers[secondLayer]);
          map.removeLayer(layers[firstLayer]);
      }else{
        if(map.haslayer(layers[secondLayer])){
          map.addLayer(layers[firstLayer]);
          map.removeLayer(layers[secondLayer]);
      }    
 }

最新更新