Angular - Leaflet.js - not showing/rendering wrong

650 Views Asked by At

I know this has been here a few times now, but I could not make those answers work for me.

First of the import of leaflet.css is weird... This doesn't work - angular.json

    "styles": [
        "src/styles.css",
        "path/to/leaflet.css"
    ]

This also does not work - src/styles.css

    @import "path/to/leaflet.css"

This works - map.component.ts

    styleUrls: ['./map.component.css', "path/to/leaflet.css"]

Why is it that only when imported through the component the css is actually imported? It is not complaining about a wrong path or anything in the first two cases.

Now even with leaflet.css being imported successfully, the map renders about half of the tiles. Someone said that resizing the window fixes the issue. But resizing a window makes the map gray...

The rest of the code:

    import { LeafletModule } from '@asymmetrik/ngx-leaflet';

    @NgModule({
      declarations: [
        AppComponent,
        MapComponent
      ],
      imports: [
        BrowserModule,
        LeafletModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })

    //...
    
    <div id="map" 
      leaflet 
      [leafletOptions]="options"
      [leafletLayersControl]="layers"
    ></div>

    //...

    layers = {
    baseLayers: {
      "OSM": tileLayer(MapConfig.layers.osm.url, {
        attribution: MapConfig.layers.osm.attribution
      }),
      "ArcGIS": tileLayer(MapConfig.layers.arcgis.url, {
          attribution: MapConfig.layers.arcgis.attribution
      }),
      //...
    },
    overlays: {}
    }

    options = {
      center: latLng(MapConfig.defaultLocation[0], MapConfig.defaultLocation[1]),
      zoom: MapConfig.zoom,
      layers: [this.layers.baseLayers["OSM"]]
    }

Here is the full code sample: https://3fjni.csb.app/

1

There are 1 best solutions below

1
ghybs On

What happens is that your 2 first attempts at loading Leaflet CSS actually work.

The 3rd attempt (in component styleUrls) actually does not work. But it may look like the situation is better than in previous cases, because now you can see some tiles... which are actually scrambled up all over your page, due to the missing CSS.

In the first 2 cases, you do not see your map (making it seem like it does not work, or like the CSS import failed) because you have styled the map container height as 100%; but this means 100% of its parent height, which is 0 if not explicitly defined. Drawing a border on the map container make the issue more visible. And setting the height fixed (e.g. with 400px) make your Leaflet map correctly appear.