首页 > 解决方案 > Angular 5 谷歌地图:仅显示 # 公里半径内的标记

问题描述

我目前正在我的应用程序中制作地图。我为此使用了惊人的 Angular agm 包。

目标是显示带有标记的地图。这些标记来自数据库并包含纬度和经度值。我有数百个标记,我想过滤它们。我只想显示距离我的位置 5 公里以内的标记。我该怎么做?我浏览了包的 API 文档,但没有看到解决方案。任何人都可以帮助我吗?

Map.component.html

<!-- this creates a google map on the page with the given lat/lng from -->
<!-- the component as the initial center of the map: -->
<agm-map
        [latitude]="lat"
        [longitude]="lng"
        [fullscreenControl]="true"
        [zoom]="13"
>

    <agm-marker
            *ngFor="let marker of markers"
            [latitude]="marker.latitude"
            [longitude]="marker.longitude"
            (markerClick)="doSomething($event)"

            >
        <agm-info-window [disableAutoPan]="true">
            <a routerLink="/">Go there</a>
        </agm-info-window>
    </agm-marker>
</agm-map>

map.component.ts

export class FindLocalsComponent implements OnInit{

    lat:number;
    lng: number;
    markers = [];

    constructor(private findLocalsService: FindLocalsService){}

    ngOnInit(){
        let token = localStorage.getItem('token');

        this.findLocalsService.getLocations(token)
            .subscribe((data) => {
                console.log(data.obj);
                this.lat = data.obj.myLocation[0].latitude;
                this.lng = data.obj.myLocation[0].longitude;
                this.markers = data.obj.locationCollection;
            })
    }
}

标签: angulargoogle-maps

解决方案


您正在寻找一个google.maps.geometry.spherical.computeDistanceBetween返回两点之间距离(​​以米为单位)的函数

变更清单:

a) 导入geometry库:

AgmCoreModule.forRoot({
  apiKey: '--key goes here--',
  libraries: ['geometry']
})

b) 要使用该google.maps.geometry.spherical.computeDistanceBetween功能,需要先加载 Google Maps API。为此, MapsAPILoader提供者 的使用如下所示

c) 按距离执行标记过滤

ngOnInit() {
    this.markers = this.getLocations(); //original list of markers data

    this.mapsAPILoader.load().then(() => {
      const center = new google.maps.LatLng(this.lat, this.lng);
      //markers located within 50 km distance from center are included
      this.filteredMarkers = this.markers.filter(m => {
        const markerLoc = new google.maps.LatLng(m.latitude, m.longitude);
        const  distanceInKm = google.maps.geometry.spherical.computeDistanceBetween(markerLoc, center) / 1000;
        if (distanceInKm < 50.0) {
          return m;
        }
      });
    });
  }

演示


推荐阅读