You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Leaflet渲染地图报错:Uncaught TypeError: Cannot convert undefined or null to object

解决React-Leaflet弹窗标记示例的"Cannot convert undefined or null to object"报错

报错根源

这个错误的核心原因是传入Leaflet的坐标值为undefined或null,Leaflet在解析地图中心(center)和标记位置(position)时,无法将空值转换为坐标对象,从而触发底层报错。

具体解决步骤

  • 初始化有效的坐标变量
    确保position变量被赋值为合法的经纬度数组,不要让它处于未定义、null状态:

    // 示例:使用官网提供的伦敦坐标
    const position = [51.505, -0.09];
    
  • 引入Leaflet必需的CSS文件
    React-Leaflet依赖Leaflet的基础样式,未引入会导致DOM渲染异常,间接触发此类错误。在组件或项目入口文件中添加:

    import 'leaflet/dist/leaflet.css';
    
  • 核对版本兼容性
    React-Leaflet和Leaflet的版本必须匹配,比如React-Leaflet v4.x需要搭配Leaflet v1.9.x。检查package.json中的依赖:

    "leaflet": "^1.9.4",
    "react-leaflet": "^4.2.1"
    

修正后的完整组件示例

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

function MyMap() {
  // 初始化有效坐标
  const position = [51.505, -0.09];

  return (
    {/* 注意给MapContainer设置宽高样式,否则地图可能不显示 */}
    <MapContainer center={position} zoom={13} scrollWheelZoom={false} style={{ height: '400px', width: '100%' }}>
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={position}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  );
}

export default MyMap;

内容的提问来源于stack exchange,提问作者yaswanth babu cholla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 02:20:46