Adding geojson layer to openlayers 3

跟風遠走 提交于 2019-12-23 05:17:17

问题


I have gone through a few different examples on this and nothing ever seems to work. I am trying to simply draw a point on the map using GeoJSON as the source. Here is what I currently have:

var staticGeo = new ol.source.GeoJSON(({
    object: {
        type: 'Feature Collection',
        crs: {
           type: 'name',
           properties: {name: 'EPSG:4326'}
        },
        features: [{
           type: 'Feature',
           geometry: {
               type: 'Point',
               coordinates: [0,0]
           }
        }]
     },
     projection: 'EPSG:3857'
   }));

   var vectorSource = new ol.source.Vector({
       source: staticGeo
   });

   var vectorLayer = new ol.layer.Vector({
       source: vectorSource,
       style: new ol.style.Style({
           fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.2)'
           }),
           stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
           })
        })
     })

     this.map.addLayer(vectorLayer);

this.map refers to the ol.Map object that is working. This overall seems like a lot of code to do something that should be seemingly trivial (maybe I am doing something wrong?).


回答1:


From OL 3.5.0 you will add geojson like this:

var geojsonObject = {
    'type': 'FeatureCollection',
    'crs': {
        'type': 'name',
        'properties': {
            'name': 'EPSG:4326'
        }
    },
    'features': [
        {
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': [21.54967, 38.70250]
            }
        }
    ]
};
var features = new ol.format.GeoJSON().readFeatures(geojsonObject, {
    featureProjection: 'EPSG:3857'
});
var vectorSource = new ol.source.Vector({
  features: features
});

Note the projection coordinates.

http://jsfiddle.net/jonataswalker/w5uuxhov/



来源:https://stackoverflow.com/questions/32789411/adding-geojson-layer-to-openlayers-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!