Как я могу проверить, находится ли маркер внутри определенного круга c - PullRequest
0 голосов
/ 09 февраля 2020

Мне нужна помощь, чтобы проверить, находится ли маркер внутри указанного круга. У меня есть массив кругов, и я должен проверить, находится ли маркер внутри, и получить информацию о целевом круге. Я пытаюсь позвонить на расстоянии. Кто-нибудь может мне помочь?

...
export class PlacesPage {
  map: Map;
  placesList = [];

  ionViewDidEnter() {
    this.map = new Map("mapId2").setView([41.694941, -8.821054], 13);

    tileLayer("http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", {
      attribution: "cityt3ip.com"
    }).addTo(this.map);

    fetch("./assets/data.json")
      .then(res => res.json())
      .then(json => {
        this.placesList = json.places;
        this.leafletMap();
      });
  }

  leafletMap() {
    for (const place of this.placesList) {
      circle([place.latitude, place.longitude], {
        color: "red",
        fillColor: "#f03",
        fillOpacity: 0.5,
        radius: 100
      }).addTo(this.map);
    }

    marker([41.692135, -8.831127], {
      draggable: true,
      autoPan: true
    })
      .addTo(this.map).on('drag', this.masterClick, this);
  }

  masterClick(e: any) {
    console.log(e)
    var d = this.map.distanceTo(e.latlng, circle.getLatLng());
    var isInside = d < circle.getRadius();
    console.log(isInside)
    circle.setStyle({
      fillColor: isInside ? "green" : "#f03"
    });
  }

  ionViewWillLeave() {
    this.map.remove();
  }
}



```

Ответы [ 3 ]

0 голосов
/ 11 февраля 2020

Похоже, вы пытаетесь изменить стиль круга, когда перетаскиваете маркер на круг.

Я сделал скрипку , которая показывает это. Моя стратегия состояла в том, чтобы сохранить текущий круг, когда маркер перемещается по любому из кругов.

function createCircles() {
  circleCoords.forEach(circ => {
    const ll = L.latLng(circ[0], circ[1]);
    let curCirc = L.circle(ll, {
      radius: 100
    }).addTo(map);
    curCirc.on('mouseover', (evt) => {
      myCircle = evt.target;
    })
  })
}

Затем я изменил вашу функцию masterClick следующим образом:

function masterClick(e) {
  var d = e.latlng.distanceTo(myCircle.getLatLng());
  var isInside = d < myCircle.getRadius();
  myCircle.setStyle({
    fillColor: isInside ? "green" : "#f03"
  });
}
0 голосов
/ 12 февраля 2020

Вот мое решение! Спасибо всем!

  async isMarkerInsideCircle() {
    try {
      this.currentLayer = null;

      this.map.eachLayer(layer => {
        if (layer instanceof L.Circle) {
          this.circleCenterLatLng = layer.getLatLng();
          this.circleRadius = layer.getRadius();
          layer.setStyle({
            color: 'red',
            fillColor: '#f03'
          });

          if (
            this.markerLatLng.distanceTo(this.circleCenterLatLng) <=
            this.circleRadius
          ) {
            this.currentLayer = layer;
          } else {
          }
        }
      });
    } catch (e) {
      console.log(e);
    }

    if (this.currentLayer !== null) {
      console.log(this.currentLayer);
      for (const pl of this.places) {
        if (
          pl.latitude == this.currentLayer.getLatLng().lat &&
          pl.longitude == this.currentLayer.getLatLng().lng
        ) {
          console.log(pl.title);

          this.spotVisited = pl.id;
          this.isLoading = true;
        }
      }

      this.currentLayer.setStyle({
        color: 'green',
        fillColor: '#ddd'
      });
    }
  }
0 голосов
/ 09 февраля 2020

В Leaflet нет функции, чтобы определить, находится ли маркер внутри круга. Вместо этого вы можете использовать метод distanceTo, чтобы проверить, находится ли точка в пределах определенного радиуса центра круга, что имеет тот же результат.

isMarkerInsideCircle(markerLatLng, circleCenterLatLng, circleRadius){
    // markerLatLng and circleCenterLatLng must be instance of L.latlng class.
    // you can create an instance like this L.latLng(lat, lng);
    if (markerLatLng.distanceTo(circleCenterLatLng) <= circleRadius){
        return true;
    } else {
        return false;
    }
}
...