Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Leaflet - Map does does not render properly

No matter which way I try in Angular 7, my Leaflet Map does not load properly. I get a block puzzle with half the screen grey and the other half in random disjointed map blocks (see pic).

Map Block Puzzle:


My HTML has been either:

<div 
  leaflet 
  [leafletOptions]="options">
</div>

or

<div id="map" class="map"></div>


My component is:

import * as L from "leaflet";
...
@Component( {
  styleUrls:  [ "../../../../node_modules/leaflet/dist/leaflet.css" ],
  templateUrl:  "./map.html"
} )
...
export class Map implements OnInit {

  map: any;

  options = {
    layers: [
        L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 7, attribution: '...' })],
        zoom: 5,
        center: L.latLng([ 46.879966, -121.726909 ])};

  async ngOnInit() {

    this.map =  L.map('map').setView( [37.8, -96], 4 );
    var osmUrl    = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
    var osm       = new L.TileLayer( osmUrl, { minZoom: 1, maxZoom: 7, attribution: osmAttrib } );      
    this.map.addLayer( osm ); // */

  }

} 

My app-module.ts has the "LeafletModule.forRoot()" added to the Imports. invalidateSize() did not work for me, though perhaps I used it wrong. I did it with a setTimeout and not, in a method call.

Am I missing something? Do I have to add a script to INDEX.HTML like this or something?

<script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>

I have searched a lot of posts and followed tutorials, but nothing gets me a nice map loaded.

Can anyone help?

Thanks, Moa

like image 687
Moa Avatar asked Mar 05 '19 06:03

Moa


1 Answers

Here are the steps you need to follow:

1.install leaflet and import leaflet css style on angular.json

"styles": ["../node_modules/leaflet/dist/leaflet.css", "styles.css"],

2.import leaflet in your ts:

import * as L from "leaflet";

3.initialize your map inside ngOnInit:

map;
ngOnInit() {
    this.map = L.map("map").setView([46.879966, -121.726909], 7);

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
          attribution:
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);
}

Demo

You do not need to use script & cdns since you import the files directly from the local folder. Plus you were trying to use leaflet 0.4 which is really obsolete version

like image 98
kboul Avatar answered Sep 21 '22 13:09

kboul