首页 > 解决方案 > 如何在 Angular 12.x 中导入传单控制地理编码器?

问题描述

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

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

我包括了样式:./node_modules/leaflet/dist/leaflet.cssangular.json文件上和LeafletModule没有我的app.module.ts.

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

这是我的 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”

标签: angulartypescriptleaflet

解决方案


您尚未导入库及其样式:

  1. 安装传单控制地理编码器
  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)以避免收到打字稿错误,但您收到的错误是因为您没有提前导入库。

演示


推荐阅读