Leaflet Map and IONIC 4

依然范特西╮ 提交于 2019-12-08 08:34:52

问题


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.




回答2:


Answer from @alex351 is very good. But I arrived into this thread from Google looking for "ionic4 leaflet broken map".

I had tiles not showing up, even with the import of leaflet.css.

It was because I wrote

<ion-content>
  <div id="map" style="height:400px; width: 100%;"></div>
</ion-content>

It seems Ionic4 css conflicts with leaflet. You need to get the <div> outside of <ion-content>.

Correct is just :

<div id="map" style="height:400px; width: 100%;"></div>

Hope this help someone



来源:https://stackoverflow.com/questions/53945625/leaflet-map-and-ionic-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!