OL OSM получает центральную точку заданного c слоя - PullRequest
0 голосов
/ 17 января 2020

Я использую карту OSM Открытого слоя с Angular для просмотра стран, затем штатов и городов соответственно. Я могу повысить уровень в соответствии с выбором и добавив новый слой для каждого. Я не удаляю, а просто скрываю предыдущий слой. Предположим, что если кто-то выберет Нью-Йорк из Соединенных Штатов, тогда слой всех стран будет скрыт, и будет виден верхний слой с городами Нью-Йорк. Теперь мне нужно дать пользователю возможность вернуться к верхнему уровню. Как двойной щелчок по Нью-Йорку отобразит все графства. чтобы сделать это, когда я скрываю текущий слой и показываю предыдущий слой, он отображается правильно, но я не могу получить его центральную точку. Может ли кто-нибудь помочь в этом?

this.map.on('singleclick', (event) => {
    // do foreach for each layer  this.MapLevel is each layer number in map
    this['vectorLayer' + this.MapLevel].getFeatures(event.pixel).then((features) => {
        if (!features.length) {
          selection = {};
          return;
        }
        const feature = features[0];
        if (!feature) {
          return;
        }
 this.MapLevel = this.MapLevel + 1;
        this['vectorLayer' + this.MapLevel] = new VectorLayer({
source: new VectorSource({
          url: this.MapSourceURl, // local json file path to retrive Data
          map: this.map,
          format: new GeoJSON(),
          wrapX: false,
          useSpatialIndex: false,
          overlaps: false 
         })}); // layer parameters not pasting here as it has long
        this.map.addLayer(this['vectorLayer' + this.MapLevel]);
        this['vectorLayer'+ this.MapLevel].setVisible(true);
        this['vectorLayer' + (this.MapLevel - 1)].setVisible(false);
      });
      });


// On double click I am trying to show previous layer to downgrade Level in map

this.map.on('dblclick', (event) => {


     this['vectorLayer' + (this.MapLevel - 1)].setVisible(true);
     this['vectorLayer' + (this.MapLevel - 1)].setOpacity(1);
     this.view.animate({center: toLonLat([this.long, this.lati]), zoom : this.view.getZoom() - 1, duration: 2000});
     this.map.removeLayer(this['vectorLayer' + this.MapLevel]);
     this['vectorLayer'+ this.MapLevel].setVisible(false);
    });

But I am not getting correct zoom level of previous layer this so this code is failing. 

1 Ответ

0 голосов
/ 21 января 2020

Если я вас правильно понимаю, это может сработать,

let updateViewExtent = function (pixel, level) {
  this['vectorLayer' + level].getFeatures(event.pixel).then((features) => {
    if (features.length > 0) {
      return;
    }
    const feature = features[0];
    if (!feature) {
      return;
    }
    // zoom to feature clicked (here just first feature)
    this.map.getView().fit(feature.getGeometry().getExtent(), {size: this.map.getSize()});
}
this.map.on('singleclick', (event) => {
  // if this is the lower level return
  if (this.MapLevel === LOWERLEVEL) {
    return;
  }
  // zoom to the clicked feature of the level
  updateViewExtent(event.pixel, this.MapLevel);
  // update map level and layers visibility
  this['vectorLayer' + this.MapLevel].setVisible(false);
  this.MapLevel += 1;
  this['vectorLayer' + this.MapLevel].setVisible(true);
});
this.map.on('dblclick', (event) => {
  // if this is the upper level return
  if (this.MapLevel === UPPERLEVEL) {
    return;
  }
  // zoom to the clicked feature of the upper level
  updateViewExtent(event.pixel, this.MapLevel - 1);
  // update map level and layers visibility
  this['vectorLayer' + this.MapLevel].setVisible(false);
  this.MapLevel -= 1;
  this['vectorLayer' + this.MapLevel].setVisible(true);
});

Я использую функцию для увеличения масштаба желаемого, в данном случае - нажатую функцию. На самом деле может случиться так, что это больше, чем просто функция, вы можете увеличить масштаб. Если вы действительно хотите увеличить масштаб слоя до двойного щелчка, тогда вместо вызова функции просто используйте это,

// zoom upper layer extent
this.map.getView().fit(
  this['vectorLayer' + (this.MapLevel - 1)].getSource().getExtent(),
  {size: this.map.getSize()}
);

Наконец, вам может потребоваться отменить поведение карты по умолчанию при двойном щелчке (увеличить на одном уровне).

...