5

无论我在 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 ); // */

  }

} 

我的 app-module.ts 在 Imports 中添加了“LeafletModule.forRoot()”。invalidateSize() 对我不起作用,尽管也许我用错了。我是用 setTimeout 做的,而不是在方法调用中做的。

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

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

我搜索了很多帖子并遵循教程,但没有什么能让我加载一张漂亮的地图。

任何人都可以帮忙吗?

谢谢,莫阿

4

2 回答 2

4

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

1.在angular.json上安装leaflet并导入leaflet css样式

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

2.在您的ts中导入传单:

import * as L from "leaflet";

3.在 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);
}

演示

您不需要使用脚本和 cdns,因为您直接从本地文件夹导入文件。另外,您正在尝试使用传单 0.4,这确实是过时的版本

于 2019-03-05T08:45:02.367 回答
1

我正在使用 Angular Cli:9.1.1

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

npm i leaflet

像这样修改angular.json文件

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

最后重新运行项目ng serve

于 2020-04-21T12:19:33.310 回答