I'm trying to get vector feature from geojson file displayed in openlayers 3.9.0.

{"type": "FeatureCollection","crs": {"type": "name","properties": {"name": "EPSG:3857"}},
"features": [{"type": "Feature","geometry": {"type": "Point","coordinates": [0, 0]}}]}

Does anyone see why this code does not do it?

<!doctype html>
<html lang="en">
    <link rel="stylesheet" href="http://openlayers.org/en/v3.9.0/css/ol.css" type="text/css">
    <script src="http://openlayers.org/en/v3.9.0/build/ol.js" type="text/javascript"></script>
      html, body, #map {
        margin: 0;
        height: 100%;
        width: 100%;
    <div id="map" class="map"></div>
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.MapQuest({layer: 'sat'})
          new ol.layer.Vector({
            source: new ol.source.Vector({
              url: 'data.json',
              format: new ol.format.GeoJSON()
        view: new ol.View({
          center: [0, 0],
          zoom: 2

Note that reading the geojson from an internally defined object works fine:

  var geojsonObject = {
    "type": "FeatureCollection",
    "crs": {"type": "name","properties": {"name": "EPSG:3857"}},
    "features": [
      {"type": "Feature","geometry": {"type": "Point","coordinates": [0, 0]}}
  new ol.layer.Vector({
    source: new ol.source.Vector({
      features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)

Your source arguments need some corrections. You use the object key "source" twice. Replace the 2nd with "format":

source: new ol.source.Vector({
        url: 'data.json',
        format: new ol.format.GeoJSON()
  • I have corrected it but it still won't work. – yaugenka Sep 22 '15 at 7:04
  • There can be many reasons. Do you get an error message? (Press F12 for opening the developer tools in Fire Fox or Chrome) – fidelfisch Sep 22 '15 at 7:08
  • Here is the error message: XMLHttpRequest cannot load file:///D:/gsdata/www/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – yaugenka Sep 22 '15 at 7:37
  • This error happens when you want to access files from another domain (en.wikipedia.org/wiki/Cross-origin_resource_sharing). Do you use an apache server? you have to access it by using "localhost/index.html". Not recommended would be to switch of the restriction: stackoverflow.com/questions/3102819/… – fidelfisch Sep 22 '15 at 7:54
  • I was lanching my map file by just clicking on it. I have geoserver instaled and have just tried accessing the file by http:/<host:port>/geoserver/www/ link and it works! – yaugenka Sep 22 '15 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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