【问题标题】:React Leaflet - Update map centerReact Leaflet - 更新地图中心
【发布时间】:2021-04-22 03:00:56
【问题描述】:

我正在使用 React Leaflet。我有一个地图和一个包含名称和相应位置的数组。数组中的每个名称都是一个按钮。当我单击一个名称时,位置会发生变化,并且应该在地图中更新。这适用于标记,但不适用于地图的部分。如何更新地图的部分?

const data = [
      {
        name: 'John',
        coordinates: {
          langitude: '40.72260370101827',
          latitude: '-73.99323791583221',
        },
      },
      {
        name: 'Bob',
        coordinates: {
          langitude: '40.72843542344666',
          latitude: '-73.94860440141105',
        },
      },
      {
        name: 'Chris',
        coordinates: {
          langitude: '40.79159996340942',
          latitude: '-73.94077957876242',
        },
      },
    ];

export default function Map(props) {
  const { index, data } = props;

  return (
    <MapContainer
      center={[
        data[index].coordinates.langitude,
        data[index].coordinates.latitude,
      ]}
      zoom={16}
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      ></TileLayer>
      <Marker
        position={[
          data[index].coordinates.langitude,
          data[index].coordinates.latitude,
        ]}
      >
        <Popup>{data[index].name}</Popup>
      </Marker>
    </MapContainer>
  );
}

【问题讨论】:

    标签: reactjs dictionary leaflet react-leaflet


    【解决方案1】:

    以下是此问题的完整描述:another thread。基本上,MapContainercenter 道具(以及所有其他道具,除了儿童)是不可变的,因此您需要使用上面答案中解释的提供的方法。
    但是,这是我想到的一个快速修复:

     <MapContainer
         key={JSON.stringify([data[index].coordinates.langitude, data[index].coordinates.latitude])}
         center={[
            data[index].coordinates.langitude,
            data[index].coordinates.latitude,
         ]}
         zoom={16}
    >
    

    您的代码中唯一添加的是 key 属性,它采用字符串化的中心位置。因此,当位置发生变化时,会创建 MapContainer 组件的另一个实例(新副本;)),具有正确的 center 值。

    【讨论】:

    • 这不是更新地图视图的正确方法。这更像是一种 hack,而不是一个适当的解决方案。
    • @kboul 你是对的。这就是我写“快速修复”的原因。正确的做法是在我在回答的第一句话中慷慨地放入链接中。
    • 这里有更多关于“hack”的信息,如果有人好奇的话:reactjs.org/blog/2018/06/07/… ... 虽然这是一个非常具体的用例(天哪,从他们在 React 中使用 classes 的那一天起),我个人更喜欢了解一个工具,无论它多么“hacky”,而不是看着它并希望它永远不存在,因为它太丑陋了。干杯;)
    【解决方案2】:

    来自官方docs

    除了它的孩子之外,MapContainer 道具是不可变的:不断变化 它们在第一次设置后将不会影响 地图实例或其容器。

    因此,您必须创建一个自定义组件,以便在坐标更改时更改地图视图

    function SetViewOnClick({ coords }) {
      const map = useMap();
      map.setView(coords, map.getZoom());
    
      return null;
    }
    

    通过将坐标作为道具传递,将其用作标记组合下方的 MapContainer 的子级。

    <SetViewOnClick
            coords={[
              data[index].coordinates.langitude,
              data[index].coordinates.latitude
            ]}
    />
    

    一旦收到更新的索引,地图的视图就会改变。

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2022-07-06
      • 2023-02-13
      • 2013-07-19
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多