1

I have the following code working here and in jsfiddle to to add a GeoJSON LineString to a leaflet map using a function which is triggered by clicking on the map.

// get base map tiles
var map = L.map('map').setView([30, 1], 7);

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

var data = {
  "type": "FeatureCollection",
  "features": [{
    "id": "0",
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
          1,
          30
        ],
        [
          2,
          31
        ]
      ]
    }
  }]
}


map.on('click', function(e) {
  L.geoJSON(data).addTo(map);
});
#map {
  width: 400px;
  height: 300px;
  background-color: black;
}
<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>

The issue is that I cannot get this code to work as expected in a Django application or just outside of jsfiddle. I currenlty have a html file with the following code which is included in a parent html file.

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static '/css/map.css' %}">
<link rel="stylesheet" type="text/css" href="//unpkg.com/leaflet/dist/leaflet.css">
<script src="//unpkg.com/leaflet/dist/leaflet.js"></script>

<div id="map"></div>
<script src="{% static '/js/map.js' %}"></script>

The map loads as expected but when I click on the map to activate the function, I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'x')
    at m.intersects (Bounds.js:135:27)
    at i._clipPoints (Polyline.js:251:42)
    at i._update (Polyline.js:296:8)
    at i._reset (Path.js:140:8)
    at i.onAdd (Path.js:85:8)
    at i._layerAdd (Layer.js:114:8)
    at i.whenReady (VM32 leaflet.js:5:42397)
    at i.addLayer (VM32 leaflet.js:5:65406)
    at i.eachLayer (LayerGroup.js:122:11)
    at i.onAdd (LayerGroup.js:106:8)

The issue is caused by min2 being undefined in Bounds.js.

Any help would be very appreciated :)

1 Answers1

0

It turns out the issue was caused by the map already being initialised which led to the bounds being undefined. This answer solved the problem - I just needed to add this to the top of the js file:

var container = L.DomUtil.get('map');
if (container != null) {
    container._leaflet_id = null;
}