ember-leaflet - 使用缩放初始化地图以适合所有图钉

ember-leaflet - initialize map with zoom to fit all pins

我在一个新项目中使用 ember-leaflet,我有一个组件,其中包含一张地图,上面有几个标记,名为 embedded-map。我正在按照他们页面上的教程进行操作,可以为我的地图设置静态 zoom 值。

我看到传单 javascript 库中有某种 fitBounds 函数可用。有没有办法在使用 ember-leaflet 时访问它?我的文档搜索结果很短,但我确实找到了一个看起来相关但不完全是我要找的模板助手:https://miguelcobain.github.io/ember-leaflet/docs/helpers/lat-lng-bounds.

嵌入式-map.js

import Component from "@ember/component";
import { computed } from "@ember/object";
import { readOnly } from "@ember/object/computed";

export default Component.extend({
  tagName: "",
  zoom: 10.25, /* I'd like this to initialize to fit all map markers */

  lat: readOnly("trip.averageLatitude"), /* `trip` is a model passed into the component */
  lng: readOnly("trip.averageLongitude"),

  location: computed("trip.averageLatitude", "trip.averageLongitude", function() {
    return [this.get("averageLatitude"), this.get("averageLongitude")];
  }),
});

嵌入式-map.hbs

{{#leaflet-map lat=lat lng=lng zoom=zoom as |layers|}}
  {{layers.tile url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"}}

  {{#each trip.days as |day|}}
    {{#each day.dayItems as |item|}}
      {{#layers.marker location=item.coordinates as |marker|}}
        {{#marker.popup}}
          <h3>{{item.name}}</h3>
        {{/marker.popup}}
      {{/layers.marker}}
    {{/each}}
  {{/each}}
{{/leaflet-map}}

我对最新的 api 不是很熟悉,但是当我在 2017 年底/2018 年初的项目中使用 ember-leaflet 时,我至少确定了这个用例的两个选项。您选择哪个取决于您的用例和您的考虑 "proper"。

您可以利用 ember-map 组件的 onLoad 操作

{{#leaflet-map onLoad=(action "showAllPins") }}

并在操作中处理边界设置逻辑

showAllPins(map){
  let mapTarget = map.target;
  let disableDrag = this.disableDrag;
  // you *can* do totally store the map for later use if you want but... the
  // addon author is trying to help you avoid accessing leaflet functions directly
  this.set('map', mapTarget);

  /* determine min/max lat and lng */

  //set the bounds
  mapTarget.fitBounds([[lowestLatitude, lowestLongitude], [highestLatitude, highestLongitude]]);
}

或者您可以通过扩展 LeafletMap 来使用继承,并拥有您自己的自定义版本的传单地图,以特定于域的方式处理缩放设置(扩展此 class 允许您 override/enhance 可以访问底层传单对象的现有方法)。

我找到了问题的解决方案,这要归功于我在执行上述 @mistahenry 的解决方案时在控制台中看到的一条错误消息。

本教程建议您将 latlngzoom 参数传递到 leaflet-map 声明中,但错误消息指出您还可以传递 bounds 而不是上面的 3 个,你不知道吗 - 它正是我想要做的!

我使用手头的所有地图标记计算最大和最小纬度和经度,并将其传递到 embedded-map 组件以以适合所有标记的方式呈现地图 on-screen.