首页 > 解决方案 > 在 Angular 中的 Leaflet 地图上显示 geoJSON 数据

问题描述

我正在尝试在传单地图上展示一些 geoJSON 数据。geoJSON 文件很大(60mb),加载数据时网站的性能很糟糕。geoJSON 是关于流量密度等等,所以它包含大约 230k 段......

到目前为止,我尝试过的是leaflet.vectorgrid通过创建这里leaflet.vectorgrid.d.ts提到的 Angular 来实现。这是文件:

import * as L from "leaflet";

declare module "leaflet" {
  namespace vectorGrid {
    export function slicer(data: any, options?: any): any;
  }
}

虽然表现还是很差。

到目前为止,这是我的代码:

import { Component, OnInit } from "@angular/core";
import {
  MapOptions,
  LatLng,
  TileLayer,
  Map,
  LeafletEvent,
  Circle,
  Polygon
} from "leaflet";

import * as L from "leaflet";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "map-visualization",
  templateUrl: "./map-visualization.component.html",
  styleUrls: ["./map-visualization.component.scss"]
})
export class MapVisualizationComponent implements OnInit {
  leafletOptions: MapOptions;
  layersControl: any;
  map: Map;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.initializeMap();
  }

  /**
   * Initializes the map
   */
  initializeMap() {
    this.leafletOptions = {
      layers: [
        new TileLayer(
          "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
          {
            maxZoom: 18
          }
        )
      ],
      zoom: 4,
      center: new LatLng(48.1323827, 4.172899)
    };
  }

  /**
   * Once the map is ready, it pans to the user's current location and loads the map.geojson
   * @param map Map instance
   */
  onMapReady(map: Map) {
    this.map = map;

    if (navigator) {
      navigator.geolocation.getCurrentPosition(position => {
        this.map.setView(
          new LatLng(position.coords.latitude, position.coords.longitude),
          12
        );
      });
    }

    this.http.get("assets/map.json").subscribe((json: any) => {
      L.geoJSON(json).addTo(this.map);
    });
  }

  /**
   * Return the current bound box
   * @param event Leaflet event
   */
  onMapMoveEnd(event: LeafletEvent) {
    console.log("Current BBox", this.map.getBounds().toBBoxString());
  }
}

最后,geoJSON 总是那么大(60mb)......所以,我想知道是否有一种方法可以过滤在当前边界框中获取的数据。

请注意,该文件暂时存储在本地,但稍后我将从 API 中获取它。

标签: angularperformanceleafletgeojson

解决方案


以下方法应该与传单本机一起工作(不依赖于另一个库):

this.map.getBounds()- 返回LatLngBounds- 地图的边界(4 个角的坐标) - “边界框” - 你已经在做这个了。

LatLngBounds有一个名为 的方法contains()true如果 的值coords在边界框内则返回:https ://leafletjs.com/reference-1.5.0.html#latlngbounds-contains

onMapReady()您可以创建一个方法,该方法既可以调用,也可以onMapMoveEnd()执行以下操作:

addItemsToMap(items: []): Layer[] {
  const tempLayer: Layer[] = [];

  items.forEach(item => {
    if (item.coordinates) {
      const itemCoordinates = latLng(
        item.coordinates.latitude,
        item.coordinates.longitude
      );
      /** Only add items to map if they are within map bounds */
      if (this.map.getBounds().contains(itemCoordinates)) {
        tempLayer.push(
          marker(itemCoordinates, {
            icon: icon(
              this.markers['red']
            ),
            title: item.description
          })
        );
      }
    }
  });

  return tempLayer;
}

根据我的经验,Leaflet 可以轻松处理多达 800 个功能。如果用户体验允许,您还可以向用户显示一条消息,要求他们缩放或平移,直到特征数量低于可容忍的数量。

注意: contains() 接受LatLngLatLngBounds. 要查看折线或多边形是否重叠或“包含在”边界框内,请执行以下任一操作:

这两种方法显然会返回不同的结果:质心/重叠应该返回更多的匹配。


推荐阅读