Angular Leaflet - 地图无法正确渲染

Moa*_*Moa 8 leaflet typescript angular-leaflet-directive angular

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

\n\n

地图块拼图:

\n\n

\n\n


\n我的 HTML 是:

\n\n
<div \n  leaflet \n  [leafletOptions]="options">\n</div>\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者

\n\n
<div id="map" class="map"></div>\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n我的组件是:

\n\n
import * as L from "leaflet";\n...\n@Component( {\n  styleUrls:  [ "../../../../node_modules/leaflet/dist/leaflet.css" ],\n  templateUrl:  "./map.html"\n} )\n...\nexport class Map implements OnInit {\n\n  map: any;\n\n  options = {\n    layers: [\n        L.tileLayer(\'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\', { maxZoom: 7, attribution: \'...\' })],\n        zoom: 5,\n        center: L.latLng([ 46.879966, -121.726909 ])};\n\n  async ngOnInit() {\n\n    this.map =  L.map(\'map\').setView( [37.8, -96], 4 );\n    var osmUrl    = \'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\';\n    var osmAttrib = \'Map data \xc2\xa9 <a href="http://openstreetmap.org">OpenStreetMap</a> contributors\';\n    var osm       = new L.TileLayer( osmUrl, { minZoom: 1, maxZoom: 7, attribution: osmAttrib } );      \n    this.map.addLayer( osm ); // */\n\n  }\n\n} \n
Run Code Online (Sandbox Code Playgroud)\n\n

我的 app-module.ts 将“LeafletModule.forRoot()”添加到 Imports.\ninvalidateSize() 对我不起作用,尽管也许我用错了。我是通过 setTimeout 完成的,而不是在方法调用中完成的。

\n\n

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

\n\n
<script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

有人可以帮忙吗?

\n\n

谢谢,\n莫阿

\n

kbo*_*oul 9

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

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

"styles": ["../node_modules/leaflet/dist/leaflet.css", "styles.css"],
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

演示

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

  • 它确实有效,是的!但有一件事没有提到,尽管也许因为我不是专家,所以没有必要。当您将“./node_modules/leaflet/dist/leaflet.css”添加到“angular.js”时,重新启动您的项目!“npm start”是我所缺少的。非常感谢。 (3认同)