【问题标题】:How to import leaflet-control-geocoder in Angular 12.x?如何在 Angular 12.x 中导入传单控制地理编码器?
【发布时间】:2021-07-16 21:12:08
【问题描述】:

我已经使用以下命令在 Angular 12 中安装了传单:

npm install leaflet
npm install @asymmetrik/ngx-leaflet
npm install --save-dev @types/leaflet

我在angular.json 文件中包含了以下样式:./node_modules/leaflet/dist/leaflet.cssLeafletModule 没有我的app.module.ts

地图工作正常,但是,我正在尝试从地理编码器添加搜索输入控件,因为我已将地理编码器链接的链接和脚本包含到我的 index.html,找到 here

这是我的 ts 文件:

import { Component, AfterViewInit } from '@angular/core';
import * as L from 'leaflet';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
})

export class AppComponent implements AfterViewInit {
  title = 'leaf-let';

  private map: any;

  constructor() {}

  ngAfterViewInit(): void {
   this.initMap();
  }

  private initMap(): void {
   this.map = L.map('map').setView([14.094167, -87.206667], 15);

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

 tiles.addTo(this.map);

  //L.Control.geocoder().addTo(this.map);
 }

但是当我做L.Control.geocoder().addTo(this.map); 时,它给了我错误:

“typeof control”类型上不存在属性“geocoder”

【问题讨论】:

  • 您已将传单控制地理编码器作为 index.html 上的脚本导入?在导入级别尝试,声明 var Control;然后在你的组件 Control.geocoder().addTo(this.map);

标签: angular typescript leaflet


【解决方案1】:

您尚未导入库及其样式:

  1. 安装leaflet-control-geocoder
  2. import "leaflet-control-geocoder/dist/Control.Geocoder.css";
  3. import "leaflet-control-geocoder/dist/Control.Geocoder.js";

另外,您似乎没有使用 ngx-leaflet 而是使用 vanilla 传单。如果是这种情况,您应该采用以下方法:

private initMap(): void {
    this.map = L.map("map").setView([14.094167, -87.206667], 15);

    const tiles = 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);

    tiles.addTo(this.map);

    (L.Control as any).geocoder().addTo(this.map);
}

使用(L.Control as any) 初始化插件以避免收到打字稿错误,但您收到的错误是因为您没有提前导入库。

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多