0

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();
    }

}
kboul
  • 13,836
  • 5
  • 42
  • 53
sunny
  • 51
  • 12
  • 1
    when do you change the value? Can you make a demo to reproduce the issue? – kboul Apr 10 '20 at 16:41
  • 46.879966, -121.726909 these two values if i replace with any other lat longs in the addMarker method ,marker is not getting created – sunny Apr 10 '20 at 17:10

1 Answers1

1

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

kboul
  • 13,836
  • 5
  • 42
  • 53