[GIS] OpenLayers add a json layer to existing map on load

geojsonopenlayers-2

I am new to OpenLayers … i have managed to build a layer with several features (draw tools, delete and save buttons).

When the user draws shapes on the image map and press Save, these are stored as a json String to filesystem/database.

Since a user desires to see or re-edit his drawing on the image i would like to fetch and re-draw this json String. My code is as follows:

function initialiseMap(){
    var options = {
        controls : [],
        maxExtent : new OpenLayers.Bounds(0.0, -72448.0, 142848.0, 0.0),
        maxResolution : 1024.000000,
        numZoomLevels : 10
    };

    map = new OpenLayers.Map(imageEditorID, options);

    imageLayer = new OpenLayers.Layer.TMS(imgURL, "", {
        url : '',
        serviceVersion : '.',
        layername : '.',
        alpha : true,
        type : 'png',
        getURL : overlay_getTileURL,
        transitionEffect: 'resize'
    });

    map.addLayer(imageLayer);
    var vlayer = new OpenLayers.Layer.Vector("Editable");
    var previousLayer = getJSONData(); //<<<--- HERE I CALL A FUNCTION TO FETCH STORED LAYER
    ....
    .... // create some tools for drawing & then provide save option ....
    ....
    var save = new OpenLayers.Control.Button({
            title: 'Save', text: 'Save',                
            trigger: function(){                        
            var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();        
            var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);                                  
            sendJSONToServer([{name:'param', value:vectorLayerAsJson}]);
            }, 'displayClass': "olControlSaveFeatures"  
    });
    ...
    ...        

and the function i would like to built, fetch json String from an XHTML form:

function getJSONData(data) {
    var htmlstring = document.getElementById("A3702:imageEditor:getJSONData").value;
    .... ///<<<--- How am i going to add this json String as Layer on existing image?

Json String is something like:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[43796,-32494],[43852,-30582],[41940,-30526],[41884,-32438],[43796,-32494]]]}}]}

How am i going to maybee parse (serialize/deserialize) json String and properly add it (like e.g. as GEOJson layer) to the map?

Best Answer

function getJSONData(data) {
    var htmlstring = document.getElementById("A3702:imageEditor:getJSONData").value;
    var format = new OpenLayers.Format.GeoJSON(); //create a format to read/write GeoJSON
    return format.read(htmlstring) ; //parse the GeoJSON to an OpenLayers Feature array

then in your initialiseMap()

var previousFeatures = getJSONData(); //call your function
vlayer.addFeatures(previousFeatures); //add the features to your layer