til*_*lly 1 google-maps angular
我目前正在我的应用程序中制作地图。我为此使用了惊人的 Angular agm 包。
目标是显示带有标记的地图。这些标记来自数据库并包含纬度和经度值。我有数百个标记,我想过滤它们。我只想显示距离我所在位置(例如 5 公里)内的标记。我这个怎么办 我浏览了包的 API 文档,但没有看到解决方案。任何人都可以帮助我吗?
地图.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>
Run Code Online (Sandbox Code Playgroud)
地图组件.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;
})
}
}
Run Code Online (Sandbox Code Playgroud)
您正在寻找一个google.maps.geometry.spherical.computeDistanceBetween函数,它返回两点之间的距离(以米为单位)
变更清单:
a) 导入geometry库:
AgmCoreModule.forRoot({
apiKey: '--key goes here--',
libraries: ['geometry']
})
Run Code Online (Sandbox Code Playgroud)
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;
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4575 次 |
| 最近记录: |