AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77119486
Accepted
hansmei
hansmei
Asked: 2023-09-17 04:25:29 +0800 CST2023-09-17 04:25:29 +0800 CST 2023-09-17 04:25:29 +0800 CST

Modificando um MultiPolygon com Openlayers quando dois subpolígonos compartilham lados ou vértices

  • 772

Espero poder modificar um MultiPolygon em Openlayers que consiste em vários subpolígonos. Ativei a interação Modificar padrão e arrastar ambos os vértices e criar novos segmentos de linha ao arrastar a linha funciona bem. No entanto, parece que é inconsistente quando se trata da operação de edição.

O comportamento é muito inconsciente. Para alguns vértices, ele arrastará todos os vértices conectados (comportamento desejado) assim: Comportamento desejado

Para outros locais, ele arrastará apenas alguns, mas não todos os vértices: Mau comportamento

Ele não modificará (sempre, mas às vezes) ambas as subentidades ao arrastar para adicionar novos segmentos: Inserindo novos vértices

Este é o código para reproduzir o comportamento inesperado:

var multiPolygon = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": {
        "id": "1.1"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              1193836.0495014254,
              8383930.129123866
            ],
            [
              1193847.7380479588,
              8383914.044627354
            ],
            [
              1193861.7086440534,
              8383894.250081073
            ],
            [
              1193873.9649199897,
              8383877.232589948
            ],
            [
              1193883.717211206,
              8383863.628916129
            ],
            [
              1193894.5047360454,
              8383944.666907605
            ],
            [
              1193881.5012495161,
              8383963.164657038
            ],
            [
              1193860.4841296545,
              8383947.813224077
            ],
            [
              1193843.674886545,
              8383935.594306091
            ],
            [
              1193836.0495014254,
              8383930.129123866
            ]
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "id": "2.1"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              1193883.717211206,
              8383863.628916128
            ],
            [
              1193889.0153151448,
              8383856.238480768
            ],
            [
              1193890.5403921688,
              8383857.260414857
            ],
            [
              1193909.1752749276,
              8383870.745514915
            ],
            [
              1193929.301838863,
              8383884.8526888145
            ],
            [
              1193934.6451744211,
              8383888.740497403
            ],
            [
              1193929.168255474,
              8383896.316176012
            ],
            [
              1193903.787411573,
              8383931.462094758
            ],
            [
              1193894.5047360454,
              8383944.666907605
            ],
            [
              1193883.717211206,
              8383863.628916128
            ]
          ]
        ]
      }
    }
  ]
}

const styleFunction = () => {
  const style = [
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(0,0,255,0.4)',
        width: 2,
      }),
      fill: new ol.style.Fill({
        color: `rgba(0,0,255,0.2)`,
      }),
    }),
    new ol.style.Style({
      image: new ol.style.Circle({
        radius: 3,
        fill: new ol.style.Fill({
          color: 'rgba(0,0,255,0.4)',
        }),
      }),
      geometry: function(feature) {
        // return the coordinates of the first ring of the polygon
        const type = feature.getGeometry().getType();
        let coordinates;
        if (type === 'Polygon') {
          coordinates = feature.getGeometry().getCoordinates()[0];
        } else if (type === 'MultiPolygon') {
          const coordArray = feature.getGeometry().getCoordinates();
          coordinates = [];
          coordArray.forEach((ring) => {
            coordinates.push(...ring[0]);
          });
        }
        return new ol.geom.MultiPoint(coordinates);
      },
    }),
  ];
  return style;
};

var multiPolygonFeatures = new ol.format.GeoJSON().readFeatures(multiPolygon);
var vectorSource = new ol.source.Vector({
  features: multiPolygonFeatures,
});

var viewCenter = [1193887, 8383870];
var view = new ol.View({
  projection: 'EPSG:3857',
  center: viewCenter,
  zoom: 18,
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: vectorSource,
      style: styleFunction
    })
  ],
  target: 'map',
  view: view,
});


const modify = new ol.interaction.Modify({
  source: vectorSource
});
map.addInteraction(modify);
html,
body,
.map {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.ol-dragbox {
  background-color: rgba(255, 255, 255, 0.4);
  border-color: rgba(100, 150, 0, 1);
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<div id="map" class="map"></div>

openlayers
  • 2 2 respostas
  • 19 Views

2 respostas

  • Voted
  1. hansmei
    2023-09-17T04:54:20+08:002023-09-17T04:54:20+08:00

    Após inspeção detalhada dos dados brutos (os dados do polígono), cheguei à conclusão de que a interação de modificação exige que os vértices do polígono compartilhem exatamente a mesma coordenada (até a décima casa decimal) para acionar a edição compartilhada . Eu acreditava que o encaixe detectaria diferenças tão pequenas. Aparentemente eu estava errado nessa suposição.

    No meu código acima, aqueles vértices que não trabalhavam com edição compartilhada tinham o último dígito diferente.

    Alterando a forma como a fonte (o GeoJSON) é gerada e adicionando alguns arredondamentos a ela, funciona conforme desejado.

    • 0
  2. Best Answer
    MoonE
    2023-09-17T05:08:27+08:002023-09-17T05:08:27+08:00

    Apenas uma das coordenadas correspondia exatamente entre os dois polígonos, a outra diferia no último dígito.

    A interação Modificar atualizará uma coordenada de cada geometria na mesma posição. (Havia um bug nas versões mais antigas do OpenLayers onde múltiplas coordenadas da mesma geometria eram modificadas quando eram iguais. Nesse caso, você pode querer usar a versão mais recente.)

    Aqui está o exemplo atualizado:

    var multiPolygon = {
      "type": "FeatureCollection",
      "features": [{
          "type": "Feature",
          "properties": {
            "id": "1.1"
          },
          "geometry": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  1193836.0495014254,
                  8383930.129123866
                ],
                [
                  1193847.7380479588,
                  8383914.044627354
                ],
                [
                  1193861.7086440534,
                  8383894.250081073
                ],
                [
                  1193873.9649199897,
                  8383877.232589948
                ],
                [
                  1193883.717211206,
                  8383863.628916129
                ],
                [
                  1193894.5047360454,
                  8383944.666907605
                ],
                [
                  1193881.5012495161,
                  8383963.164657038
                ],
                [
                  1193860.4841296545,
                  8383947.813224077
                ],
                [
                  1193843.674886545,
                  8383935.594306091
                ],
                [
                  1193836.0495014254,
                  8383930.129123866
                ]
              ]
            ]
          }
        },
        {
          "type": "Feature",
          "properties": {
            "id": "2.1"
          },
          "geometry": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  1193883.717211206,
                  8383863.628916129
                ],
                [
                  1193889.0153151448,
                  8383856.238480768
                ],
                [
                  1193890.5403921688,
                  8383857.260414857
                ],
                [
                  1193909.1752749276,
                  8383870.745514915
                ],
                [
                  1193929.301838863,
                  8383884.8526888145
                ],
                [
                  1193934.6451744211,
                  8383888.740497403
                ],
                [
                  1193929.168255474,
                  8383896.316176012
                ],
                [
                  1193903.787411573,
                  8383931.462094758
                ],
                [
                  1193894.5047360454,
                  8383944.666907605
                ],
                [
                  1193883.717211206,
                  8383863.628916129
                ]
              ]
            ]
          }
        }
      ]
    }
    
    const styleFunction = () => {
      const style = [
        new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'rgba(0,0,255,0.4)',
            width: 2,
          }),
          fill: new ol.style.Fill({
            color: `rgba(0,0,255,0.2)`,
          }),
        }),
        new ol.style.Style({
          image: new ol.style.Circle({
            radius: 3,
            fill: new ol.style.Fill({
              color: 'rgba(0,0,255,0.4)',
            }),
          }),
          geometry: function(feature) {
            // return the coordinates of the first ring of the polygon
            const type = feature.getGeometry().getType();
            let coordinates;
            if (type === 'Polygon') {
              coordinates = feature.getGeometry().getCoordinates()[0];
            } else if (type === 'MultiPolygon') {
              const coordArray = feature.getGeometry().getCoordinates();
              coordinates = [];
              coordArray.forEach((ring) => {
                coordinates.push(...ring[0]);
              });
            }
            return new ol.geom.MultiPoint(coordinates);
          },
        }),
      ];
      return style;
    };
    
    var multiPolygonFeatures = new ol.format.GeoJSON().readFeatures(multiPolygon);
    var vectorSource = new ol.source.Vector({
      features: multiPolygonFeatures,
    });
    
    var viewCenter = [1193887, 8383870];
    var view = new ol.View({
      projection: 'EPSG:3857',
      center: viewCenter,
      zoom: 18,
    });
    
    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        }),
        new ol.layer.Vector({
          source: vectorSource,
          style: styleFunction
        })
      ],
      target: 'map',
      view: view,
    });
    
    
    const modify = new ol.interaction.Modify({
      source: vectorSource
    });
    map.addInteraction(modify);
    html,
    body,
    .map {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }
    
    .ol-dragbox {
      background-color: rgba(255, 255, 255, 0.4);
      border-color: rgba(100, 150, 0, 1);
    }
    <link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
    <div id="map" class="map"></div>

    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve