【问题标题】:GEOjson not displaying in my map openlayersGEOjson 未显示在我的地图 openlayers 中
【发布时间】:2019-01-08 02:06:25
【问题描述】:

我想在我的地图 openLayers 中显示 geojson 数据,但我的数据没有显示,地图甚至没有显示。我使用 openLayers 5。 我有一个 api(在 node.js 中),它允许在我的数据库中提取数据。 我有一个文件(script.js),它允许显示地图,恢复 api 发送的数据并在地图上显示数据。

在 script.js 中:

我创建了一个包含geojson样式的新vectorLayer:

 var foncier2 = new VectorLayer({
source:source,
style: function (feature, res) {
  property = feature.get("nature");
  return new  Style({
    stroke: new Stroke({
      color: [40, 40, 40, 1],
      width: 0.3
    }),
    fill: new Fill({
      color: couleur(property)
    })
  })
},});

我请求我的 API 在回调的帮助下恢复数据:

`
function loadJSON(callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            console.log(this.responseText);
            callback(this.responseText);
          }
        };
        xhr.open("GET", "adressIP:port/endpoint", true);
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(null);
      }`

然后我创建一个函数,将数据转换为 json 然后转换为 GEOjson :

   var myData = JSON.parse(data);

var geojsonObject = {
 "type": "FeatureCollection",
 "crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
 "features": [
   {
     "type": "Feature",
     "geometry": {
       "type": "Polygon",
       "coordinates":myData[2].geom
     }
   }
 ]};

最后我显示数据:

foncier2.getSource().clear();
foncier2.getSource().addFeatures(foncier2.getSource().getFormat().readFeatures(geojsonObject, {
  dataProjection: 'EPSG:4326',
  defaultFeatureProjection: 'EPSG:3857',
}));
foncier2.getSource().refresh();
foncier2.getSource().changed();
map.getView().fit(foncier2.getSource().getExtent());

但是
我的地图上没有显示任何内容,我的控制台日志中也没有错误。

谢谢你帮助我

PS :(我设法恢复了数据,看起来像thatthe coordinates)

【问题讨论】:

  • readFeatures 中的选项应该是featureProjection(而不是defaultFeatureProjection)。如果这不能解决它,您可以在创建source 的位置包含您的代码以检查格式是否正确指定?
  • 我将 readFeatures 更改为 featureProjection 但问题仍然相同。源代码: var source = new VectorSource({ format: new GeoJSON(), features: [], });

标签: javascript node.js json openlayers geojson


【解决方案1】:

您正在为几何体设置坐标(您的屏幕截图显示为多面体)而不是几何体的坐标并且不更新类型。试试这个:

var geojsonObject = {
 "type": "FeatureCollection",
 "crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
 "features": [
   {
     "type": "Feature",
     "geometry": {
       "type": JSON.parse(myData[2].geom).type,
       "coordinates": JSON.parse(myData[2].geom).coordinates
     }
   }
 ]};

【讨论】:

  • 感谢您的建议,我的问题几乎解决了,现在我的地图正在显示。但是 GEOjson 没有出现,因为我的控制台显示:“ Unsupported GeoJSON type: undefined ”。所以我做了一个 console.log(myData[2].geom.type) 它告诉我“未定义”。我没有使用正确的方式来显示数据?
  • 我刚刚注意到您的屏幕截图中有一个额外的",因此尽管您解析了data,但数据中的geom 值仍然是一个字符串,因此也需要解析。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多