React+Leaflet制作西班牙Choropleth地图:GeoJSON区域不显示求助
问题排查与解决方案
1. 未正确初始化GeoJSON数据
你的geoJSONData状态初始为null,但没有将导入的spainGeoJSON赋值给它,同时传入GeoJSON组件的参数有误:
- 直接初始化
geoJSONData状态,将导入的GeoJSON数据赋值给它 GeoJSON组件的data属性需要传入完整的FeatureCollection对象,而非features数组
修改示例:
// 初始化state时直接赋值 const [geoJSONData, setGeoJSONData] = useState(spainGeoJSON); // 对应GeoJSON组件修改 <GeoJSON data={geoJSONData} />
2. 错误使用whenCreated属性
MapContainer的whenCreated回调参数是Leaflet的map实例,你将其赋值给center状态会导致坐标被覆盖为map对象,破坏地图初始化逻辑,直接删除该属性即可:
<MapContainer center={center} zoom={ZOOM_LEVEL} ref={mapRef}>
3. 添加自定义样式确保可见性
GeoJSON默认样式可能与底图颜色接近导致无法识别,添加自定义样式强制区分:
const geoStyle = { fillColor: '#ff7800', weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 }; // 在GeoJSON组件中应用样式 <GeoJSON data={geoJSONData} style={geoStyle} />
修改后的完整代码
import React, { useRef, useState } from 'react'; import { MapContainer, TileLayer, GeoJSON, FeatureGroup } from 'react-leaflet'; import OSMProvider from './OSM-provider'; import 'leaflet/dist/leaflet.css'; import spainGeoJSON from '../sources/spainregions.geojson'; import L from 'leaflet'; const SpainMap = () => { const [geoJSONData, setGeoJSONData] = useState(spainGeoJSON); const mapRef = useRef(); const ZOOM_LEVEL = 6; const [center, setCenter] = useState({ lat: 40.4165000, lng: -3.7025600 }); const geoStyle = { fillColor: '#ff7800', weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 }; return ( <div className="row"> <div className="col text-center"> <div className="col"> <MapContainer center={center} zoom={ZOOM_LEVEL} ref={mapRef}> <TileLayer url={OSMProvider.maptiler.url} attribution={OSMProvider.maptiler.attribution} /> <FeatureGroup> {geoJSONData && ( <GeoJSON data={geoJSONData} style={geoStyle} /> )} </FeatureGroup> </MapContainer> </div> </div> </div> ); }; export default SpainMap;
内容的提问来源于stack exchange,提问作者Kronk
相关产品推荐
相关产品推荐

