Cannot read property ‘addLayer’ of undefined in svelte

below is my code. I am using leaflet in svelte to plot a map with image.

<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/[email protected]/dist/leaflet.css"
      integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
      crossorigin=""
    />
    <script
      src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
      crossorigin=""
    ></script>
    <style>
      #issmap {
        height: 180px;
      }
    </style>
  </head>
  <body>
    <div id="issmap"></div>
  </body>
</html>

But I am getting a error “Cannot read property ‘addLayer’ of undefined”. How can I solve this ?

Answer

Here your problem is that you try to use map outside the onMount callback so it is undefined in the line:

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

To fix it just add it to the onMount callback:

  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);
  });

Checkout the Codesandbox.

Leave a Reply

Your email address will not be published. Required fields are marked *