Задать вопрос
Ответы пользователя по тегу JavaScript
  • Почему catch в промисе axios выполняется всегда?

    Edheldor
    @Edheldor
    А как у вас на вход функций что-то поступает?

    Если так:
    axios
          .post(options.url, options.sendata)
          .then(procResponce(response))
          .catch(procError(error))
          .finally(procFinal());

    Тогда все выполняется в момент создания промиса.

    Вам нужно что-то в таком стиле
    axios
            .post(options.url, options.sendata)
            .then((response) => {
              procResponce(response)
            })
            .catch((error) => {
              procError(error)
            })
            .finally(() => {
              procFinal()
            })
      },


    Или в таком, если никакие аргументы в функции передавать не нужно
    axios
            .post(options.url, options.sendata)
            .then(() => {
              procResponce()
            })
            .catch(() => {
              procError()
            })
            .finally(() => {
              procFinal()
            })
      },
    Ответ написан
    Комментировать
  • Как запретить сохранение полигона, если полигон пересекается с ранее созданными?

    Edheldor
    @Edheldor Автор вопроса
    Нашел решение, если кому интересно:
    Нужно прослушивать события draw:edited и draw:created из leaflet.draw. Сравнение же полигонов с помощью turf js.

    Как-то так:
    this.map.on('draw:created', (e) => {
        const layer = e.layer;
        // проверяем есть ли какие-то существующие слои
        if (this.zonesLayers['_layers'] && Object.keys(this.zonesLayers['_layers']).length) {
            // проверяем пересекается ли этот созданный слой со всеми уже существующими слоями 
            for (const existingZoneLayerKey in this.zonesLayers['_layers']) {
                const existingZoneLayer = this.zonesLayers['_layers'][existingZoneLayerKey];
                if (this.intersectionPolygonLayersCheck(layer, existingZoneLayer)) {
                    // пересечение полигонов!
                    this.showIntersectionErrorWhenZoneCreating = true;
                    return;
                }
            }
        }
       // тут если все ок - сохраняем
    
    });
    
    // при сохранении отредактированного
    this.map.on('draw:edited', (e) => {
                let haveZonesIntersections = false;
                const layers = e.layers;
                //  начинаем проверку на пересечение полигонов 
                layers.eachLayer((layer) => {
                    for (const existingZoneLayerKey in this.zonesLayers['_layers']) {
                        if (this.zonesLayers['_layers'][existingZoneLayerKey] !== layer) {
                            const existingZoneLayer = this.zonesLayers['_layers'][existingZoneLayerKey];
                            if (this.intersectionPolygonLayersCheck(layer, existingZoneLayer)) {
                                // пересечение полигонов!
                                haveZonesIntersections = true;
                                this.showIntersectionErrorWhenZoneCreating = true;
                                return;
                            }
                        }
                    }
                    if (!haveZonesIntersections) {
                        // если нет пересечений сохраняем куда-нибудь
                    }
    
                });
    intersectionPolygonLayersCheck(polygonLayerOne, polygonLayerTwo) {
                    // приводим полигоны к виду, понятному turf js
                    const polygonOne = polygonLayerOne.toGeoJSON();
                    const polygonTwo = polygonLayerTwo.toGeoJSON();
                    // проверяем пересечение с помощью turf js
                    const intersectCheckResult = intersect(polygonOne, polygonTwo);
                    // console.log(intersectCheckResult);
                    if (intersectCheckResult === null) {
                        return false;
                    } else {
                        // если результат пересенчения - полигон или мультиполигон то считаем что пересекаются
                        if (intersectCheckResult.geometry && intersectCheckResult.geometry.type === 'Polygon') {
                            return true;
                        } else if (intersectCheckResult.geometry && intersectCheckResult.geometry.type === ' MultiPolygon') {
                            return true;
                        } else {
                            // а если результат перессечения другой (документация говорит что может быть
                            // Point или MultiPoint или LineString или MultiLineString)
                            // то считаем что нет пересечения
                            return false;
                        }
                    }
                },
    Ответ написан
    Комментировать