Reputation: 440
I'm trying to use the leatflet package in my Angular project but I can't get it to work.
I installed leatflet with npm install leatflet --save
then I'm including the dependencies in the angular.json
file:
"styles": [
"node_modules/leaflet/dist/leaflet.css",
],
"scripts": [
"node_modules/leaflet/dist/leaflet.js"
],
My app.component.ts
file:
import { Component, OnInit } from '@angular/core';
import * as L from 'leaflet';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
constructor() {}
ngOnInit() {
const myMap = L.map('map').setView([51.505, -0.09], 13);
}
onAdressSubmit(form) {
console.log(form.value.adress);
}
}
and inside the app.component.html
I have a section with an id of map.
All I see is this:
Does someone know where the problem lies and how to fix it?
Help would be much appreciated. :)
Upvotes: 5
Views: 18336
Reputation: 9355
Install the following to have Leaflet for Angular:
npm install leaflet
npm install @asymmetrik/ngx-leaflet
And typings
:
npm install --save-dev @types/leaflet
Add the following in your Angular CLI .json:
{
...
"styles": [
"styles.css",
**"./node_modules/leaflet/dist/leaflet.css"**
],
...
}
Import Leaflet Module in app.module.ts:
import { LeafletModule } from '@asymmetrik/ngx-leaflet';
imports: [
LeafletModule.forRoot()
]
And create a map:
<div style="height: 300px;"
leaflet
[leafletOptions]="options">
</div>
And configure your options:
options = {
layers: [
tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' })
],
zoom: 5,
center: latLng(46.879966, -121.726909)
};
Edit:
If you do not want to use the above package, then fix your issue with:
ngOnInit() {
const myMap = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);
}
Upvotes: 10