【问题标题】:Type error while rendering leaflet.js map渲染leaflet.js 地图时出现类型错误
【发布时间】:2021-11-19 22:28:18
【问题描述】:

我一直在尝试将 Leaflet.js 库与 react.js 一起使用并遵循以下代码:

import {L} from 'leaflet'

const myApp = () => {

const map = L.map("map").setView([45, 1], 4);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

L.control.scale().addTo(map);
L.marker([45, 1], {icon: new L.Icon({iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon.png'})}).addTo(map);

return (
    <div id="map" style="height:100vh"></div>
)}

我收到以下类型错误: TypeError: Cannot read properties of undefined (reading 'map') in line:

const map = L.map("map").setView([45, 1], 4);

有什么办法解决吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这里有多个问题需要解决。

    库导入不正确 - 应该是

    import L from "leaflet";

    在执行代码L.map之前需要渲染带有id map的div——更多信息请参考Leaflet: Map container not found

    应用这 2 个修复程序后,它应该可以工作 - 工作示例 https://codesandbox.io/s/agitated-galileo-w6now?file=/src/App.js:42-67

    【讨论】:

    • 完美!谢谢
    • 如果您认为这是一个好的/正确的答案,请不要忘记标记为正确答案并点赞
    猜你喜欢
    • 2019-10-18
    • 2011-12-10
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多