将GeoJSON加载到OpenLayers时出错3 VectorLayer:JSON.parse期望属性名称

时间:2016-12-15 18:11:24

标签: javascript json openlayers-3 geojson

我试图将GeoJSON字符串加载到VectorLayer中,但遇到JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data问题。

已经阅读了类似JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data的短信,但无法解决我的问题。

这是我的JSON。在http://jsonviewer.stack.hu/进行了测试。

{'type': 'FeatureCollection','crs': {'type': 'name','properties': {'name': 'EPSG:4326'}},'features': [{'type': 'Feature','geometry':{'type':'MultiLineString','coordinates':[[[-43.1996056,-22.9109588],[-43.1993777,-22.9115575],[-43.1993539,-22.9116778],[-43.1993568,-22.9118156],[-43.199378,-22.9123812]]]}},{'type': 'Feature','geometry':{'type':'MultiLineString','coordinates':[[[-43.199378,-22.9123812],[-43.1994332,-22.9131767]]]}},{'type': 'Feature','geometry':{'type':'MultiLineString','coordinates':[[[-43.1994332,-22.9131767],[-43.1994563,-22.9141351],[-43.1994364,-22.9142456],[-43.199379,-22.9143303]]]}},{'type': 'Feature','geometry':{'type':'MultiLineString','coordinates':[[[-43.199379,-22.9143303],[-43.1985846,-22.9144791]]]}}]}

我的OpenLayers内容(featuresText是上面的GeoJSON):

    var styleFunction = function(feature) {
        return styles[feature.getGeometry().getType()];
    };      

    var vectorSource = new ol.source.Vector({
        features: ( new ol.format.GeoJSON() ).readFeatures( featuresText )
    });     

    var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: styleFunction
    });   

错误发生在ol-debug.js:45632。 JSON字符串似乎没问题。我无法弄清楚。

我也读过http://openlayers.org/en/master/examples/geojson.html

1 个答案:

答案 0 :(得分:2)

看看你的geojson和你的错误信息,我会尝试一个答案。第一行第2列是单引号。 JSON需要双引号来保存字符串see this question

另外,来自geojson specification

  

要素对象必须具有名称为"属性"的成员。属性成员的值是一个对象(任何JSON对象或JSON空值)。

您的功能没有属性。

有了这两个变化:

{"type": "FeatureCollection", "crs": {"type": "name","properties": {"name": "EPSG:4326"}},"features": [{"type": "Feature","properties": {}, "geometry":{"type":"MultiLineString","coordinates":[[[-43.1996056,-22.9109588],[-43.1993777,-22.9115575],[-43.1993539,-22.9116778],[-43.1993568,-22.9118156],[-43.199378,-22.9123812]]]}},{"type": "Feature","properties": {}, "geometry":{"type":"MultiLineString","coordinates":[[[-43.199378,-22.9123812],[-43.1994332,-22.9131767]]]}},{"type": "Feature","properties": {}, "geometry":{"type":"MultiLineString","coordinates":[[[-43.1994332,-22.9131767],[-43.1994563,-22.9141351],[-43.1994364,-22.9142456],[-43.199379,-22.9143303]]]}},{"type": "Feature","properties": {}, "geometry":{"type":"MultiLineString","coordinates":[[[-43.199379,-22.9143303],[-43.1985846,-22.9144791]]]}}]}

我在geojson.io

成功地展示了你的geojson