Google Angular 5 Google地图:仅显示半径为#公里的标记 [英] Angular 5 google maps : show only markers in radius of # kilometers
问题描述
我目前正在我的应用中制作地图.我为此使用了令人惊叹的Angular agm软件包.
I'm currently making a map in my app. I'm using the amazing Angular agm package for this.
目标是显示带有标记的地图.这些标记来自数据库,包含纬度和经度值.我有数百个标记,我想过滤它们.我只想显示距离我的位置5公里之内的标记.我该怎么办?我查看了该软件包的API文档,但没有看到解决方案.有人可以帮助我吗?
The goal is to display a map with markers. These markers come from the database and contain latitude and longitude values. I have hundreds of markers and I want to filter those. I only want to display the markers that are within a distance e.g 5 kilometers of my location. How do I this? I went through the API docs of the package, but I don't see the solution. Anyone can help me?
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
函数,该函数返回两点之间的距离(以米为单位)
You are looking for a google.maps.geometry.spherical.computeDistanceBetween
function which returns the distance between two points (in meters)
更改列表:
a)导入geometry
库:
AgmCoreModule.forRoot({
apiKey: '--key goes here--',
libraries: ['geometry']
})
b)要使用google.maps.geometry.spherical.computeDistanceBetween
功能,需要首先加载Google Maps API.为此,使用 MapsAPILoader
提供程序作为如下所示
b) to utilize google.maps.geometry.spherical.computeDistanceBetween
function, Google Maps API needs to be loaded first. For that matter MapsAPILoader
provider is utilized as demonstrated below
c)按距离执行标记过滤
c) perform markers filtering by distance
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;
}
});
});
}
这篇关于Google Angular 5 Google地图:仅显示半径为#公里的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!