首页 > 解决方案 > 如何使用 @asymmetrik/ngx-leaflet 默认选择 baseLayers 和覆盖

问题描述

stackblitz 代码@asymmetrik/ngx-leaflet

如何使默认选择 baseLayers 和覆盖?我使用 layersControl 来显示这些 baseLayers 和覆盖。

标签: angularleafletngx-leaflet

解决方案


将所有 app.component.ts 内容替换为:

import { Component, OnInit } from "@angular/core";
import { tileLayer, marker } from "leaflet";
declare let L;

// the best thing is to separate this (you can also do is in external file modal.ts for example)
const LayersForMap = {
  layer1: tileLayer("https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", {
    maxZoom: 30,
    minZoom: 12
  }),
  layer2: tileLayer(
    "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
    { maxZoom: 30, minZoom: 12 }
  ),
  layer3: tileLayer("https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", {
    maxZoom: 30,
    minZoom: 12
  }),
  layer4: tileLayer("", { maxZoom: 100, minZoom: 12 })
};

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  // attributs
  name = "Angular";
  options: any;
  layersControl: any;

  ngOnInit() {
    this.init();
  }

  //
  init() {
    this.options = this.getOptions();
    this.layersControl = this.getLayerControls();
  }
  getOptions() {
    this.options = {
      layers: [LayersForMap.layer1 /* your problem was exactly here ... */],
      zoom: 5,
      center: L.latLng(46.879966, -121.726909)
    };
    return this.options;
  }

  getLayerControls() {
    this.layersControl = {
      baseLayers: {
        "Topo Map": LayersForMap.layer1,
        Imagery: LayersForMap.layer2,
        Outdoors: LayersForMap.layer3,
        None: LayersForMap.layer4
      },
      overlays: {
        "example overlays": this.exampleOverlays()
      }
    };
    return this.layersControl;
  }

  exampleOverlays() {
    const mark = marker(L.latLng(46.879966, -121.726909)).bindTooltip(
      "this is example of overlays"
    );
    return mark;
  }
}

推荐阅读