javascript - 如何在传单中显示/隐藏带标记的折线

标签 javascript leaflet

使用传单 1.6.0,我列出了位置(标记和多段线) 按国家分组,我需要 单击国家按钮时按国家/地区过滤。 我使用 layerGroup 并设法使用如下方法显示标记和多段线:

    drawGroupedAdLocationsMarkers() {
        let polylinePoints = []  // I get all info about all Polylines
        let loop_index = 0

        this.groupedAdLocations.forEach(nextGroupedAdLocations => { // draw all groupedAdLocations
            this.groupedCountriesList[this.groupedCountriesList.length] = {
                key: nextGroupedAdLocations.country,
                label: this.countriesList[nextGroupedAdLocations.country],
            }
            let markersList = []
            let polylinesList = []
            nextGroupedAdLocations.adLocations.forEach(nextAddLocation => { // draw all nextAddLocation
                let priorPoint = null // eslint-disable-line
                let priorMarker = null // eslint-disable-line
                if (loop_index > 0) {
                    priorPoint = this.groupedAdLocations[loop_index - 1]
                    priorMarker= nextMarker
                }
                polylinePoints[polylinePoints.length] = [nextAddLocation.lat, nextAddLocation.lng]
                let nextMarker= this.showLocationMarker(nextAddLocation)
                markersList[markersList.length] = nextMarker
                polylinesList[polylinesList.length] = this.showLocationDirections(polylinePoints, nextGroupedAdLocations.country)
                loop_index++
            }) // nextGroupedAdLocations.adLocations.forEach(nextAddLocation => { // draw all nextAddLocation

            polylinesList.map((nextPolyline) => {
                markersList.push(nextPolyline);
            });

            let newMarkersLayerGroup = this.leaflet.layerGroup(markersList).addTo(this.locationsMap);
            this.layerGroupsMarkersArray[this.layerGroupsMarkersArray.length] = {
                country: nextGroupedAdLocations.country,
                layersObj: newMarkersLayerGroup
            }
        }) // this.groupedAdLocations.forEach(nextGroupedAdLocations => { // draw all groupedAdLocations


        let radius = 10;
        let polyline = new this.leaflet.Polyline(polylinePoints, {
            color: 'green',
            opacity: 1,
            weight: 2,
            customData: {
                type:'polyline'
                // point_id: point.id,
                // prior_point_id: priorPoint ? priorPoint.id : null,
            },
            offset: radius
        });
        polyline.on('click', function (event) {
            event.stopPropagation();
            window.event.cancelBubble = true;
            // showModal(event)
            // alert('Polyline clicked!');
        });
        // Add polyline to featuregroup
        polyline.addTo(this.locationsMap);
    }, // drawGroupedAdLocationsMarkers() {

和创建标记/多段线的方法:

    showLocationMarker(nextAddLocation) {
        let icon_size = 32
        if (nextAddLocation.featured) {
            icon_size = 48
        }
        var markerIcon = this.leaflet.icon({
            iconUrl: (!nextAddLocation.featured ? '/images/location.png' : '/images/location_featured.png'),
            iconSize: [icon_size, icon_size], // size of the icon
            // shadowSize:   [50, 64], // size of the shadow
            iconAnchor: [icon_size, icon_size], // point of the icon which will correspond to marker's location
            // shadowAnchor: [4, 62],  // the same for the shadow
            popupAnchor: [0, 0] // point from which the popup should open relative to the iconAnchor
        });

        let nextMarker = this.leaflet.marker(
            [nextAddLocation.lat, nextAddLocation.lng],
                {
                    icon: markerIcon,
                    customData:{add_location_id: nextAddLocation.id,type:'marker'}
                })
            .addTo(this.locationsMap)
            .bindPopup(nextAddLocation.content)
            .on('mouseover', this.locationMarkerOnMouseOver)
            .on('click', this.locationMarkerOnClick)
            .on('popupopen', this.locationMarkerOnPopupOpen)

        // circleMarker

        if (nextAddLocation.featured) {
            nextMarker.bindTooltip("Featured Location").openTooltip();
        }

        let self = this
        this.locationsMap.on('zoomend', function (/*e*/) {

            self.current_zoom = self.locationsMap.getZoom()
        });

        if (nextAddLocation.opened) {
            nextMarker.openPopup()
        }
        return nextMarker
    }, // showLocationMarker(nextAddLocation) {

    showLocationDirections(polylinePoints, country) {
        let radius = 10;
        let polyline = new this.leaflet.Polyline(polylinePoints, {
            color: 'green',
            opacity: 1,
            weight: 2,
            customData: {
                type:'polyline'
                // point_id: point.id,
                // prior_point_id: priorPoint ? priorPoint.id : null,
            },
            offset: radius
        });
        // Add click listener
        polyline.on('click', function (event) {
            event.stopPropagation();
            window.event.cancelBubble = true;
        });
        // Add polyline to featuregroup
        polyline.addTo(this.locationsMap);
        let decorator = this.leaflet.polylineDecorator(polyline, { // eslint-disable-line
            patterns: [
                // defines a pattern of 10px-wide dashes, repeated every 20px on the line
                {
                    offset: 0,
                    repeat: 50,
                    symbol: this.leaflet.Symbol.arrowHead({
                        pixelSize: 10,
                        polygon: false,
                        pathOptions: {stroke: true}
                    })
                }
            ]
        }).addTo(this.locationsMap)

        this.locationsMap.fitBounds(polyline.getBounds());
        return polyline;
    },  // showLocationDirections(polylinePoints) {

结果我看到带有标记/折线的 map :https://prnt.sc/t1751f

点击过滤器的方法标记被隐藏/显示,但多段线是 总是可见的方法:

filterByGroupedCountry(country_key, country_label) {
    let self = this
    this.layerGroupsMarkersArray.forEach(nextLayerMarkerGroup => { // draw all layerGroupsMarkersArray
        if (nextLayerMarkerGroup.country === country_key) {
            let layersObj = nextLayerMarkerGroup.layersObj

            if (self.locationsMap.hasLayer(layersObj)) {
                self.locationsMap.removeLayer(layersObj);
            } else {
                self.locationsMap.addLayer(layersObj);
            }
            return
        }
    }) // this.layerGroupsMarkersArray.forEach(nextLayerMarkerGroup => { // draw all layerGroupsMarkersArray

如我上面所写,将所有多段线推送到标记数组的方式不正确吗:

...
polylinesList.map((nextPolyline) => {
    markersList.push(nextPolyline);
});

let newMarkersLayerGroup = this.leaflet.layerGroup(markersList).addTo(this.locationsMap);
...

哪种方式是正确的?

第 2 block :

我重新制作了,如果我只有一组数据,它就可以正常工作。 但如果我有更多 1 个组,它会以错误的方式工作。 假设我有 2 个国家/地区组,在打开的页面上有任何国家/地区的一组位置(在运行 drawGroupedAdLocationsMarkers 之后),我看到带有多段线的标记显示正常。 当我单击隐藏第一个国家组(方法 filterByGroupedCountry)时,仅隐藏标记, 但折线和装饰器仍然可见。 当我单击以隐藏第二个(最后一个)国家组时,所有标记折线和装饰器都被隐藏。 我想这是用一个数组创建 LayerGroup 的错误方法

       let newMarkersLayerGroup = this.leaflet.layerGroup(markersList); 

如果我将所有多段线和装饰器添加到 markersList,但哪种方式有效?

        drawGroupedAdLocationsMarkers() {
            let polylinePoints = []  // I get all info about all Polylines
            let loop_index = 0

            this.groupedCountriesList= []
            this.groupedAdLocations.forEach(nextGroupedAdLocations => { // draw all groupedAdLocations
                this.groupedCountriesList[this.groupedCountriesList.length] = {   // keep list of countries for filtering countries list
                    key: nextGroupedAdLocations.country,
                    label: this.countriesList[nextGroupedAdLocations.country],
                }
                let markersList = []
                let polylinesList = []
                let decoratorsList = []  // init markers, polylines, decorators Lists withing one country group
                nextGroupedAdLocations.adLocations.forEach(nextAdLocation => { // draw all adLocations inside of one country group
                    let priorPoint = null // eslint-disable-line
                    let priorMarker = null // eslint-disable-line
                    if (loop_index > 0) {
                        priorPoint = this.groupedAdLocations[loop_index - 1]
                        priorMarker= nextMarker
                    }
                    polylinePoints[polylinePoints.length] = [nextAdLocation.lat, nextAdLocation.lng]

                    // add new marker and add it to markersList
                    let nextMarker= this.showLocationMarker(nextAdLocation, nextGroupedAdLocations.country)
                    markersList[markersList.length] = nextMarker

                    let radius = 10; // Add new polyline based on point of nextAdLocation
                    let polyline = new this.leaflet.Polyline(polylinePoints, {
                        color: 'green',
                        opacity: 1,
                        weight: 2,
                        customData: {
                            add_location_id: nextAdLocation.id,
                            type:'polyline',
                            country:nextGroupedAdLocations.country
                        },
                        offset: radius
                    });
                    polyline.on('click', function (event) {
                        event.stopPropagation();
                        window.event.cancelBubble = true;
                    });
                    // polyline.addTo(this.locationsMap);

                    // add new decorator for polyline created above
                    let decorator = this.leaflet.polylineDecorator(polyline, { // eslint-disable-line
                        patterns: [
                            // defines a pattern of 10px-wide dashes, repeated every 20px on the line
                            {
                                offset: 0,
                                repeat: 50,
                                symbol: this.leaflet.Symbol.arrowHead({
                                    pixelSize: 10,
                                    polygon: false,
                                    pathOptions: {stroke: true},
                                    customData: {
                                        add_location_id: nextAdLocation.id,
                                        type:'polyline',
                                        country:nextGroupedAdLocations.country
                                    },
                                })
                            }
                        ]
                    })
                    // decorator.addTo(this.locationsMap)

                    this.locationsMap.fitBounds(polyline.getBounds());
                    // add created polyline to polylinesList
                    polylinesList[polylinesList.length] = polyline

                    // add created decorator to decoratorsList
                    decoratorsList[decoratorsList.length] = decorator
                    loop_index++
                }) // nextGroupedAdLocations.adLocations.forEach(nextAdLocation => { // draw all adLocations inside of one country group

                polylinesList.map((nextPolyline) => {
                    markersList.push(nextPolyline);
                });
                decoratorsList.map((nextDecorator) => {
                    markersList.push(nextDecorator);
                });

                // create layer Group with polylinesList, markersList and decoratorsList
                let newMarkersLayerGroup = this.leaflet.layerGroup(markersList); 
                this.locationsMap.addLayer(newMarkersLayerGroup);
                this.layerGroupsMarkersArray[this.layerGroupsMarkersArray.length] = {
                    country: nextGroupedAdLocations.country,
                    layersObj: newMarkersLayerGroup
                }

            }) // this.groupedAdLocations.forEach(nextGroupedAdLocations => { // draw all groupedAdLocations

        }, // drawGroupedAdLocationsMarkers() {

        showLocationMarker(nextAdLocation, country) {
            let icon_size = 32
            if (nextAdLocation.featured) {
                icon_size = 48
            }
            var markerIcon = this.leaflet.icon({
                iconUrl: (!nextAdLocation.featured ? '/images/location.png' : '/images/location_featured.png'),
                iconSize: [icon_size, icon_size], // size of the icon
                // shadowSize:   [50, 64], // size of the shadow
                iconAnchor: [icon_size, icon_size], // point of the icon which will correspond to marker's location
                // shadowAnchor: [4, 62],  // the same for the shadow
                popupAnchor: [0, 0] // point from which the popup should open relative to the iconAnchor
            });

            let nextMarker = this.leaflet.marker(
                [nextAdLocation.lat, nextAdLocation.lng],
                    {
                        icon: markerIcon,
                        customData:{
                            add_location_id: nextAdLocation.id,
                            type:'marker',
                            country:country
                        }
                    })
                .addTo(this.locationsMap)
                .bindPopup(nextAdLocation.content)
                .on('mouseover', this.locationMarkerOnMouseOver)
                .on('click', this.locationMarkerOnClick)
                .on('popupopen', this.locationMarkerOnPopupOpen)

            if (nextAdLocation.featured) {
                nextMarker.bindTooltip("Featured Location").openTooltip();
            }

            let self = this
            this.locationsMap.on('zoomend', function (/*e*/) {
                self.current_zoom = self.locationsMap.getZoom()
            });

            if (nextAdLocation.opened) {
                nextMarker.openPopup()
            }
            return nextMarker
        }, // showLocationMarker(nextAdLocation) {


        filterByGroupedCountry(country_key, country_label) {
            let self = this
            this.layerGroupsMarkersArray.forEach(nextLayerMarkerGroup => { // draw all layerGroupsMarkersArray
                if (nextLayerMarkerGroup.country === country_key) {
                    console.log('FOUND country_key::')
                    console.log(country_key)
                    let layersObj = nextLayerMarkerGroup.layersObj
                    console.log(0)
                    if (self.locationsMap.hasLayer(layersObj)) {
                        console.log(-1)
                        self.locationsMap.removeLayer(layersObj);
                    } else {
                        console.log(-2)
                        self.locationsMap.addLayer(layersObj);
                    }
                    return
                }
            }) // this.layerGroupsMarkersArray.forEach(nextLayerMarkerGroup => { // draw all layerGroupsMarkersArray

        }

第 3 block : 我做了在线演示 请打开http://ads.my-demo-apps.tk/login 凭据已经在输入中。只需点击“登录” 之后重定向到 http://ads.my-demo-apps.tk/test2 您必须看到带有一些点/折线的 map 以及下面 4 个国家/地区的列表 尝试一个一个地点击国家。 您会看到相关标记被隐藏(或再次显示,如果单击 再次链接国家/地区):https://prnt.sc/t8dsxb 但是折线并没有像我预期的那样被隐藏

点击所有国家 - 然后所有国家都被隐藏。 我在 BLOCK # 2 中给出了代码描述:

谢谢!

最佳答案

您的代码中存在逻辑错误,实际上很容易修复。
看着你的jsfiddle示例可以看到多次添加相同的多段线,实际上是每次创建另一个国家/地区的标记。
需要做的是为每个外部循环执行用一个空数组重新初始化 polylinePoints 变量。您可以在 this jsfiddle 中查看.

this.groupedAdLocations.forEach(nextGroupedAdLocations => { 
    let markersList = []
    let polylinesList = []
    polylinePoints = [] // THIS was missing
    nextGroupedAdLocations.adLocations.forEach(nextAdLocation => {
        ...

如果您希望来自不同国家的城市也连接起来,那么您需要调整此解决方案并确保您不会多次添加相同的折线。

BUT 还有一个非常重要的但是。正如@IvanSanchez 在他的评论中已经提到的那样,这段代码非常、非常、非常复杂。它很难读,错误百出,而且很容易出错。
如果你不是一个人工作,并且有一个更有经验的软件工程师,那么请向他寻求帮助。他们可以而且应该帮助您重构此代码。

我举几个例子:

  • Array.forEach 与自定义 loop_index++ 逻辑结合使用。而不是简单地使用 forEach 回调函数的第二个参数。
  • polylinesList.map((nextPolyline) => { markersList.push(nextPolyline);});
    调用 map,没有映射发生,forEach 或简单循环更多适当的。
  • polylinesList[polylinesList.length] = polyline. 也许在 JS 中这只是一个品味问题,但我会在这里简单地使用 push 函数。
  • 数据结构的设计非常低效且令人困惑。在多个地方拥有相同的数据,使得这种冗余容易出错。拥有单一的真实来源会好得多。
  • 最后但并非最不重要的一点 - 这段代码真的很复杂。

保重并继续学习:)

关于javascript - 如何在传单中显示/隐藏带标记的折线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62422882/

相关文章:

javascript - 使用从 PHP 生成的 HTML 调用的函数 AJAX 更新 MYSQL 数据库

javascript - 试图检查一个复选框是否被选中,请问我做错了什么?

javascript - 填充输入字段时重新启用禁用的命令按钮

javascript - 如何通过onmouseup发送属性?

javascript - 使用 Angular 在 View 中打印全局变量

javascript - LeafletJS : Load Tile Layer based on bounding box

javascript - 单击 map 外部时传单缩放 map

javascript - leaflet js中Z代表什么

leaflet - 调整传单 map 的大小时,如何保持 map 居中?

javascript - 如何从传单上的本地存储和图层组中删除特定项目?