我正在努力在一个创建-反应-应用程序项目中添加一个带有本地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)
}),
});控制台中没有出现错误,但仍然没有显示向量层。
我和这个问题斗争很久了。任何帮助都将不胜感激。
顺便说一句,如果我在没有反应的情况下运行代码,代码就能工作。
发布于 2018-09-07 06:38:22
我尝试用一个样例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的VectorSource字段中,并将文件从.json重命名为.geojson。
https://stackoverflow.com/questions/52216011
复制相似问题