''未捕获的SyntaxError:意外的令牌<在JSON的位置''使用openlayers js

时间:2017-05-20 16:53:09

标签: openlayers geojson geoserver

有些日子我试图解决这个问题,但我无法得到正确的答案;我试图使用openlayers工具从geoserver插入带有wfs请求的地图,但是我收到此错误:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Jl (ol.js:342)
    at wm.k.Pa (ol.js:342)
    at T.<anonymous> (ol.js:340)

这是我的代码:

<HTML>
<head>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.1.1/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
</head>
<center>
<div id="mapid" style="width: 600px; height: 500px;"></div>
</center> 
<script>
 var vectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: function(extent) {
          return 'http://localhost:8080/geoserver/opengeo/ows?service=WFS&' +
          'version=1.0.0&request=GetFeature&typeName=opengeo:comgeo&' +
          'maxFeatures=50'+
          'outputFormat=application%2Fjson' ;

        },
        strategy: ol.loadingstrategy.bbox
      });



      var map = new ol.Map({
        layers: [
        new ol.layer.Vector({
        source: vectorSource,
        style: new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 255, 1.0)',
            width: 2
          })
        })
      })
        ],
        target: document.getElementById('mapid'),
        view: new ol.View({
          center: [-9, 30],
          maxZoom: 19,
          zoom: 5
        })
      });

</script> 

</HTML>

我不知道问题出在哪里,因为我没有找到任何关于json问题和openlayers的问题......谢谢

2 个答案:

答案 0 :(得分:1)

您的WFS请求无效。变化

'maxFeatures=50'

'maxFeatures=50&'

您也没有设置WFS请求的BBOX。因此,您应该删除bbox策略,或添加

&BBOX=' + extent.toString()

到您的WFS网址。

答案 1 :(得分:0)

我遇到了同样的问题,所以我的回答也可能会帮助其他人。

对我来说,我要求的(不是全部)某些 层确实返回XML而不是JSON。由于我在循环中请求多个层,因此调试起来很棘手,有些会按预期返回JSON,有些则不会,导致您认为它们 all 都很好,就像您看到的某些层一样显示在地图上。

在我的情况下,这是由于服务器内存不足而检索了这些特定层的查询结果,因此,按如下所示返回了XML错误页面:

<ServiceExceptionReport xmlns="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2.0" xsi:schemaLocation="http://www.opengis.net/ogc http://schemas.opengis.net/wfs/1.0.0/OGC-exception.xsd">
<ServiceException>
java.lang.RuntimeException: java.io.IOException java.io.IOExceptionorg.postgresql.util.PSQLException: Ran out of memory retrieving query results. Ran out of memory retrieving query results. Java heap space
</ServiceException>
</ServiceExceptionReport>

我建议您直接在Web浏览器中加载 all 层的URL,或者使用浏览器开发人员工具检查每个服务器的响应,即使您确定它们应该返回JSON也是如此。