Search code examples
angulartypescriptleafletleaflet.markercluster

Single marker not visualized using ngx leaflet markercluster


When I zoom in a cluster on a map, using ngx angular version of leaflet-markercluster, I can't visualize single marker.

Different result can be obtained using pure javascript and js-version of above modules.

The code of map.component is below:

import { Component, OnInit, Input } from '@angular/core';

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

@Component({
    selector: 'map',
    templateUrl: './map.component.html'
})
export class MapComponent implements OnInit {

  @Input() coords:number[][];
    options = {
        zoom: 5,
    maxZoom : 18,
        center: L.latLng([ 41.5, 12.5 ]),

   layers: [L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {})],


    };

    // Marker cluster stuff
  markerClusterGroup: L.MarkerClusterGroup;
    markerClusterData: L.Marker[] = [];
    markerClusterOptions: L.MarkerClusterGroupOptions;


    ngOnInit() {

        this.markerClusterData = this.generateMarker(this.coords);
    }

    markerClusterReady(group: L.MarkerClusterGroup) {
        this.markerClusterGroup = group;
    }
   [...]

Leaflet options are defined in

    <div leaflet style="height: 400px;"
        [leafletOptions]="options"
        [leafletMarkerCluster]="markerClusterData"
        [leafletMarkerClusterOptions]="markerClusterOptions"
        (leafletMarkerClusterReady)="markerClusterReady($event)">
    </div>

You can visualize entire code and run on stackblitz

How can I resolve single marker visualization?


Solution

  • It has to do with the well known bundle issue with webpack. Define the iconUrl inside the icon variable and it should fix the problem.

    const icon = L.icon({
        iconSize: [25, 41],
        iconAnchor: [10, 41],
        popupAnchor: [2, -40],
        // specify the path here
        iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
        shadowUrl:
          "https://unpkg.com/[email protected]/dist/images/marker-shadow.png"
    });
    

    And just an advice, keep the iconUrl outside the for loop. As you need to declare the variable only once.

    Demo