首页 > 解决方案 > 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 错误消息,将其添加为矢量图层。

标签: node.jsjsonopenlayersgeojsonkoa

解决方案


您已经有一个 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)
  }

推荐阅读