简体   繁体   中英

OpenLayers save a feature

I'm creating a line which can be edited using this code:

    var line_points = Array();
    var lineLayer = new OpenLayers.Layer.Vector(label);
    this.map.addLayer(lineLayer);
    this.map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));

    for ( x in points ) {
        var point = points[x].split(',');
        var lat = parseFloat( point[0] );
        var lon = parseFloat( point[1] );
        line_points[x] = new OpenLayers.Geometry.Point(this.Lon2Merc(lon), this.Lat2Merc(lat));
    }

    var line = new OpenLayers.Geometry.LineString(line_points);
    var lineFeature = new OpenLayers.Feature.Vector(line, null, style);

    lineLayer.addFeatures([lineFeature]);

I'm trying to pull the latitudes and longitudes out of this feature whenever a point is moved or created to update a HTML form which is then used to save that data. I've heard about the protocols and stuff, but don't think that's the right thing for me.

Could someone point me in the right direction please?

EDIT: I've tried getting the details from the HTML directly:

    var x = 0;
    var y = 0;
    $.each(document.getElementById("OpenLayers.Geometry.LineString_195").getAttribute("points").split(','), function(index, value) {
        if(index%2){
            y = value;
            console.log(MercatorToLatLon(x,y).Lat + "," + MercatorToLatLon(x,y).Lon);
        } else {
            x = value;
        }
        //console.log(value);
    });

but this doesn't seem to give any useful values, and in no particular order which I find strange.

You can use the getVertices operation to retrieve all the latest latitudes and longitudes of the points in the feature.

So call the following whenever you want to update your html.

console.log(lineFeature.geometry.getVertices());

Update per comment:

function report(event) {
    console.log(event.feature.geometry.getVertices());
    console.log(event.type, event.feature ? event.feature.id : event.components);
}
lineLayer.events.on({
    "beforefeaturemodified": report,
    "featuremodified": report,
    "afterfeaturemodified": report,
    "vertexmodified": report,
    "sketchmodified": report,
    "sketchstarted": report,
    "sketchcomplete": report
});

Accessing geometry values directly from dom is probably not the best idea. Better and easier to use OpenLayers API.

You can subscribe to layer's featuremodified event and then access modified feature:

lineLayer.events.on({"featuremodified": function(feature){
    console.log(feature.geometry.getVertices());
}});

You can listen to other events too, for instance "featureadded", "featureremoved", etc.

Hope you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM