【问题标题】:React Leaflet LayersControl.Overlay with multiple markers使用多个标记反应 Leaflet LayersControl.Overlay
【发布时间】:2021-02-18 16:53:45
【问题描述】:

我有一张地图,其中显示了城市中每个不同公共设施的标记,我想要一组复选框来根据其类型过滤这些设施,一个类型复选框。每个类型都有多个标记,地图只会显示选中的标记。
我正在使用 react-leaflet v3。

这是我尝试做的:

<MapContainer center={[50,50]} zoom={13} scrollWheelZoom={true} whenCreated={setMap}>
            <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />     
            <LayersControl position='topright'>
                {typologies.map((typology, index) => (                    
                    <LayersControl.Overlay key={index} checked name={typology}>
                        {publicFacilities.filter((publicFacility) => publicFacility.typology == typology ).map((publicFacility) => (                            
                            <Marker key={publicFacility._id} position={publicFacility.coordinates} />
                        ))}  
                    </LayersControl.Overlay>
                ))}
            </LayersControl>                    
        </MapContainer> 

typologies 是字符串列表,publicFacilities 是对象列表。

但使用这种方法,我会为每个设施设置一个复选框。

【问题讨论】:

  • 您的数据是什么样的? typologiespublicFacilities.
  • typologies 是一个字符串列表,例如["office", "sports" ... ]publicFacilities 对象列表,例如[ { _id: "123", name:"town hall", typology:"office", coordinates:[50,50] }, ... ]
  • 我是working
  • 如果你在publicFacilities 中添加了另一个typeology = "office" 的对象,那么它将出现两个名为office 的复选框,而我只想要一个用于所有办公室的复选框。
  • 这是该问题的新信息。你应该在你的帖子中澄清这一点。但它会有相同的标记还是新的标记?如果它与第一个相比有不同的标记,你想用不同的复选框显示它们吗?这是您必须在问题描述中澄清的信息。

标签: javascript reactjs leaflet react-leaflet react-leaflet-v3


【解决方案1】:

您可以使用 lodash groupBy 按类型构建您的组。

然后使用图层组让多个标记充当叠加层。

以下内容:

const groupedByTypology = groupBy(publicFacilities, "typology");

return <LayersControl>
  {Object.keys(groupedByTypology).map(typology => (
    <LayersControl.Overlay key={typology} name={typology}>
      <LayerGroup>
        {groupedByTypology[typology].map(publicFacility => (
          <Marker key={publicFacility._id} position={publicFacility.coordinates} />
        ))}
      </LayerGroup>
    </LayersControl.Overlay>
  ))}
</LayersControl>

【讨论】:

  • 为什么要使用 lodash?单独的 LayerGroup 将完成最初的问题。 .filter() 的性能差异是否如此显着以至于有理由为此导入一个新的实用程序?
  • 嗨@Sam,“.filter() 的性能差异如此显着吗”在常见情况下没有;它使您遍历整个数组的次数与不同值的数量一样多;而 groupBy 只需 1 次就可以完成。但是对于少数值和小数组,我们不在乎。 “为什么使用 lodash”确实很容易编写具有相同性能的 groupBy 等效项。现在我们应该重新发明轮子还是依赖库,这是另一个争论。
猜你喜欢
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多