calvinmetcalf / leaflet.shapefile

Shapefile in Leaflet
http://calvinmetcalf.github.io/leaflet.shapefile/
MIT License
259 stars 119 forks source link

Leaflet error when loading shapefile (shp is not defined) #62

Closed mperdikeas closed 4 years ago

mperdikeas commented 4 years ago

(also posted in https://stackoverflow.com/q/60265760/274677) I am following the Leaflet essentials book, on how to load shapefiles. The book's instructions are:

First, add references to two JavaScript files. The first, leaflet-shpfile, is the plugin, and the second depends on the shapefile parser, shp.js:

<script src="leaflet.shpfile.js">
</script><script src="shp.js"></script>

Next, create a new shapefile layer and add it to the map. Pass the layer path to the zipped shapefile:

var shpfile = new L.Shapefile('council.zip');
shpfile.addTo(map);

I've followed the above instructions with slight changes since I'm on Webpack. Here's what I 've done:

  1. installed shpjs with npm i shpjs --S
  2. downloaded leaflet.shpfile.js from github and placed it in src/
  3. in my *.js file I require both shpjs and leaflet.shpfile.js with the following code:

const shp=require('shpjs');
require('./leaflet.shpfile.js');

I then access the shapefile as instructed:

console.log(shp);
const shapeFileLayer = L.shapefile(someURL);

On the last line of code I get the following trace:

react-dom.production.min.js:196 ReferenceError: shp is not defined
    at NewClass.addFileData (leaflet.shpfile.js:38)
    at NewClass.initialize (leaflet.shpfile.js:25)
    at new NewClass (leaflet-src.js:300)
    at Object.L.shapefile (leaflet.shpfile.js:67)
    at Map.createLayerGroups (main.js_+_3_modules:342)
    at Map.componentDidMount (main.js_+_3_modules:186)
    at ik (react-dom.production.min.js:251)
    at exports.unstable_runWithPriority (scheduler.production.min.js:18)
    at fg (react-dom.production.min.js:120)
    at Yj (react-dom.production.min.js:244)

The console.log statement on the line immediately above succeeds, showing that some function shp is defined. I cannot, then, explain why I get the reference error shp is not defined on the line that comes immediately next.

mperdikeas commented 4 years ago

I was advised that I had to do: window.shp=require('shpjs');. This seems to solve this issue.