My requirement is to create the leaflet map in angular formly,but I am new to this formly
and I know how to use integrate the map with normal html in angular as below
map.component.ts
ngOnInit() {
const map = L.map('map').setView([51.509865,-0.118092], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
}
map.component.html
<div id="map"></div>
map.component.css
div{
height: 500px;
width: 500px;
}
But,Now I have to place the leaflet map in angular formly, can anyone help me regarding this
you can create a custom component of leaflet map and use it wherever in your project:
LeafletMapComponent.html
<div class="col-md-12">
<div id="map" leaflet
[leafletOptions]="Options"
(leafletMapReady)="onMapReady($event)" >
</div>
</div>
LeafletMapComponent.css
#map {
width: 100%;
height: 300px;
}
LeafletMapcomponent.ts
constructor() { }
map;
@Input() markers;
@Output() LMarkerclicked: EventEmitter<any> = new EventEmitter<any>();
@Output() setPositon: EventEmitter<any> = new EventEmitter<any>();
Options = {
layers: [
tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
],
zoom: 7,
center: latLng(29.6060218, 52.5378041)
};
ngOnInit() {
}
onMapReady(map: L.Map) {
setTimeout(() => {
this.map = map;
map.invalidateSize();
this.addMarker();
}, 0);
map.on('click', (e)=>{this.onMapClick(e)});
}
addMarker() {
this.markers.forEach((mapMarker) => {
let m = L.marker([mapMarker.lat, mapMarker.lng], {
draggable: true,
icon: new L.DivIcon({
className: 'my-div-icon',
html: '<img class="my-div-image" src="' + mapMarker.icon +'" />'+
'<label class="MarkerLabel">'+ mapMarker.label +'</label>'
})
}).addTo(this.map).bindPopup("<b>" + mapMarker.info + "</b><br>" + mapMarker.label).on('click', this.markerClick, this).on('dragend', this.markerDragend, this);
});
}
markerClick(e) {
this.LMarkerclicked.emit(e.latlng);
}
markerDragend(e){
this.LMarkerclicked.emit(e.target._latlng);
}
Then for using it :
<app-leaflet-map [markers]="markers" (LMarkerclicked)="onClickLMarker($event)" (setPositon)="onClickLMarker($event)"></app-leaflet-map>
and in your ts file:
markers: MapmarkerVm[] = [
{
lat: 29.60602,
lng: 52.53780,
label: '',
draggable: true,
icon: '../assets/images/marker-active.png',
info: 'cityName'
},
];
onClickLMarker(e) {
this.addEditForm.controls["Latitude"].reset(e.lat);
this.addEditForm.controls["Longtude"].reset(e.lng);
}
export class MapmarkerVm {
lat: number;
lng: number;
label?: string;
draggable: boolean;
icon:string;
info:String;
}