Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running leaflet on nodejs server side

I tried to run leaflet on a nodejs server side without success. I build it with jake as described in the download section, but then, when I require leaflet on a server file, if I start my node server, it crash with this error :

ReferenceError: window is not defined

Thanks node, I know it. But Is there a way to use leaflet on server side ? I need it for some operation on a L.geojson (https://github.com/mapbox/leaflet-pip) and I can't manage to do it without the "L" reference.

I'll appreciate any help. Thanks.

like image 814
Thco Avatar asked Jan 27 '15 09:01

Thco


People also ask

Does node js run server-side?

Node. js is an open source JavaScript runtime environment that lets developers run JavaScript code on the server. If that's too complex for you to understand then you should think of it this way: Node. js is JavaScript that runs outside the browser — on the server.

Can we use node js on client-side?

Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node. js modules for client-side JavaScript applications without having to use a server with Node. js just to implement functionality that is already available as a Node.


1 Answers

You can load leaflet in node.js by simulating the browser:

// Create globals so leaflet can load
global.window = {
  screen: {
    devicePixelRatio: 1
  }
};
global.document = {
  documentElement: {
    style: {}
  },
  getElementsByTagName: function() { return []; },
  createElement: function() { return {}; }
};
global.navigator = {
  userAgent: 'nodejs',
  platform: 'nodejs'
};
global.L = require('leaflet');

I used this in conjunction with Point in Polygon for Leaflet.

like image 90
Brendan Nee Avatar answered Sep 20 '22 16:09

Brendan Nee