Search code examples
angulartypescriptleafletgisngx-leaflet

how can i pass lat,long from outside to create a leaflet marker angular


  • This is a working code to place a marker using leaflet angular for predefined lat,longs.

    Now i want to customize this by passing lat,long when addmarker button is pressed. Can anyone advise ?

    Lat long infomration is not available when page loads and it has to be passed only when add marker button is pressed.

import { Component, OnChanges } from "@angular/core";
import "leaflet/dist/leaflet.css";
import * as L from "leaflet";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  map;
  markers: L.Layer[] = [];


  markerIcon = {
    icon: L.icon({
      iconSize: [25, 41],
      iconAnchor: [10, 41],
      popupAnchor: [2, -40],
      // specify the path here
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  };

  public options = {
    layers: [
      L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 18,
        attribution: ""
      })
    ],
    zoom: 10,
    center: L.latLng(40.7128, 74.0060)
    //center: L.latLng(this.lat, this.long);
  };

getLatLong() {
this.lat = 40.7128;
this.long = 74.0060;
this.addMarker(this.lat, this.long);

  }


  addMarker(lat, long) {

    const newMarker = L.marker([40.7128, 74.0060], this.markerIcon);
    //const newMarker = L.marker([this.lat, this.long], this.markerIcon);

    this.markers.push(newMarker);

    newMarker.addTo(this.map);
  }

  onMapReady(map: L.Map) {
    this.map = map;
    // Do stuff with map
  }
}




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

<button (click)="addMarker()">
add marker
</button>
<button (click)="getLatLong()">
  getLAtLong
  </button>



Solution

  • You pass the coordinates you want as arguments on addMarker() like this:

    <button (click)="addMarker(46.8523, -121.7603)">
      add marker
    </button>
    

    You do not need getLatLong and another button

    And then using the map instance you change the map center:

    this.map.panTo(new L.LatLng(lat, lng));
    

    Demo