Layer KML using OpenLayers3

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 intend to use the OpenLayers3 library to display those polygons on a map.

Return example 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 to 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 how would the syntax of this layer be in OL3?

    
asked by anonymous 23.05.2017 / 01:33

1 answer

0

Let's assume that your polygons consist 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 one (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 starting coordinates as the endpoints:

a.push(a[0]);

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

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

After this, create the object via initialization:

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

Finally, to show the polygon you must use a wrapper of 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 link )

    
23.05.2017 / 15:02