[英]Error when trying to map a choropleth using react-leaflet-choropleth: Cannot read property 'map' of undefined
我正在嘗試使用react
react-leaflet-choropleth
。
我的 leaflet 工作正常。
現在,當我嘗試使用庫加載geojson (crimes_by_district)時,在映射功能時遇到錯誤,特別是:
Cannot read property 'map' of undefined
看來我沒有准確地將正確的數組引用到 map。
我查看了 git 存儲庫中的問題並嘗試了這些建議,但沒有成功。 我想知道我是否從我正在使用的geoJson
中引用了不正確的值。
下面是我的代碼:
Leaf.js (在 App.js 中渲染)
import React, { Component } from 'react';
import { Map, TileLayer } from 'react-leaflet';
import classes from './leaf.module.css'
import Choropleth from 'react-leaflet-choropleth'
import geojson from "./assets/crimes_by_district.geojson";
const style = {
fillColor: '#F28F3B',
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.5
};
class Leaf extends Component {
render() {
return (
<Map>
<Choropleth
data= {{type: 'FeatureCollection', features: geojson.features}}
valueProperty={(feature) => feature.properties.value}
// visible={(feature) => feature.id !== active.id}
scale={['#b3cde0', '#011f4b']}
steps={7}
mode='e'
style={style}
onEachFeature={
(feature, layer) => layer.bindPopup(feature.properties.label)
}
ref={(el) => this.choropleth = el.leafletElement}
/>
</Map>
);
}
}
export default Leaf;
使用與您包含的擴展類似的相同 choropleth 庫創建您自己的choropleth wrapper
,因為react-leaflet-choropleth
似乎已過時:
function Choropleth() {
const { map } = useLeaflet();
useEffect(() => {
fetch(
"https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
)
.then((response) => response.json())
.then((geojson) => {
L.choropleth(geojson, {
valueProperty: "incidents", // which property in the features to use
scale: ["white", "red"], // chroma.js scale - include as many as you like
steps: 5, // number of breaks or steps in range
mode: "q", // q for quantile, e for equidistant, k for k-means
style,
onEachFeature: function (feature, layer) {
layer.bindPopup(
"District " +
feature.properties.dist_num +
"<br>" +
feature.properties.incidents.toLocaleString() +
" incidents"
);
}
}).addTo(map);
});
}, []);
return null;
}
然后將其作為 Map 子項導入:
<Map center={position} zoom={11} style={{ height: "100vh" }}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Choropleth />
</Map>
您可以通過傳遞所需的各種變量作為道具來進一步擴展它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.