我使用Nodejs创建了一个restfulAPI,我想从中在Openlayers中创建一个新的Vectorlayer并显示在地图上。
我从API获得的GeoJSON看起来像这样(JSONlint和geojson.io都说这是有效的):
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [9.9627244, 53.5565378]
},
"properties": {
"f1": 1,
"f2": "Tabakbörse",
"f3": "Beim Grünen Jäger 2, 20359 Hamburg"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [9.9874951, 53.5162912]
},
"properties": {
"f1": 2,
"f2": "Fähr Getränke Kiosk",
"f3": "Veringstraße 27, 21107 Hamburg"
}
}]
}
addKioskGeoJSON函数应将图层添加到地图:
import './map.scss'
import {Map as olMap} from 'ol'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import { fromLonLat } from 'ol/proj'
import {Style, Icon} from 'ol/style'
import { Vector as layerVector } from 'ol/layer'
import { Vector as sourceVector } from 'ol/source/'
import GeoJSON from 'ol/format/GeoJSON'
import { Component } from '../component'
const template = '<div ref="mapContainer" class="map-container"></div>'
export class Map extends Component {
constructor (placeholderId, props) {
super(placeholderId, props, template)
const target = this.refs.mapContainer
// Initialize Openlayers Map
this.map = new olMap({
....
});
this.layers = {}; // Map layer dict (key/value = title/layer)
}
addKioskGeojson (geojson) {
console.log(geojson)
this.layers.kiosks = new layerVector({
title: 'Kiosks',
visible: true,
source: new sourceVector({
format: new GeoJSON(),
projection : 'EPSG:4326',
url: geojson
}),
style: new Style({
image: new Icon(({
anchor: [0.5, 40],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: './map-icons/kiosk.png'
}))
})
});
this.map.addLayer(this.layers.kiosks)
}
}
奇怪的是,我可以在image和我的代码中看到console.log()geojson,但是收到一条404错误消息,将其添加为矢量层。
答案 0 :(得分:0)
您已经有一个geojson对象(它不是URL)。您所需要做的就是从对象中解析功能:
addKioskGeojson (geojson) {
console.log(geojson)
this.layers.kiosks = new layerVector({
title: 'Kiosks',
visible: true,
source: new sourceVector({
features: new GeoJSON().readFeatures(geojson, { featureProjection: this.map.getView().getProjection() })
}),
style: new Style({
image: new Icon(({
anchor: [0.5, 40],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: './map-icons/kiosk.png'
}))
})
});
this.map.addLayer(this.layers.kiosks)
}