我在Angular应用程序上使用传单,我正在显示一些位于我从后端检索的坐标中的标记。
使用帖子末尾的代码,会显示标记,但它们不会将位置保持在不同的缩放级别,如下图所示。
标记应该在红点之上,但是它们位于另一个位置,并且当我放大或缩小时它们似乎不保持位置。看起来这些点位于具有不同参考系统的不同层上。
我试图将mMarker.prototype.options.icon保留在变量上并使用addTo(map),但它会抛出一个错误,指出“addTo”不是一个函数。
我能做什么?谢谢
import { Component, OnInit } from '@angular/core';
import { MapService } from '../../services/map.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Map } from '../../models/map';
import { Icon, icon, Marker, marker } from 'leaflet';
declare let L;
var map;
@Component({
selector: 'map-component',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
private defaultIcon: Icon = icon({
iconUrl: 'assets/leaflet/marker-icon.png',
shadowUrl: 'assets/leaflet/marker-shadow.png'
});
public coordinates: [number];
constructor(
private _mapService: MapService, private _router: Router
) {
}
ngOnInit() {
Marker.prototype.options.icon = this.defaultIcon;
map = L.map('map').setView([0, 0], 2); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
this.getLocations();
}
getLocations() {
var geoJsonMulti = {
"type": "GeometryCollection",
"geometries": [
]
}
this._mapService.getCoordinates().subscribe(
response => {
if (!response) {
this._router.navigate(['/']);
} else {
var layer = response.cityFeatures.cities;
console.log(layer.cities)
layer.forEach(layer => {
geoJsonMulti.geometries.push(layer);
})
console.log(geoJsonMulti)
}
var myStyle = {
"color": "#ff7800",
"weight": 5,
"opacity": 0.65
};
L.geoJSON(geoJsonMulti, {
style: myStyle
}).addTo(map);
},
error => {
let errorMessage = <any>error;
if (errorMessage !== null) {
let body = JSON.parse(error._body);
}
}
);
}
}
您必须指定图标大小和锚位置,如下所示:
private defaultIcon: Icon = icon({
iconUrl: 'assets/leaflet/marker-icon.png',
shadowUrl: 'assets/leaflet/marker-shadow.png',
iconSize: [41, 51], // => random values you have to choose right ones for your case
iconAnchor: [20, 51] // => random values too
});