在OpenLayers 4.6中读取geojson功能时出错

时间:2017-12-13 17:13:22

标签: openlayers geojson

所以,我开始构建一个简单的OpenLayers 4.6应用程序,并且我试图制作一个带有一些点特征的简单地图。我试图修改OpenLayers网站上的GeoJSON示例。我遇到的问题是我的geojson对象出了问题,应用程序抛出了以下错误:Uncaught TypeError: Cannot read property 'length' of undefined。从技术上讲,由于这是一个对象,而不是一个数组,它不应该有长度属性,所以我不知道为什么它会抛出错误。主要区别似乎是我添加了"属性"属性到geojson对象中的要素。

var geojsonObject = {
    "type": "FeatureCollection",
    "crs": {"type": "name","properties": {"name": "EPSG:3857"},
    "Features":[
      {
      "type" : "feature",
      "geometry" : {"type" : "Point", "coordinates" : [-4.65, 79.36]},
      "properties" : {
      "name" : "ARED",
      "country" : "Rwanda",
      "sector" : "ITC"
     }
    },{
    "type" : "feature",
    "geometry" : {'type':'Point','coordinates': [8.08, 29.19]},
    "properties" : {
      "name" : "Bio Phyto Collines",
      "country": "Benin", 
      "sector": "Organic Ag Inputs"
      }  
    }
  ]}}
var vectorSource = new ol.source.Vector({
  features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

传递geojson时会在readFeatures方法上抛出错误。我对其他实现持开放态度,但我试图比手动创建每个功能更优雅。

1 个答案:

答案 0 :(得分:2)

再次检查您的geojsonObject对象。并请使用JSON类型对象更好地缩进。我在代码中添加了对错误点的评论

var geojsonObject = {
  "type": "FeatureCollection",
  "crs": { // First, you didn't close `crs` brackets
    "type": "name",
    "properties": {
      "name": "EPSG:3857"
    }
  },
  "features":[{
    "type" : "Feature", // Second, it's `Feature' not `feature`
    "geometry" : {
      "type" : "Point", 
      "coordinates" : [-4.65, 79.36]
    },
    "properties" : {
      "name" : "ARED",
      "country" : "Rwanda",
      "sector" : "ITC"
    }
  }, {
    "type" : "Feature", // Feature again.
    "geometry" : {
      'type':'Point',
      'coordinates': [8.08, 29.19]
    },
    "properties" : {
      "name" : "Bio Phyto Collines",
      "country": "Benin", 
      "sector": "Organic Ag Inputs"
    }  
  }]
};