如何在Angular组件中向传单地图添加标记

时间:2019-03-17 20:07:55

标签: angular leaflet gis

我正在Angular应用程序上使用传单,并显示了一些标记,这些标记位于从后端检索的坐标中。

帖子末尾带有代码,显示了标记,但它们并未将位置保持在不同的缩放级别,如下面的图像所示。

enter image description here enter image description here enter image description here

标记应该在红点上,但是它们在另一个位置,并且当我放大或缩小时,它们似乎没有保持位置。看起来这些点位于具有不同参考系统的不同层上。

我试图将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);
        }
      }
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您必须指定图标大小和锚点位置,诸如此类:

  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
  });

查看此处:https://leafletjs.com/examples/custom-icons/