在Node.js服务器端运行Leaflet

8

我试图在nodejs服务器上运行leaflet但没有成功。我按照下载部分所述使用jake构建它,但是当我在服务器文件中要求leaflet时,如果我启动我的节点服务器,它会因为以下错误而崩溃:

ReferenceError: window is not defined

谢谢,我了解node。但是否有一种方法可以在服务器端使用leaflet?我需要对L.geojson进行一些操作(https://github.com/mapbox/leaflet-pip),而且如果没有"L"引用,我就无法完成操作。

我将非常感激任何帮助。 谢谢。


正如传单作者所建议的那样,点在多边形内部的代码不需要依赖项。因此,他建议我使用像turf(http://github.com/Turfjs/turf-inside)这样的库,并避免在服务器端使用leaflet。问题解决了。 - Thco
2个回答

14

你可以通过模拟浏览器来在 node.js 中加载 leaflet:

// 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');

我将它与Leaflet中的点面关系插件一起使用。


2
您还应该在 window 中添加 devicePixelRatio: 1,并在 navigator 下添加 platform: 'nodejs',以使 Leaflet 的更新版本正确加载。 - Ruben S
'GLOBAL'已被弃用,请使用'global'代替。 - S Panfilov
node --require node_modules/jsdom-global/register - Lee Goddard

2

1
看起来是我想要的。但我在Windows上遇到了一些问题,我缺少一些依赖项(如MS Visual Studio...)。如果有人有另一个和这个一样好的解决方案,我仍然会关注这个帖子。谢谢。 - Thco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接