L未定义(Leaflet.js节点包)

时间:2019-06-08 17:20:24

标签: angular typescript leaflet

我正在尝试从Leaflet quickstart guide获取示例以在Angular 7中工作,但是出现错误ERROR ReferenceError: L is not defined。注意:我没有通过JS文件包括Leaflet,而是通过npm install leaflet通过npm安装了它,并且确实显示在我的node_modules中。

import { Component, OnInit } from '@angular/core';
declare let L;


@Component({
  selector: 'app-mapvisual',
  templateUrl: './mapvisual.component.html',
  styleUrls: ['./mapvisual.component.css']
})
export class MapvisualComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const map = 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(map);
  }
}

编辑:我找到了解决方法here.

1 个答案:

答案 0 :(得分:1)

您必须在index.html中包含这些资源


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>

    <!-- Make sure you put this AFTER Leaflet's CSS -->
    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
    integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
    crossorigin=""></script>
</head>
<body>

</body>
</html>

在您的component.html文件中

 <div id="mapid"></div>

component.css

#mapid { height: 180px; }

在您的component.ts文件中

import { Component, OnInit } from '@angular/core';
declare let L;


@Component({
  selector: 'app-mapvisual',
  templateUrl: './mapvisual.component.html',
  styleUrls: ['./mapvisual.component.css']
})
export class MapvisualComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const map = L.map('mapid').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(map);
  }
}