angular - 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;
})
}
}
解决方案
您正在寻找一个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;
}
});
});
}
推荐阅读
- python - 具有 2 个不同 Websocket API 的不同行为
- outlook-redemption - 从 Windows 服务使用 Outlook 兑换
- api - 即使 JSON 路径有效,karate.jsonPath 也不起作用
- c# - 如何查询带有子表集合的视图?
- python - 有没有办法在 Ubuntu/linux 系统中使用 Window 编译的 dll 到 python 脚本中?
- java - 如何模拟 inetaddress.getlocalhost().gethostname() 抛出异常
- r - R Shiny:向数据表添加新列
- r - 基于具有相同维度 (R) 的另一个表为数据透视表创建自定义格式
- java - Spring Boot Broker-Consumer 项目出错
- node.js - NodeJS - 将数据传递给 httpRequest