【问题标题】:How to add marker to leaflet map in Angular component如何在Angular组件中向传单地图添加标记
【发布时间】:2019-03-17 20:07:55
【问题描述】:

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

【问题讨论】:

  • 他们确实保持他们的位置 - 查看标记图像的左上角在相应点的位置。

标签: angular leaflet gis


【解决方案1】:

您必须指定图标大小和锚点位置,类似这样:

  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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多