简体   繁体   中英

How can I import leaflet into an angular project?

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. :)

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:

  • For Angular 5 and below: angular-cli.json
  • For Angular 6 and above: angular.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)
};

Ref: @asymmetrik/ngx-leaflet

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM