How to Install Leaflet plugin for ionic 2

2019-07-18 04:32发布

问题:

Anyone can help this? I am trying to import a leaflet plugin (https://github.com/Leaflet/Leaflet.markercluster) for ionic 2

Here is step which I did:

npm install leaflet.markercluster --save

I added leaflet like this:

import * as L from 'leaflet'; import * as LL from 'leaflet.markercluster';

And using it like this:

var markers = LL.markerClusterGroup();

i got an error TypeError:

WEBPACK_IMPORTED_MODULE_2_leaflet_markercluster.markerClusterGroup is not a function

Are there any ways to custom webpack to load plugin lib? Thanks

回答1:

Leaflet.markercluster plugin does not export itself the "standard" / UMD way.

When you import it, it only performs a side effect, i.e. it attaches itself to the L (Leaflet) global namespace. It does not return anything into your default import nor LL variable.

But you should be able to use it as if you had included it the "old school" way (i.e. through a <script> tag):

var mcg = L.markerClusterGroup();

BTW, both Leaflet and Leaflet.markercluster perform side effects, so you would just need to import them this way:

import 'leaflet'; // Creates a global L namespace.
import 'leaflet.markercluster'; // Attaches L.markerClusterGroup to global L.


回答2:

You need to use type declarations along with the module if you are using a javascript module. For leaflet.markercluster it should be here.

After

npm install leaflet.markercluster --save

Do:

npm install --save-dev @types/leaflet-markercluster

Also ensure your tsconfig.json has the entry "typeRoots": ["types"],

Now it can be imported in your class.

import * as LL from 'leaflet-markercluster';