问题
I already tried to put the following function and new Vector Layer into my code. I uploaded the GeoJSON File into my BPlaced account to link the file in my code, is that right? The Geojson has the same Coordinate System as the website. Also the code seems to work but I don't see any of the Geojson.
Or is there another way to embed GeoJSON into OpenLayers?
Here is my code:
var vectorLayerJSON = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: 'http://kristinab.bplaced.net/ALDI_LIDL_Buffer_KBS_3857.geojson'
}),
style: new ol.style.Style({
image: new ol.style.Circle(({
radius: 20,
fill: new ol.style.Fill({
color: '#ffff00'
})
}))
})
});
回答1:
welcome to the SO :)
I believe that there are several ways to add vectors (geojson) data to map
1) loading vectors using geojson file url:
var vectorLayerJSON_1 = new ol.source.Vector({
projection : 'EPSG:3857',
url: 'myFolder/yourFile_1.geojson',
format: new ol.format.GeoJSON()
});
2) generating vector layer from geojson object
var geojsonObject = {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:3857'
}
},
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [0, 0]
}
}, {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [[456, -256], [816, 226]]
}...
var vectorLayerJSON_2 = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
More detailed example on OpenLayer 3 example page Geojson Example
3) reading vector features from ajax
var vectorLayerJSON_3 = new ol.layer.Vector({
renderMode: 'image',
source: new ol.source.Vector({
loader: function() {
$.ajax({
type: 'GET',
url: 'myFolder/yourFile_2.geojson',
context: this
}).done(function(data) {
var format = new ol.format.GeoJSON();
this.addFeatures(format.readFeatures(data));
});
}
}),
style: myDefinedStyle
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayerJSON_1,
vectorLayerJSON_2,
vectorLayerJSON_3
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
Hope it helps :)
来源:https://stackoverflow.com/questions/50211597/how-to-get-geojson-into-openlayers