6

I have an query that produces an array of coordinates like so: 95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65 (long/lat separated by "," and coordinates separated by a space).

How can I use these arrays to dynamically draw polygons on my map?

Ideas?

edit 1

Long answer… I have a table with rows like so: Area 1 lot1 95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65 Area 1 lot2 95.63,38.65 95.27,37.98 94.60,39.66 92.97,37.64 Area 2 lot 3 95.64,38.63 95.24,37.95 95.66,37.62 94.94,37.61 The first column has a checkbox. As I select a checkbox, I want to draw a polygon using the coordinates from each row.

1 Answer 1

12

Of course you can.

You must translate your string to an array of coordinates readable by your map.

Something like that:

var polyCoords = [];
var coords = "95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65".split(' ');

for (var i in coords) {
  var c = coords[i].split(',');
  polyCoords.push(ol.proj.transform([parseFloat(c[0]), parseFloat(c[1])], 'EPSG:4326', 'EPSG:3857'));
}

var feature = new ol.Feature({
    geometry: new ol.geom.Polygon([polyCoords])
})

var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: [feature]
    })
});

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'sat'})
    }),
    layer            
  ],
  view: new ol.View({
    center: ol.proj.transform([95.22, 37.98], 'EPSG:4326', 'EPSG:3857'),
    zoom: 4
  })
});

Here a live example

4
  • I should have been more specific. The coordinates are being pushed in an array from a table like so: if ($this.is('checked')){ tableData.push(polygon); "polygon" holding the array of coordinates.
    – Dean
    Commented Apr 8, 2015 at 20:50
  • What is inside this variable polygon ? polygon = "95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65" ?
    – oterral
    Commented Apr 9, 2015 at 9:18
  • Short answer…. Yes. Long answer… I have a table with rows like so: Area 1 lot1 95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65 Area 1 lot2 95.63,38.65 95.27,37.98 94.60,39.66 92.97,37.64 Area 2 lot 3 95.64,38.63 95.24,37.95 95.66,37.62 94.94,37.61 The first column has a checkbox. As I select a checkbox, I want to draw a polygon using the coordinates from each row.
    – Dean
    Commented Apr 9, 2015 at 13:34
  • I figured it out!
    – Dean
    Commented Apr 10, 2015 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.