【发布时间】:2020-07-21 10:53:06
【问题描述】:
我想从本地主机上的 API 获取数据(geojson 格式),并根据读取的数据,在地图上显示标记。
GeoJson 格式:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
53.531697,
23.545435
]
},
"properties": {
"Shop_Id": 328,
"Shop_Name": "A01_0386,4_TF_0",
"Shop_Radius": 0.1512987687
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
29.54306,
31.531401
]
},
"properties": {
"Shop_Id": 532,
"Shop_Name": "A01_0397,0_TF_0",
"Shop_Radius": 0.1773436375047
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
28.34949,
30.10745
]
},
"properties": {
"Shop_Id": 160,
"Shop_Name": "A01_0003,9_TF_0",
"Shop_Radius": 0.1922466020678
}
}
]
}
当我从 geojson 文件中读取它时,它会正确显示在地图上,但如果我想从 API 获取数据: http://localhost:8080/get_shops,那么我无法到达这些标记。
我的逻辑:
var styles = {
'Point': new Style({
stroke: new Stroke({
color: 'rgba(17,158,76,0.8)',//#F3C35D
width: 15,
})
})
}
var styleFunction = function(feature) {
return styles[feature.getGeometry().getType()];
};
var vectorSource = new VectorSource({
format: new GeoJSON(),
loader: vectorLoader(),
projection:"EPSG:4326",
})
function vectorLoader(){
axios.get('http://localhost:8080/get_shops'
,{
"dataType": 'json',
headers: {
"Content-Type":"application/json",
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Headers': 'Origin,X-Requested-With,Content-Type,Accept',
'Access-Control-Allow-Credentials': true,
"crossorigin":true
}
}
)
.then(res => {
console.log("1: " + JSON.stringify(res.data));
console.log("1: " + JSON.stringify(res.data[0]));
var geoJsonFormat = new GeoJSON();
var features = geoJsonFormat.readFeatures(JSON.stringify(res.data));
vectorSource.addFeatures(features)
// return JSON.stringify(res.data[0]);
})
.catch(err => console.warn(err))
}
var vectorLayer = new VectorLayer({
source: vectorSource,
style: styleFunction
});
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
}),vectorLayer],
view: new View({
center: fromLonLat([12,44]) ,
zoom: 3,
})
});
和错误:
Error: Unsupported GeoJSON type: undefined
readGeometry GeoJSON.js:295
readFeatureFromObject GeoJSON.js:110
readFeaturesFromObject GeoJSON.js:144
readFeatures JSONFeature.js:52
vectorLoader Mapper.js:110
我想使用 Axios 而不是 jQuery,因为我收到了 $ is no defined 的错误。
有什么建议吗?
【问题讨论】:
-
哪个
console.log调用显示了正确的数据?无论哪个是正确的,都不需要对数据进行字符串化,解析器可以处理一个对象 - 但您需要将特征转换为地图投影var features = geoJsonFormat.readFeatures(res.data, {featureProjection: map.getView().getProjection()}); -
正确数据显示 JSON.stringify(res.data[0]) ;这个 [0] 因为来自外部站点我有方括号。我添加了这个 featureProjection 但这不起作用。
-
所以你还需要在
readFeatures调用中使用res.data[0]。 -
是的,我尝试了所有组合,但仍然无法正常工作。也许我忘记了一些重要的方面?你能给我看看codepen或类似的解决方案吗?
-
如果您的 console.log 显示 geojson 数据,则数据中可能缺少某些内容,例如几何或几何类型,如错误所示。您可以在问题中包含日志输出吗?
标签: javascript reactjs axios openlayers geojson