Search code examples
angulartypescriptleafletleaflet.markerclusterngx-leaflet

Issue in creating marker in leaflet


I am trying to create a marker using leaflet angular 8.The following example is working fine.

But in the addMarker method when i change the value of lat and long(valid lat long) the marker is no longer created. Can someone please explain?

LAYER_OSM = tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Open Street Map' });

    // Values to bind to Leaflet Directive
    options = {
        layers: [ this.LAYER_OSM ],
        zoom: 10,
        center: latLng(46.879966, -121.726909)
    };

    markers: Layer[] = [];



    addMarker() {
        const newMarker = marker(
        [ 46.879966 + 0.1 * (Math.random() - 0.5), -121.726909 + 0.1 * (Math.random() - 0.5) ],

            {
                icon: icon({
                    iconSize: [ 25, 41 ],
          iconAnchor: [ 13, 41 ],
          iconUrl: 'leaflet/marker-icon.png',
          shadowUrl: 'leaflet/marker-shadow.png'


                })
            }
        );

        this.markers.push(newMarker);
    }

    removeMarker() {
        this.markers.pop();
    }

}

Solution

  • I am not sure where is your issue. Check this demo. It works regardless which marker values you place

        <div
          style="height: 90vh;"
          leaflet
          [leafletOptions]="options"
          (leafletMapReady)="onMapReady($event)"
        ></div>
    
        <button (click)="addMarker()">
          add marker
        </button>
    

    component:

      map;
      markers: L.Layer[] = [];
    
      popupText = "Some popup text";
    
      markerIcon = {
        icon: L.icon({
          iconSize: [25, 41],
          iconAnchor: [10, 41],
          popupAnchor: [2, -40],
          // specify the path here
          iconUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png",
          shadowUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-shadow.png"
        })
      };
    
      options = {
        layers: [
          L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
            maxZoom: 18,
            attribution: ""
          })
        ],
        zoom: 10,
        center: L.latLng(46.879966, -121.726909)
      };
    
      addMarker() {
        // const newMarker = L.marker(
        //   [
        //     46.879966 + 0.1 * (Math.random() - 0.5),
        //     -121.726909 + 0.1 * (Math.random() - 0.5)
        //   ],
        //   this.markerIcon
        // );
        const newMarker = L.marker([46.879966, -121.726909], this.markerIcon);
    
        this.markers.push(newMarker);
    
        newMarker.addTo(this.map);
      }
    
      onMapReady(map: L.Map) {
        this.map = map;
        // Do stuff with map
      }
    

    Demo