Add GeoJSON Layer to OpenLayers 3 – JavaScript Mapping Integration

geojsonjavascriptopenlayersopenstreetmap

I have a GeoJSON file called mygeojson.json and I want to add it as a layer in OpenLayers 3 on top of an openstreetmap layer. So far I could display the openstreetmap world including zoom etc. but for some reason I can't get the mygeojson.json on it.

The geojson contains many polygons and looks like this:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
      { "type": "Feature", "properties": { "DN": 2 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.559093915055664, 52.545214330050563 ], [ 13.559633429050496, 52.545205649772548 ], [ 13.559633415380715, 52.545214636296755 ], [ 13.559093915055664, 52.545214330050563 ] ] ] } }
]
}

my main.html:

<!doctype html>
<html lang="en">
  <head>
    <link rel='stylesheet' href='http://ol3js.org/en/master/css/ol.css'>
    <style>
      #map {
        height: 100%;
        width: 100%;
      }
    </style>
    <title>OpenLayers 3 example</title>
    <script src="ol3/ol.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>My Map</h1>
    <div id="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
           new ol.layer.Tile({
              source: new ol.source.OSM()
           }),
           new ol.layer.Vector({
              title: 'added Layer',
              source: new ol.source.GeoJSON({
                 projection : 'EPSG:4326',
                 url: 'mygeojson.json'
              })
           })
        ],
        view: new ol.View({
          center:[52.5243700 , 13.4105300],
          zoom:2

        })
      });
    </script>
  </body>
</html>

I also tried removing the projection info but no use.

Best Answer

FYI... I believe this has changed for OL3 V3.5.0, so gcarrillo's answer would be:

new ol.layer.Vector({
      title: 'added Layer',
      source: new ol.source.Vector({
         url: 'mygeojson.json',
         format: new ol.format.GeoJSON()
      })
  })

You can see the changes here: https://github.com/openlayers/ol3/blob/master/changelog/upgrade-notes.md#v350

Related Question