alexvap19
@alexvap19
начинающий фронтендер

Как получить данные маркеров, которые находятся в области видимости карты (vue-yandex-map)?

<template>
  <yandex-map
    :coords="coords"
    :zoom="zoom"
    :controls="controls"
    ref="map"
    @map-was-initialized="mapLoaded"
    @boundschange="mapChange"
    @sizechange="mapChange"
    :cluster-callbacks="{ '1': { click: getDataPoint } }"
    :cluster-options="{
      1: {
        clusterDisableClickZoom: false,
        hasBalloon: false,
        clusterLayout: [
          '<div class=cluster-icon>{{ properties.geoObjects.length }}</div>',
        ].join(''),
      },
    }"
  >
    <ymap-marker
      v-for="office in allOffices"
      :coords="office.coords"
      marker-id="office.id"
      cluster-name="1"
      @balloonopen="bindListener(office.id, office)"
      :key="office.id"
      @balloonclose="unbindListener"
      :balloon-template="`<div class='balloon'>
      <div class = 'balloon__address'>${office.fullAddress}</div>
      <div class = 'balloon__address'>${office.timetable}</div>
      <div class = 'balloon__date'>${office.date}</div>
       <div class = 'balloon__cost'>${office.cost}</div>
       <button class = 'btn btn_transparent' id ='baloon__btn${office.id}' data-id = ${office.id}>Забрать здесь</button>
        </div>
      `"
    />
  </yandex-map>
</template>

<script>
import { yandexMap, ymapMarker, loadYmap } from "vue-yandex-maps";
import { useDeliveryStore } from "@/store/deliveryStore.js";

export default {
  name: "BasketMap",
  props: ["allOffices"],
  data: () => ({
    coords: [58, 52],
    controls: ["zoomControl"],
    zoom: 4,
    settings: {
      apiKey: "",
      lang: "ru_RU",
      coordorder: "latlong",
      enterprise: false,
      version: "2.1",
    },
    currentOffice: null,
  }),
  components: {
    yandexMap,
    ymapMarker,
  },
  computed: {},
  setup() {
    const delivery = useDeliveryStore();
    function selectHandler(target) {
      delivery.setSelectedOffice(target);
    }
    function setMap(target) {
      delivery.setMapLink(target);
    }
    return {
      selectHandler,
      setMap,
    };
  },
  methods: {
    unbindListener(id) {
      const target = document.getElementById(`baloon__btn${id}`);
      if (target) {
        target.myParams = null;
        target.getElementById(`baloon__btn${id}`);
        target.removeEventListener("click", this.someHandler);
      }
    },
    bindListener(id, office) {
      const target = document.getElementById(`baloon__btn${id}`);
      target.myParams = office;
      console.log("BINDLISTENER");
      target?.addEventListener("click", this.someHandler);
    },
    mapLoaded(e) {
      console.log("MAPLOADED");
      this.myMap = e;
      console.log(this.$refs);
      this.setMap(this.$refs);
    },
    mapChange(e) {
      console.log(e);
      console.log(yandexMap);
    },
    someHandler: function (e) {
      this.selectHandler(e.target.myParams);
      this.myMap.balloon.close();
    },
  },
};
</script>
  • Вопрос задан
  • 615 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега Яндекс.Карты
Подписаться на события инициализации карты и изменения её границ. Получить границы видимой области карты. Перебрать массив данных, на основе которых создаются маркеры, проверяя, как координаты маркеров соотносятся с границами видимой области. Как-то так:

<yandex-map
  ref="map"
  @map-was-initialized="onBoundsChange"
  @boundschange="onBoundsChange"
  ...
>
  <ymap-marker
    v-for="n in markersData"
    ...
  >

methods: {
  onBoundsChange() {
    const bounds = this.$refs.map.myMap.getBounds();
    this.markersData.forEach(n => {
      if (
        bounds[0][0] < n.coords[0] && n.coords[0] < bounds[1][0] &&
        bounds[0][1] < n.coords[1] && n.coords[1] < bounds[1][1]
      ) {
        // ...
      }
    });
  },
  ...
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы