2016-10-27 89 views
1

我试图在openlayers地图上显示geojson文件。该openlayers地图已经工作,但我不知道如何显示来自geoj​​son文件的功能。不幸的是,The example on their website不是很有用,因为它只是将geojson对象直接写入文件中,然后再进行访问。我希望从一个单独的geojson文件中获取这些特征并将它们显示在地图上。试图在Openlayers 3上显示GeoJSON 3

这是我到目前为止,直接从复制的范例:

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

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

var map = new ol.Map({ 
    layers: [ 
     new ol.layer.Tile({ 
      source: new ol.source.OSM() 
     }), 
     vectorLayer 
    ], 
    target: 'map', 
    controls: ol.control.defaults({ 
     attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ 
      collapsible: false 
     }) 
    }), 
    view: new ol.View({ 
     center: [0, 0], 
     zoom: 2 
    }) 

});

我需要知道的是如何“打开”文件并从geojson文件(当前位于地址..\public\geojson\federal_ridings.geojson)获取功能,以取代已存在的变量geojsonObject

回答

1

从外部文件添加GeoJSON的层替换:

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

var vectorSource = new ol.source.Vector({ 
    url: '..\public\geojson\federal_ridings.geojson', 
    format: new ol.format.GeoJSON() 
}); 

ol.format.GeoJSON documentation

确保federal_ridings.geojsonvalid JSON file

Demo