无法在 svelte 中读取未定义的 属性 'addLayer'

Cannot read property 'addLayer' of undefined in svelte

下面是我的代码。我正在使用 leaflet in svelte 绘制带有图像的地图。

<script>
  import { onMount } from "svelte";
  import L from "leaflet";
  var map;
  onMount(() => {
    map = L.map("issmap").setView([51.505, -0.09], 13);
  });
  var imageUrl = "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg",
    imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  L.imageOverlay(imageUrl, imageBounds).addTo(map);
</script>

<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
      integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
      crossorigin=""
    />
    <script
      src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
      integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
      crossorigin=""
    ></script>
    <style>
      #issmap {
        height: 180px;
      }
    </style>
  </head>
  <body>
    <div id="issmap"></div>
  </body>
</html>

但我收到错误消息“无法读取未定义的 属性 'addLayer'”。我该如何解决这个问题?

你的问题是你试图在 onMount 回调之外使用 map 所以它是 undefined 在行中:

L.imageOverlay(imageUrl, imageBounds).addTo(map);

要修复它,只需将其添加到 onMount 回调:

  onMount(() => {
    map = L.map("issmap").setView([51.505, -0.09], 13);
    var imageUrl = "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg",
      imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
    L.imageOverlay(imageUrl, imageBounds).addTo(map);
  });

查看 Codesandbox