我正在开发一个openlayers地图,在create-react-app项目中添加一个带有本地geojson文件源的矢量图层,但是无法显示矢量图层。
这是我的代码:
import React,{ Component } from 'react'
import './BaseMap.scss'
import 'ol/ol.css'
import {Map, View} from 'ol'
import TileLayer from 'ol/layer/Tile'
import {fromLonLat} from 'ol/proj'
import XYZ from 'ol/source/XYZ'
import {defaults, ScaleLine } from 'ol/control'
import GeoJSON from 'ol/format/GeoJSON';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
const vectorLayer = new VectorLayer({
source: new VectorSource({
url: './shanghang_lj.json',
format: new GeoJSON()
}),
style: function(feature) {
style.getText().setText(feature.get('name'));
return style;
}
});
const tian_di_tu_road_layer = new TileLayer({
title: "road_layer",
source: new XYZ({
url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"
})
});
const tian_di_tu_annotation = new TileLayer({
title: "annotation",
source: new XYZ({
url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}'
})
});
export class BaseMap extends Component{
constructor(props){
super(props);
};
componentDidMount(){
let map = new Map({
controls: new defaults({
attributionOptions: {
collapsible: false
}
}).extend([
new ScaleLine()
]),
target:'basemap',
layers:[
tian_di_tu_road_layer,//can be displayed
tian_di_tu_annotation,//can be displayed
vectorLayer//can not be displayed
],
view:new View({
center:fromLonLat([116.4,25.0]),
zoom:10
})
})
}
render(){
return(
<div id="basemap" className='basemap'></div>
)
}
}
我从控制台得到错误:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at getObject (JSONFeature.js:188)
at GeoJSON.readFeatures (JSONFeature.js:56)
at VectorSource.<anonymous> (featureloader.js:87)
然后我尝试了另一种传递geojson数据的方法:
import border_shanghang from './shanghang_lj.json';
const vectorLayer = new VectorLayer({
source: new VectorSource({
features: (new GeoJSON()).readFeatures(border_shanghang)
}),
});
控制台中不显示任何错误,但仍未显示矢量图层。
我一直在努力解决这个问题。任何帮助将不胜感激。
顺便说一下,如果我没有反应就运行代码。
我尝试使用示例geojson文件实现此功能,对我有用的是:
import border_shanghang from './shanghang_lj.geojson'; // I got a sample geojson from the web
const style = // ...;
const vectorLayer = new VectorLayer({
source: new VectorSource({
url: border_shanghang,
format: new GeoJSON()
}),
style: function (feature) {
style.getText().setText(feature.get('name'));
return style;
}
});
// ...
其他一切都一样。唯一的区别是将导入直接放入VectorSource的url
字段,并将您的文件从.json
重命名为.geojson