Layer KML using Openlayers3

Asked

Viewed 43 times

0

I’m starting in Openlayers and I’m having a problem visualizing polygons on maps. I have a set of polygons being returned from a query in the database (postgres/postgis). This set of polygons is passed via json by an ajax request to the frontend where I plan to use the Openlayers3 library to display these polygons on a map.

Example of return as KML:

{st_askml=<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>-53.460269936027402,-24.954734829872194 -53.460072335178054,-24.954744520125182 -53.460093771307605,-24.955104793997403 -53.460291372725941,-24.955095103672289 -53.460269936027402,-24.954734829872194</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>}
{st_askml=<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>-53.459896169834188,-24.955114484062349 -53.459874734273619,-24.9547542101181 -53.459701833437066,-24.954762688648493 -53.459723268499758,-24.955122962655768 -53.459896169834188,-24.955114484062349</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>}

What would be the best way to create the vector layer with these polygons using OL3? Saving the set of polygons in a file and using this file as source for the layer? Using json itself as source for the layer? (is there such a possibility?) and what the syntax of this layer would look like in OL3?

1 answer

0

Let’s assume your polygons are composed of coordinate lists lat x lng, for example:

var a =[
    {
        "lng": 106.972534,
        "lat": -6.147714
    },
    {
        "lng": 106.972519,
        "lat": -6.133398
    },
    {
        "lng": 106.972496,
        "lat": -6.105892
    }
]

The primitive geom.Polygon() accepts collections where the last item in the list is equivalent to the first (so that its polygon is properly closed) and where latitude and longitude are defined in a collection of primitive values ([lng, lat]).

You need to close your polygon, using the same initial coordinates as endings:

a.push(a[0]);

After that, transform the initial collection of complex members into primitive collections:

var b = a.map(function(item) {
    return [item.lng, item.lat];
});

After that, create the object via startup:

var polygon = new ol.geom.Polygon([b]);

Finally, to show the polygon you should use a wrap of the type feature() and add it to a layer of vectors, which is then added to the map:

var feature = new ol.Feature(polygon);

var vectorSource = new ol.source.Vector();
vectorSource.addFeature(feature);

var vectorLayer = new ol.layer.Vector({ source: vectorSource });

map.addLayer(vectorLayer);

(Adapted from https://stackoverflow.com/questions/27210362/open-layers-3-how-to-draw-a-polygon-programmically)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.