如何在React Leaflet的MapContainer中渲染GeoJSON格式多边形?
React + Leaflet 加载GeoJSON无效问题修复
问题根因
- 你直接将
axios.get()返回的Promise实例传入了L.geoJSON()方法,该方法仅支持接收标准GeoJSON格式的对象/数组作为入参,不能识别Promise类型,这是报错的直接原因 - 异步请求逻辑写在组件顶层,会随组件重复渲染反复发起请求
useEffect未设置空依赖数组,会导致地图实例重复初始化,引发内存泄漏- 原代码中地图容器仅设置了宽度100%,未设置高度,会导致地图无法正常渲染
修复后代码
import React, { useEffect, useRef, useState } from 'react'; import * as L from 'leaflet'; import 'leaflet/dist/leaflet.css'; import * as EL from "esri-leaflet"; import axios from 'axios'; export default function Mapfun() { const mapRef = useRef(null); const geojsonLayerRef = useRef(null); useEffect(() => { // 避免重复初始化地图 if (mapRef.current) return; // 初始化地图 const map = L.map('mapdiv', { center: [31, 72], zoom: 6, layers: [ L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", { attribution: '© OpenStreetMap contributors' }), EL.featureLayer({ url: 'http://localhost:6080/arcgis/rest/services/Pu/PB_/MapServer/11' }) ] }); mapRef.current = map; // 发起请求加载GeoJSON axios.get('https://gist.githubusercontent.com/UmairMughal901/d43ee77a9be27f2dcd006038fe8f07e7/raw/8650f4f3585ff0c1706da7a434251cfc70f1907b/map.geojson') .then(resp => { // 拿到数据后再添加GeoJSON图层 if (geojsonLayerRef.current) { map.removeLayer(geojsonLayerRef.current); } geojsonLayerRef.current = L.geoJSON(resp.data).addTo(map); }); // 组件卸载时销毁地图,避免内存泄漏 return () => { if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; } }; }, []); return ( // 必须给地图容器设置高度,否则地图无法渲染 <div id='mapdiv' style={{ width: '100%', height: '100vh' }}> </div> ); }
内容的提问来源于stack exchange,提问作者Umair Asghar
相关产品推荐
相关产品推荐

