Leaflet Map and IONIC 4

2019-06-11 06:06发布

问题:

I need to create maps on IONIC 4.
But it is not possible, because I don't have maps for IONIC 4.

So, is it possible to create a Leaflet Map on IONIC 4 for an App on Android?

回答1:

  1. npm install leaflet --save
  2. inside angular.json or any similar config doc of your app, add the following:

    a)

    "assets": [
          ...,
          {
            "glob": "**/*",
            "input": "./node_modules/leaflet/dist/images",
            "output": "leaflet/"
          }
        ],
    

    b)

    "styles": [
          ...,
          "./node_modules/leaflet/dist/leaflet.css"
        ],
    
  3. Inside your component.html:

    <div id="map" style="width:100%; height:100%;"></div>
    
  4. Inside your component.ts:

    import { Map, latLng, tileLayer, Layer, marker } from 'leaflet';
    
    map: Map;
    
  5. then you can call a function like this when the DOM is loaded:

    loadmap() {
      setTimeout(() => {
        this.map = new Map('map').setView([this.lat, this.lng], 8);
    
        tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
           // tslint:disable-next-line
          attribution: 'Map data &copy; <a 
        href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a 
        href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery 
        © <a href="https://www.mapbox.com/">Mapbox</a>',
          maxZoom: 18
        }).addTo(this.map);
    
      }, 50);
    }
    

Notice, this.lat, this.lng are my own values.

For anything else, there are the docs: https://leafletjs.com/reference-versions.html

EDIT:

Instead of setTimeout, I use Ionic's ionViewDidEnter(). SetTimeout was a workaround, because Angular's ngAfterViewInit() was not working for me.