node.js - Openlayers 无法从 RestfulAPI(节点)显示 GeoJSON Vectorlayer
问题描述
我使用 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)
}
}
奇怪的是,我可以 console.log() 如您在图像和我的代码中看到的geojson,但会收到 404 错误消息,将其添加为矢量图层。
解决方案
您已经有一个 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)
}
推荐阅读
- java - Java AES 加密问题
- python - Opencv 相机校准用于世界查看端口映射
- r - 如何将R脚本转换为函数
- java - 从不包含它的模块(jar)中读取的包
- azure-devops - 为继承的进程预定义工作项并在 Azure Boards 中自动创建它
- c++ - QTabWidget setCurrentIndex 未按预期工作
- java - 测试在返回 Void 的方法内的变量上调用了方法
- sql - 如何确定不在 DBA_TAB_PRIVS 表中的用户的表权限?
- mysql - 我可以将多个 MySQL 行组连接到一个字段中吗?
- python - 如何通过创建自己的函数来比较两个变量?