0

In other Q&As on the site, @QuentinN helped me to delete the added lines when the user clicks on the map.

They are partially erased and the rest stays there and I don't know why ... The name of the layer is "line" and also on "line" it tries to delete it.

Can you help me to do this?

var array_coordinates = feature.getGeometry().getCoordinates();
map.getLayers().forEach(layer => {
    if (layer && layer.get('name') == 'line') {
        console.log(layer);
        map.removeLayer(layer);
    }
});
for (var o = 0; o < array_coordinates[0].length - 1; o++) {
    var point = array_coordinates[0][o];


    PointA = array_coordinates[0][o];
    PointB = array_coordinates[0][o + 1];

    var coordinates = [PointA, PointB];
    var line = new ol.geom.LineString(coordinates);
    dist = line.getLength();


    var line_stile = new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'black'
        }),
        stroke: new ol.style.Stroke({
            color: 'blue',
            width: 10
        }),
        text: new ol.style.Text({
            font: 'bold 19px "Open Sans", "Arial Unicode MS", "sans-serif"',
            placement: 'line',
            fill: new ol.style.Fill({
                color: 'white',
                width: 42
            })
        })
    });

    var layerLines = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [new ol.Feature({
                geometry: new ol.geom.LineString(coordinates)
            })]
        }),
        name: 'line',
    });

    dist = dist.toFixed(2);
    var data = dist + " m";


    line_stile.getText().setText(data);
    layerLines.setStyle(line_stile);

    map.addLayer(layerLines);



}

enter image description here

When clicking on the polygon I use the method:

map.on('click', function(event) {
    console.log("CLICK POP-UP HARTA");
    var extent = ol.extent.createEmpty();
    map.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
        console.log(feature);

        var array_coordinates = feature.getGeometry().getCoordinates();

        [....]
    })
})

And this means that when you click on the map the basic design and polygons are already loaded by a function when the map is loaded.

Plus, after selecting the polygon on the map, I pick up a pop-up with information about the polygon in the database ...

My information in the database comes from GeoServer. I am very new to this.

This is my function prepare layer:

function search_teren(vectorSource, map, color) {
    //console.log("MERGE FUNCTIA");

    proj4.defs('EPSG:31700', '+proj=sterea +lat_0=46 +lon_0=25 +k=0.99975 +x_0=500000 +y_0=500000 +ellps=krass +towgs84=28,-121,-77,0,0,0,0 +units=m +no_defs');
    ol.proj.proj4.register(proj4);


    var id_primarie = < ? php echo $_SESSION['user']['data']['id_primarie']; ? > ;
    var mod = "";

    if (id_primarie == 0) {
        mod = 0;
    } else {
        mod = 1;
    }

    $.ajax({
        type: "GET",
        url: "server_harta_teren.php?get_data=1&mod=" + mod + "&id_primarie=" + id_primarie,
        dataType: 'json',
        success: function(response) {

            var polygonsSource = new ol.source.Vector({
                features: new ol.format.GeoJSON().readFeatures(response, {
                    dataProjection: 'EPSG:31700',
                    featureProjection: 'EPSG:3857'
                }),
                format: new ol.format.GeoJSON()
            });
            var vectors = new ol.layer.Vector({
                source: polygonsSource,
                style: styleFunction
            });
            map.addLayer(vectors);

            var selectedFeature = null;



            var features = new ol.format.GeoJSON().readFeatures(response);
            var extent = ol.extent.createEmpty();
            var found_extent = 0;

            //console.log(response);  
            //console.log(color.color_imobile);   

            features.forEach(function(feature) {
                feature.setId(undefined);
                feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
                //ol.extent.extend(extent, feature.getGeometry().getExtent());



                var teren_stile = new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: color.color_imobile
                    }),
                    stroke: new ol.style.Stroke({
                        color: [0, 0, 230],
                        width: 1
                    }),
                    text: new ol.style.Text({
                        font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"',
                        placement: 'center',
                        //overflow: true,
                        fill: new ol.style.Fill({
                            color: color.color_eticheta
                        })
                    })
                });

                var selected_stile = new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: color.color_selected
                    }),
                    stroke: new ol.style.Stroke({
                        color: color.color_selected,
                        width: 3
                    }),
                    text: new ol.style.Text({
                        font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"',
                        placement: 'center',
                        fill: new ol.style.Fill({
                            color: color.color_eticheta,
                            width: 23
                        })
                    })
                });

                //same id_pdf
                var id_pdf = "";


                var data = "";

                if ($('#etc_tarla').is(":checked")) {
                    data = "T:" + feature.get('tarla') + "  ";
                }
                if ($('#etc_parcela').is(":checked")) {
                    data = data + "P:" + feature.get('parcela') + "  ";
                }
                if ($('#etc_suprafata').is(":checked")) {
                    data = data + "S:" + feature.get('suprafata') + "  MP.";
                }
                if ($('#etc_proprietari').is(":checked")) {
                    data = data + "P:" + feature.get('proprietari') + "  ";
                }
                if ($('#etc_eterra').is(":checked")) {
                    data = data + "C.F.:" + feature.get('e_terra') + "  ";
                }

                //var data = data+"P:"+feature.get('parcela')+"/S:"+feature.get('suprafata')+" MP.Proprietari: "+feature.get('proprietari')+"/E_TERRA:"+feature.get('e_terra');
                //var teren = feature.get('id_teren');
                //console.log(data);


                if (feature.get('layer') == "TEREN") {
                    teren_stile.getText().setText(data);
                    feature.setStyle(teren_stile);
                }



                //console.log(feature.get('text'));

                if (feature.get('text') == id_pdf) {
                    //console.log("merge");
                    $.ajax({
                        type: "GET",
                        url: "server_harta_ser.php?get_parcel_info=1&id_pdf=" + id_pdf,
                        dataType: 'json',
                        success: function(response) {
                            //console.log(response);

                            //var data = "T:"+response.tarla+"/P:"+response.parcela+"/S:"+response.suprafata+" MP.";

                            selected_stile.getText().setText(data);
                            feature.setStyle(selected_stile);

                        }
                    });

                    ol.extent.extend(extent, feature.getGeometry().getExtent());
                    found_extent = 1;

                }

            });

            if (found_extent == 0) {
                features.forEach(function(feature) {
                    //feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
                    ol.extent.extend(extent, feature.getGeometry().getExtent());
                });
            }

            vectorSource.teren.clear();
            vectorSource.teren.addFeatures(features);
            //console.log("features:");
            //console.log(features);
            //map.getView().fit(extent);



        }
    });

And this is my click event function:

//click pe harta pop_up
map.on('clicky', function(event) {
    console.log("CLICK POP-UP HARTA");
    var extent = ol.extent.createEmpty();

    var found = false;
    map.forEachFeatureAtPixel(event.pixel, function(features, layer) {
        var isSelected = !features.get('isSelected');
        features.set('isSelected', isSelected);
        if (selectedFeature && (selectedFeature != features)) {
            selectedFeature.set('isSelected', false);
        }
        selectedFeature = (isSelected) ? features : null;
        found = true;
    })
    if (!found && selectedFeature) {
        selectedFeature.set('isSelected', false);
        selectedFeature = null;
    }



    map.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
        console.log(feature);
        var id_selected_current = feature.get('text');
        console.log("---------------->" + id_selected_current);




        /*
          for(var o = 0; o < array_coordinates[0].length - 1; o++){
                                                              var point  = array_coordinates[0][o];
                                                              
                                                              
                                                              PointA = array_coordinates[0][o];
                                                              PointB = array_coordinates[0][o + 1];
                                                              
                                                              var coordinates = [PointA, PointB];
                                                              var line = new ol.geom.LineString(coordinates);
                                                              dist = line.getLength();
                                                              
                                                              
                                                              var line_stile = new ol.style.Style({
                                                                     fill: new ol.style.Fill({color: 'black'}),
                                                                     stroke: new ol.style.Stroke({
                                                                       color: 'blue', width: 10
                                                                     }),
                                                                   text: new ol.style.Text({
                                                                     font: 'bold 19px "Open Sans", "Arial Unicode MS", "sans-serif"',
                                                                     placement: 'line',
                                                                     fill: new ol.style.Fill({
                                                                       color: 'white', width: 42
                                                                     })
                                                                   })
                                                                 });
                                                              
                                                                 var layerLines = new ol.layer.Vector({
                                                                     source: new ol.source.Vector({
                                                                         features: [new ol.Feature({ geometry: new ol.geom.LineString(coordinates)})]
                                                                     }),
                                                                     name : 'line',
                                                                 });
                                                             
                                                                 dist = dist.toFixed(2);
                                                                 var data = dist + " m";
                                                             
                                                             
                                                                 line_stile.getText().setText(data);
                                                                 layerLines.setStyle(line_stile);
                                                             
                                                                 map.addLayer(layerLines);
                                                               
                                                              
                                                              
                                                        }
         */




        var selected_stile = new ol.style.Style({
            fill: new ol.style.Fill({
                color: makePattern_click_select_map()
            }),
            stroke: new ol.style.Stroke({
                color: [102, 255, 51],
                width: 1
            }),
            text: new ol.style.Text({
                font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"',
                placement: 'center',
                fill: new ol.style.Fill({
                    color: 'white',
                    width: 23
                })
            })
        });




        var data = "";
        if ($('#etc_tarla').is(":checked")) {
            data = "T:" + feature.get('tarla') + "  ";
        }
        if ($('#etc_parcela').is(":checked")) {
            data = data + "P:" + feature.get('parcela') + "  ";
        }
        if ($('#etc_suprafata').is(":checked")) {
            data = data + "S:" + feature.get('suprafata') + "MP.  ";
        }
        if ($('#etc_proprietari').is(":checked")) {
            data = data + "P:" + feature.get('proprietari') + "  ";
        }
        if ($('#etc_eterra').is(":checked")) {
            data = data + "C.F.:" + feature.get('e_terra') + "  ";
        }

        selected_stile.getText().setText(data);
        feature.setStyle(selected_stile);
        ol.extent.extend(extent, feature.getGeometry().getExtent());



        if (feature.get('layer') == "TEREN") {

            var proprietar_tmp = feature.get('proprietari').split('--');
            var crt_proprietar = '<table class="table">';
            if (proprietar_tmp.length > 0) {
                var addit = '';
                for (i = 0; i < proprietar_tmp.length; i++) {
                    if (proprietar_tmp[i].length > 2) {
                        var no = i + 1;
                        crt_proprietar += "<tr><td>" + no + "</td><td><b>" + proprietar_tmp[i] + "</b></td></tr>";
                    }
                }
            }
            crt_proprietar += "</table>";




            //console.log(txt_dist); 


            featureStr = "<h4>Detalii Imobil: </h4>" +
                "<hr />" +
                "<b>" + "Tarla: " + feature.get('tarla') + "</b>" +
                "<br/>" + "<b>" + "Parcela: " + feature.get('parcela') + "</b>" +
                "<br/>" + "<b>" + "Suprafa&#355&#259;: " + ((feature.get('suprafata') != "") ? (feature.get('suprafata') + " MP") : '') + "</b>" +
                "<br/>" + "<b>" + "Identificator CF: " + feature.get('e_terra') + "</b>" +
                "<br/><br />" + "<b>" + "Proprietari: " + crt_proprietar + "</b>"

                +
                "<table class='table' style='font-size: 60%'>" +
                "" + "<tr><td><a href='edit_pdf.php?id=" + feature.get('text') + "' target='blank_" + feature.get('tarla') + "' ref='noopener noreferrer'>" + "<button class='btn btn-success' style='color: white;'>Adaug&#259; Informa&#355;ii" + "</a></td>" +
                "" + "<td><button class='btn btn-success' onclick='descarca_single_teren(" + feature.get('text') + ")'>Descarc&#259; KML</td></tr>" +
                "</table>";
        } else if (feature.get('layer') == "CONSTRUCTIE") {
            featureStr = "<h4>Detalii Construc&#355;ie: </h4>" +
                "<hr />" +
                "<b>" + "Numar Construc&#355;ie: " + feature.get('numar_const') + "</b>" +
                "<br /><b>Folosin&#355;&#259; Construc&#355;ie: " + feature.get('folosinta') + "</b>" +
                "<br /><b>Suprafa&#355;&#259;: " + feature.get('suprafata') + " MP.</b>" +
                "<br />" +
                "<table class='table' style='font-size: 60%'>" +
                "<tr><td><a href='edit_pdf.php?id=" + feature.get('id') + "' target='blank_'>" + "<button class='btn btn-success' style='color: white;'>Adauga Informa&#355;ii" + "</a></td>" +
                "</table>";
        } else {
            featureStr = "<h4>IN LUCRU... </h4>";
        }




        content.innerHTML = featureStr;
        overlay.setPosition(getCenterOfExtent(extent));

        $.ajax({
            type: "post",
            url: "ser_edit_pdf.php",
            data: {
                get_setari_harta_mica: 1
            },
            dataType: "json",
            success: function(data) {

                var color = data;

                if ($('#mod_cautare1').is(":checked")) {


                    imobile.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: color.color_imobile
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_eticheta
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style, featuree);
                        }



                    });


                    constructii.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: color.color_constructii
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_const
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style, featuree);
                        }



                    });


                    search.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style_selected = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: makePattern()
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_eticheta
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style_selected, featuree);

                        }



                    });


                }


                if ($('#mod_cautare2').is(":checked") || $('#imobile_non_cadgen').is(":checked")) {


                    imobile_non_cadgen.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: color.color_imobile_ancpi
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_eticheta
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style, featuree);
                        }



                    });


                    constructii_non_cadgen.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: color.color_constructii_ancpi
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_const
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style, featuree);
                        }



                    });




                    search_non_cadgen.getSource().forEachFeature(function(featuree) {
                        //feature.setId(feature.get('text'));
                        //console.log(feature.getProperties());
                        //console.log(feature.layer);


                        var style_selected = new ol.style.Style({
                            fill: new ol.style.Fill({
                                color: makePattern()
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0, 0, 230],
                                width: 1
                            }),
                            text: new ol.style.Text({
                                font: '15px Calibri,sans-serif',
                                fill: new ol.style.Fill({
                                    color: color.color_eticheta
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#fff',
                                    width: 1
                                })
                            })
                        });


                        if (id_selected_current != featuree.get('text')) {
                            label_teren_setup(style_selected, featuree);

                        }



                    });




                }

            }

        })


    });

    map.getView().fit(extent, {
        size: map.getSize()
    });

});
1

1 Answer 1

2

Without trying to find out where the problem with deleting layers is, I propose a different strategy of styling your selected polygon, by combination of custom style function and custom feature property. Logic is as follows:

  • Custom feature property isSelected (set by feature.set('isSelected, true)) is used to turn selected style on or off.
  • Custom style function returns either default style or selected style, depending on value of isSelected property.
  • In custom style function selected style is created using measured lines as geometries. Selected style is created only once and saved for later use in custom feature property selectedStyle.

Code could then look something like this (works for polygon features, for other types it should be modified):

var defaultStyle = new ol.layer.Vector().getStyleFunction()();

function styleFunction(feature, resolution) {
  if (!feature.get('isSelected')) return(defaultStyle);
  
  var selectedStyle = feature.get('selectedStyle');
  if (selectedStyle) return(selectedStyle);
  
  var point, PointA, PointB, coordinates, line, dist, data, line_stile;
  var style = [defaultStyle[0]];
  var array_coordinates = feature.getGeometry().getCoordinates();
  for (var o = 0; o < array_coordinates[0].length - 1; o++) {
    point = array_coordinates[0][o];     
    PointA = array_coordinates[0][o];
    PointB = array_coordinates[0][o + 1];
    coordinates = [PointA, PointB];
    line = new ol.geom.LineString(coordinates);
    dist = line.getLength();
    line_stile = new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'black'
      }),
      stroke: new ol.style.Stroke({
        color: 'blue',
        width: 10
      }),
      text: new ol.style.Text({
        font: 'bold 19px "Open Sans", "Arial Unicode MS", "sans-serif"',
        placement: 'line',
        fill: new ol.style.Fill({
          color: 'white',
          width: 42
        })
      }),
      geometry: line
    });
    dist = dist.toFixed(2);
    data = dist + " m";
    line_stile.getText().setText(data);
    style.push(line_stile);
  }
  feature.set('selectedStyle', style);
  return(style);
}

var polygonsSource = new ol.source.Vector({
    url: sourceDataUrl,
    format: new ol.format.GeoJSON(),
});
var vectors = new ol.layer.Vector({
  source: polygonsSource,
  style: styleFunction
});
map.addLayer(vectors);

Now all you have to do to show desired feature/polygon as selected is to set:

feature.set('isSelected', true);

and to return it to default style:

feature.set('isSelected', false);

Here is working JSFiddle: https://jsfiddle.net/TomazicM/wtmv6r83/. Clicking on polygon selects it, clicking on selected polygon unselects it, clicking outside polygons unselects currently selected polygon.

2
  • I implemented the code from @TomazicM but it doesn't work for me when I click on the polygon it marks it pops up but it doesn't mark the sides and it doesn't write their size :( I'm very early and I honestly have no idea what else I could do with him, can you please implement your solution in my code? Thank you very much, I'm very early and I just don't realize what I'm doing wrong here ..... I edited the question with the two functions I use. Thank you from the bottom of my heart Commented Mar 15, 2021 at 7:19
  • JSFiddle example is the most I can do for you. If you understand it, you'll have no problems implementing it. If you don't understand it, take your time to understand it.
    – TomazicM
    Commented Mar 15, 2021 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.