100

100

import React from 'react'
import { MapContainer, TileLayer, GeoJSON } from 'react-leaflet'
import * as L from "leaflet";


const Map = (props) => {
let cordinates = [14.716, -14.467]       // Dispaly coordinates
return (
    // Cordinates of map 
    <MapContainer center={cordinates} zoom={7} scrollWheelZoom={false}>
         {/* Display map  */}
         <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
     {/* <GeoJSON id={Math.random()} data={country} /> */}

     {/* Highlited area in map  */}
        <GeoJSON data={props.state} onEachFeature={props.handleEachFeature} />
   </MapContainer> 
)
}

export default Map

我将JSON文件和handleEachFeature函数(在控制台中返回整个JSON文件)作为props 传递.

100

100

单击HandleEach功能:

 function handleEachFeature(feature, layer) {
         layer.on("click", L.bind(handleClick, null, layer));
}

 // This is returning whole json file in console. But, I want only Polygon id on which user clicked. 
 function handleClick(e) {
    console.log(e);
}

100

  1. 我使用了一个包含多个多边形的JSON文件.但是,onClick事件会得到整个JSON文件,而不是任何唯一的值来标识多边形.
  2. 我还try for each 多边形(状态)使用不同的JSON文件,并将它们逐个添加到 map 中,但得到了相同的结果.

100

推荐答案

可以通过将唯一标识符(在提供的示例中为cartodb_id)存储在一个变量中,然后使用它来更改geojson的样式,并使用特定样式呈现单击的区域来实现这一点.

使用onEachFeature函数,您可以导出唯一id并zoom 到单击的区域.一旦将其存储在变量中,就可以通过只显示包含唯一id的对象来过滤geojson.因为react传单的geojson comp数据属性是不可变的,所以必须使用引用(ref).您可以使用传单的eachLayer将特定样式附加到除单击对象之外的所有对象.在通过useeffect过滤geojson后,可以通过设置点击层样式来实现后者(参见下面的代码).然后使用传单的addData,你可以在 map 上阅读过滤后的geojson.

export default function Map() {
  const [map, setMap] = useState(null);
  const geojsonRef = useRef();
  const [featureId, setFeatureId] = useState(null);

  const handleEachFeature = (feature, layer) => {
    layer.on({
      click: (e) => {
        setFeatureId(feature.properties.cartodb_id);
        map.fitBounds(e.target.getBounds());
      }
    });
  };

  useEffect(() => {
    if (!featureId || !geojsonRef.current) return;
    geojsonRef.current.eachLayer((layer) => {
      layer.setStyle({
        opacity: 0.5,
        weight: 0
      });
    }); // inherited from LayerGroup
    const newDistricts = districts.features.filter((district) => {
      return district.properties.cartodb_id === featureId;
    });
    geojsonRef.current.addData(newDistricts);
  }, [featureId]);

  return (
    <MapContainer
      center={position}
      zoom={9}
      style={{ height: "100vh" }}
      ref={setMap}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      {map && (
        <GeoJSON
          ref={geojsonRef}
          data={districts}
          onEachFeature={handleEachFeature}
        />
      )}
    </MapContainer>
  );
}

您可以使用clearLayers方法完全删除它,但这对我来说没有意义,因为一旦单击它,您将只显示单击的区域.我try 了另一种方法,改变了除点击区之外的所有其他地区的风格.通过这种方式,您可以单击一个新的,并恢复上一个的样式.

一个简单的免费geojson用于呈现结果.

Demo

Json相关问答推荐

Allof Indide的JSON模式之一

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

Shell脚本空格转义

用powershell条件解析json文件的数组对象

如何在linux中用jq过滤json数组?

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

将哈希表转换为 json 后,Powershell 缺少数组

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

如何找出实际安装了哪个版本的 bower 包?

如何使用 json.net 将数据表转换为 json 字符串?

在 JSON 字符串中react i18n 换行符

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

Jackson 没有使用 @JsonProperty 覆盖 Getter

如何在已声明的 JSON 对象中添加键值对

如何将有向无环图 (DAG) 存储为 JSON?

如何访问 JSON 对象数组的第一个元素?

从 JSON 创建 Hashtable

将序列化表单的数据转换为 json 对象

处理 HTTP 请求正文中的可选 JSON 字段

Volley JsonObjectRequest Post 参数不再起作用