philippos
philippos

Reputation: 1293

How to set the coordinates for a polygon in openlayers?

I am very new to OpenLayers and JavaScript, and I have the following problem.

I have an .csv table representing the coordinates of points I want to visualize them on a map using OpenLayers.

I have found the following example on the OpenLayers page,

https://openlayers.org/en/latest/examples/polygon-styles.html

However, I couldn't understand the representation of the coordinates there. More specifically, I didn't know what does the e mean in the coordinate [-5e6, 6e6] for example.

However, I tried to plot a simple square on my map using my coordinates, but it just giving me a point, in the center of the map, as following:

https://jsfiddle.net/api/post/library/pure/#&togetherjs=bD5bfPm7vz

So I don't know what's exactly is wrong, and what should I change? I think it's all in the way the coordinates are written, but not sure though.

And this is my code:

var styles = [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'blue',
      width: 3
    }),
    fill: new ol.style.Fill({
      color: 'rgba(0, 0, 255, 0.1)'
    })
  }),
  new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
        color: 'orange'
      })
    }),
    geometry: function(feature) {
      // return the coordinates of the first ring of the polygon
      var coordinates = feature.getGeometry().getCoordinates()[0];
      return new ol.geom.MultiPoint(coordinates);
    }
  })
];

var geojsonObject = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:3857'
    }
  },
  'features': [{
    'type': 'Feature',
    'geometry': {
      'type': 'Polygon',
      'coordinates': [[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6],
          [-3e6, 6e6], [-5e6, 6e6]]]
    }
  }]
};

var source = new ol.source.Vector({
  features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

var layer = new ol.layer.Vector({
  source: source,
  style: styles
});

    var basic = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

var map = new ol.Map({
  layers: [basic, layer],
  target: 'map',
  view: new ol.View({
    center: [0, 3000000],
    zoom: 2
  })
});

Upvotes: 1

Views: 3137

Answers (1)

philippos
philippos

Reputation: 1293

OK, I found the answer. The following coordinates [-5e6, 6e6] is in X,Y format, and is based on the EPSG:3857 projection. XeY is equal to X * 10 ^ Y. Normally the openlayers use the EPSG:3857 projection, but in order to use the longitude/latitude coordinates format, we have to use the projection: EPSG:4326 projection, and we specify it clearly like: projection: 'EPSG:4326

Upvotes: 1

Related Questions