首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ngx-leaflet:如何添加自定义控件?

ngx-leaflet:如何添加自定义控件?
EN

Stack Overflow用户
提问于 2019-02-17 22:41:17
回答 1查看 2.4K关注 0票数 3

我已经尝试了一段时间来使用ngx-leaflet实现这个leaflet tutorial

在遵循教程的同时,对于如何实现自定义控件或图例,绝对没有明确的documentation

代码语言:javascript
复制
var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
    this._div.innerHTML = '<h4>US Population Density</h4>' +  (props ?
        '<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
        : 'Hover over a state');
};

info.addTo(map);

创建一个图例也是如此。

有没有人可以给我指出正确的方向,尝试用ngx-leaflet库在Angular 7中实现这一点?

代码语言:javascript
复制
import { control, featureGroup, geoJson, icon, latLng, LatLngExpression, Map, Marker, marker, popup, tileLayer } from 'leaflet';

  onMapReady(map: Map) {
    this.map = map;

    // create info control
    let info = control(
      {
        onAdd: map => {

        }
      }
    )
    info.addTo(map);

我知道你需要做一些像this这样的事情,但我不想添加圆或形状,而是上面屏幕截图中的自定义控件以及图例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-18 00:33:04

要使此示例工作,您需要做的唯一一件事就是侦听onMapReady事件,并将本教程的所有代码放在其中。映射引用是您想要的,它是此函数的一个参数。

具体地说:

代码语言:javascript
复制
<div
  style="height: 100vh"
  leaflet
  [leafletOptions]="options"
  (leafletMapReady)="onMapReady($event)"
></div>

ts:

代码语言:javascript
复制
onMapReady(map) {
 // place all the tutorial code inside here
 ...

// control that shows state info on hover
let info = L.control();

// here you want the reference to be info, therefore this = info
// so do not use es6 to access the the class instance
info.onAdd = function (map) {
  this._div = L.DomUtil.create('div', 'info');
  this.update();
  return this._div;
};

// also here you want the reference to be info, therefore this = info
// so do not use es6 to access the class instance
info.update = function (props) {
  this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
    '<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
    : 'Hover over a state');
};

info.addTo(map);
...
const legend = L.control({ position: 'bottomright' });

legend.onAdd = map => {

  let div = L.DomUtil.create('div', 'info legend'),
    grades = [0, 10, 20, 50, 100, 200, 500, 1000],
    labels = [],
    from, to;

  for (var i = 0; i < grades.length; i++) {
    from = grades[i];
    to = grades[i + 1];

    labels.push(
      '<i style="background:' + getColor(from + 1) + '"></i> ' +
      from + (to ? '&ndash;' + to : '+'));
  }

  div.innerHTML = labels.join('<br>');
  return div;
};

legend.addTo(map);
}

使用ngx- demo查看Angular 7中的完整示例

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54734329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档