Angular 传单 - 地图无法正确呈现

Angular Leaflet - Map does does not render properly

无论我在 Angular 7 中尝试哪种方式,我的传单地图都无法正确加载。我得到一个方块拼图,一半屏幕是灰色的,另一半是随机不连贯的地图块(见图)。

地图方块拼图:


我的 HTML 是:

<div 
  leaflet 
  [leafletOptions]="options">
</div>

<div id="map" class="map"></div>


我的组件是:

import * as L from "leaflet";
...
@Component( {
  styleUrls:  [ "../../../../node_modules/leaflet/dist/leaflet.css" ],
  templateUrl:  "./map.html"
} )
...
export class Map implements OnInit {

  map: any;

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

  async ngOnInit() {

    this.map =  L.map('map').setView( [37.8, -96], 4 );
    var osmUrl    = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
    var osm       = new L.TileLayer( osmUrl, { minZoom: 1, maxZoom: 7, attribution: osmAttrib } );      
    this.map.addLayer( osm ); // */

  }

} 

我的应用程序-module.ts 已将 "LeafletModule.forRoot()" 添加到导入中。 invalidateSize() 对我不起作用,尽管我可能用错了。我是用 setTimeout 而不是在方法调用中完成的。

我错过了什么吗?我是否必须像这样向 INDEX.HTML 添加脚本?

<script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>

我搜索了很多帖子并遵循了教程,但没有任何东西让我加载了漂亮的地图。

有人能帮忙吗?

谢谢, 恐鸟

以下是您需要遵循的步骤:

1.install 传单并在 angular.json

上导入传单 css 样式
"styles": ["../node_modules/leaflet/dist/leaflet.css", "styles.css"],

2.import 传单在你的 ts:

import * as L from "leaflet";

3.initialize 你在 ngOnInit 中的地图:

map;
ngOnInit() {
    this.map = L.map("map").setView([46.879966, -121.726909], 7);

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
          attribution:
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);
}

Demo

您不需要使用脚本和 cdns,因为您直接从本地文件夹导入文件。另外你试图使用 leaflet 0.4 这真的是过时的版本

我正在使用 Angular CLI: 9.1.1

在控制台中通过 npm 命令安装 leaflet

npm i leaflet

像这样修改angular.json文件

{
  ...
  "projects": {
    "project-name": {
      ...
      "architect": {
        "build": {
          ...
          "options": {
            ...
            "styles": [
              "./src/styles.scss",
              "./node_modules/leaflet/dist/leaflet.css"
            ],
            ...
          }
        }
      }
    }
  }
}

最后 ng serve

重新 运行 项目