如何在Angular项目中引入Leaflet?

5

我正在尝试在我的Angular项目中使用Leaflet包,但是我无法使其正常工作。

我使用npm install leatflet --save命令安装了Leaflet,然后我在angular.json文件中包含了它的依赖项:

"styles": [
            "node_modules/leaflet/dist/leaflet.css",
],
"scripts": [
            "node_modules/leaflet/dist/leaflet.js"
],

我的app.component.ts文件:

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

app.component.html中,我有一个id为map的部分。

我只看到这个: leaflet

有人知道问题出在哪里以及如何解决吗?

非常感谢帮助。 :)


https://github.com/Asymmetrik/ngx-leaflet - IvanSanchez
1个回答

10

安装以下内容以在 Angular 中使用 Leaflet:

npm install leaflet
npm install @asymmetrik/ngx-leaflet

还有 typings

npm install --save-dev @types/leaflet

在您的 Angular CLI .json 中添加以下内容:
  • 对于 Angular 5 及以下版本:angular-cli.json
  • 对于 Angular 6 及以上版本:angular.json
    {
        ...
        "styles": [
            "styles.css",
            **"./node_modules/leaflet/dist/leaflet.css"**
        ],
        ...
    }

在app.module.ts中导入Leaflet模块:

import { LeafletModule } from '@asymmetrik/ngx-leaflet';

imports: [
    LeafletModule.forRoot()
]

并创建一个地图:
<div style="height: 300px;"
     leaflet 
     [leafletOptions]="options">
</div>

并配置您的选项:

options = {
    layers: [
        tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' })
    ],
    zoom: 5,
    center: latLng(46.879966, -121.726909)
};

参考: @asymmetrik/ngx-leaflet

编辑:

如果您不想使用上述软件包,则可以通过以下方法解决问题:

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

谢谢!添加了这个tileLayer之后,我得到了地图。你能解释一下它的作用吗?你知道我的方法哪里出了问题吗? - fonzane
1
@fonzane,地图需要瓦片才能加载,如果你没有放置服务器链接,它就无法加载。你可以在这里选择瓦片:https://leaflet-extras.github.io/leaflet-providers/preview/。 - Maihan Nijat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接