2

I want to edit the attribute's value of certain feature. I have managed to display the feature data from GeoServer layer to browser using OpenLayers. I also have managed to display some feature's attribute and its value using PopUp when the user click certain Point on the map.

enter image description here

Notice the red dot is the feature, the PopUp with 3 words are the values of different attributes. Now I just want to update the attribute's value when I click the red dot again (With additional update button is better).

After surfing the internet following some tutorial like this or this I couldn't integrate the code so well into my program. Those tutorials seem don't have complete code and demo that I can follow properly.

Below is my code, how to use WFS-T to update the attribute value of certain feature? How and where to put the transaction code in my project?

var mymap = new ol.Map({
    target: 'mapid',
    layers: [
          new ol.layer.Tile({
            source: new ol.source.XYZ({
                //Vworld Tile 변경
                url: 'http://xdworld.vworld.kr:8080/2d/Base/201802/{z}/{x}/{y}.png'
            })
          })
    ],
    view: new ol.View({
        projection: 'EPSG:3857',
        center: ol.proj.transform([128.1591, 36.4109], 'EPSG:4326', 'EPSG:3857'),
        zoom: 8,
        minZoom: 6,
        maxZoom: 19
    }),
    logo:false
});

var vectorSource = new ol.source.Vector({
    loader: function (extent, resolution, projection) {
        var url = "http://localhost/geoserver/visualization/ows?service=WFS"
            + "&version=1.1.0&request=GetFeature"
            + "&typeName=visualization:GPR"
            + '&outputFormat=text/javascript'
            + "&format_options=callback:loadFeatures"
            + '&srsname=EPSG:3857';
        $.ajax({ url: url, dataType: 'jsonp', jsonp: false });
    }
});

window.loadFeatures = function (response) {
    vectorSource.addFeatures(new ol.format.GeoJSON().readFeatures(response));
};

var layer = new ol.layer.Vector({
    source: vectorSource,
    visible: true,
    title: 'GPR',
    strategy: ol.loadingstrategy.bbox
    })
})

mymap.addLayer(layer);
dataViewer();  // PopUp Viewer


// PopUp 
function dataViewer() {
    var overlayContainerElement = document.querySelector('.overlay-container');
    var overlayLayer = new ol.Overlay({
        element: overlayContainerElement
    })
    mymap.addOverlay(overlayLayer);

    var overlayFeatureBranch = document.getElementById('feature-branch');
    var overlayFeatureRoute = document.getElementById('feature-route');
    var overlayFeatureMilestone = document.getElementById('feature-milestone');

    // Mouse Click Function
    mymap.on('click', function (e) {  
        overlayLayer.setPosition(undefined); // clear the printed information
        mymap.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
            let clickedCoord = e.coordinate;

            let featureBranch = feature.get('지사');     // attribute to display
            let featureRoute = feature.get('노선');      // attribute to display
            let featureMilestone = feature.get('이정');  // attribute to display

            overlayLayer.setPosition(clickedCoord);
            overlayFeatureBranch.innerHTML = featureBranch;
            overlayFeatureRoute.innerHTML = featureRoute;
            overlayFeatureMilestone.innerHTML = featureMilestone;
        })
    })
}

UPDATE

I added this code after the pop-up function. I applied WFS-Transaction to edit the attribute routeCode's value whenever I click the feature point on the map.

var formatWFS = new ol.format.WFS();
    var formatGML = new ol.format.GML({
        featureNS: 'http://localhost/geoserver/visualization',
        featureType: 'GPR',
        srsName: 'EPSG:3857'
    });
    var dirty = {};

    var transactWFS = function (p, f) {
        var node;
        switch (p) {
            case 'insert':
                node = formatWFS.writeTransaction([f], null, null, formatGML);
                break;
            case 'update':
                node = formatWFS.writeTransaction(null, [f], null, formatGML);
                break;
            case 'delete':
                node = formatWFS.writeTransaction(null, null, [f], formatGML);
                break;
        }
        var s = new XMLSerializer();
        var str = s.serializeToString(node);
        console.log(str); 
        $.ajax('http://localhost/geoserver/visualization/ows', {
            type: 'POST',
            dataType: 'xml',
            processData: false,
            contentType: 'text/xml',
            data: str
        }).done();
    }

    mymap.removeInteraction(interaction);
    mymap.removeInteraction(select);

    select = new ol.interaction.Select();
    mymap.addInteraction(select);

    dirty = {};
    select.getFeatures().on('add', function (e) {
        e.element.on('change', function (e) {
            dirty[e.target.getId()] = true;
        });
    });
    select.getFeatures().on('remove', function (e) {
        f = e.element;
        if (dirty[f.getId()]) {
            delete dirty[f.getId()];
            featureProperties = f.getProperties();
            delete featureProperties.boundedBy;
            var clone = new ol.Feature(featureProperties);
            clone.setId(f.getId());
            clone.set('routeCode', 'testCode');  // I want to change the value of attribute routeCode
            transactWFS('update', clone);
        }
    });

If print the transaction data, the browser will give me this XML. Looking at the XML on the browser, the updated value has been sent. But if I open the GeoServer Layer (GML for example) or reload the page, it is not updated at all.

<Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"><Update typeName="feature:GPR" xmlns:feature="http://localhost/geoserver/visualization"><Property><Name>geometry</Name><Value><Point xmlns="http://www.opengis.net/gml" srsName="EPSG:3857"><pos srsDimension="2">14361817.21281217 4530084.76632542</pos></Point></Value></Property><Property><Name>본부</Name><Value>강원본부</Value></Property><Property><Name>지사</Name><Value>강릉지사</Value></Property><Property><Name>교량명</Name><Value>산성우1교(삼척)</Value></Property><Property><Name>교량마스터내교량명</Name><Value>산성우1교(삼척)</Value></Property><Property><Name>노선</Name><Value>동해선</Value></Property><Property><Name>routeCode</Name><Value>testCode</Value></Property><Property><Name>시점명</Name><Value>남삼척</Value></Property><Property><Name>종점명</Name><Value>속초</Value></Property><Property><Name>방향</Name><Value>삼척</Value></Property><Property><Name>이정</Name><Value>37</Value></Property><Property><Name>이정방향</Name><Value>1</Value></Property><Property><Name>gisid</Name><Value>6501037000037100</Value></Property><Property><Name>시점km</Name><Value>37</Value></Property><Property><Name>종점km</Name><Value>37.1</Value></Property><Property><Name>아스팔트포장두께설계기준cm</Name><Value>5</Value></Property><Property><Name>아스팔트포장두께평균cm</Name><Value>6.76</Value></Property><Property><Name>상부철근피복두께설계기준cm</Name><Value>4</Value></Property><Property><Name>상부철근피복두께평균cm</Name><Value>6.8</Value></Property><Property><Name>바닥판손상손상면적m2</Name><Value>18.75</Value></Property><Property><Name>바닥판손상손상율</Name><Value>0.91</Value></Property><Property><Name>바닥판손상상태등급</Name><Value>b</Value></Property><Property><Name>셀병합</Name></Property><Property><Name>연장m</Name><Value>230</Value></Property><Property><Name>조사차로</Name><Value>3</Value></Property><Property><Name>조사면적m2</Name><Value>2070</Value></Property><Property><Name>lon</Name><Value>129.0143991</Value></Property><Property><Name>lat</Name><Value>37.64989266</Value></Property><Property><Name>branchCode</Name><Value>N01821</Value></Property><Filter xmlns="http://www.opengis.net/ogc"><FeatureId fid="GPR.44"/></Filter></Update></Transaction>
  • Welcome to GIS SE! We're a little different from other sites; this isn't a discussion forum but a Q&A site. Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that. Please check out our short tour for more about how the site works. – Ian Turton Feb 21 at 10:01
  • @IanTurton I described my problem, i failed to integrate the WFS-T code in the tutorial into my project – gameon67 Feb 21 at 10:04
  • where exactly are you stuck? what exactly did not work? what did happen? what is sent to the server? what does the server send back? can you produce a minimal viable example for us to look at? – Ian Turton Feb 21 at 10:05
  • @IanTurton Hi I have updated my question, any help would be appreciated – gameon67 Feb 26 at 2:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.