Saving and restoring geometries in OpenLayers Saving and restoring geometries in OpenLayers json json

Saving and restoring geometries in OpenLayers


The Openlayers.Geometry objects’ toString method converts them nicely to WKT (Well-Known Text). If you use a GIS layer on top of your database (like PostGIS for PostGres, SQL Spatial for SQL Server, Spatialite for SQLite, etc.), they should offer functions that enable you to process WKT.

But if you want to convert that WKT to a new Openlayers.Geometry object (in the browser), you can use the fromWKT function:

var point = OpenLayers.Geometry.fromWKT('POINT(-104.74560546875 44.2841796875)');alert(point.toString()); // POINT(-104.74560546875 44.2841796875)

Here, the variable point will now contain a new Openlayers.Geometry object, which has the same properties as the original one you used toString() on.

If you pass an array to the fromWKT function, it will return a GeometryCollection containing all the generated geometries.

var geometryTexts = [      'POINT(-104.74560546875 44.2841796875)'    , 'POLYGON((-96.52783203125 44.6796875,-96.52783203125 45.734375,-92.22119140625 45.734375,-92.22119140625 44.6796875,-96.52783203125 44.6796875))'    , 'LINESTRING(-105.71240234375 44.6796875,-106.06396484375 42.658203125,-103.55908203125 42.7021484375,-103.47119140625 45.55859375,-104.65771484375 45.20703125)'    ],    collection = OpenLayers.Geometry.fromWKT(geometryTexts);

After this, collection.toString() should yield the following:

GEOMETRYCOLLECTION(POINT(-104.74560546875 44.2841796875),POLYGON((-96.52783203125 44.6796875,-96.52783203125 45.734375,-92.22119140625 45.734375,-92.22119140625 44.6796875,-96.52783203125 44.6796875)),LINESTRING(-105.71240234375 44.6796875,-106.06396484375 42.658203125,-103.55908203125 42.7021484375,-103.47119140625 45.55859375,-104.65771484375 45.20703125))


In my other answer, I went with WKT because you mentioned it. I now see that you seem to prefer GeoJSON.

To convert a vector layer or an Openlayers.Geometry object to a GeoJSON string, you should use the OpenLayers.Format.GeoJSON.write function:

var geoJSON = new OpenLayers.Format.GeoJSON(),    geoJSONText = geoJSON.write(geometryObject);

Note that you should be able to pass your object to this function, since (according to documentation) it accepts an OpenLayers.Feature.Vector as well as a OpenLayers.Geometry or an array of features.

Conversely, when you’ve got a GeoJSON string, you can convert that back to an object using the OpenLayers.Format.GeoJSON.read function:

var geometry = geoJSON.read(geoJSONText, 'Geometry');

The second parameter lets you indicate which type of object you’d like returned. Read the docs linked to for more information.

Also, take a look at this demo for a more extensive example. (View the source of the page to see how they’re doing it).