从API中提取时出现无效的GeoJSON错误

时间:2017-07-18 15:40:01

标签: javascript c# asp.net google-maps geojson

我正在开发一个项目,我需要通过jQuery ajax调用从.NET API中提取GeoJSON。 当我尝试将数据分配给变量时,然后将其加载到Google地图中,如下所示:

 map.data.addGeoJson(data);

它抛出错误说:

js:70InvalidValueError:不是功能或FeatureCollection

如果我采用API提供的相同响应,并将其直接粘贴到html文件中(因此将相同的值分配给JS变量数据)它可以正常工作并且地图呈现

我的猜测可能是编码问题?我甚至将响应输出到div,复制了div的值,将其粘贴,然后就可以了。似乎只是当我直接从API中分配它引发错误的值时。

我可以做些什么来格式化这个或让它正常工作?是剧本"打破" b / c格式化或用JavaScript直接写出来的东西?

非常感谢!

修改 我从API返回的数据已包含在功能集中:

{" type":" FeatureCollection","功能":[{" id":5280," type&# 34;:"功能","几何":{"类型":" MultiPolygon","坐标":[ [[[-73.431919,40.989009],[ - 73.423452,40.990793],[ - 73.398054,40.996147],[ - 73.389588,40.997932],[ - 73.388429,40.998151],[ - 73.384952,40.99881],[ - 73.383794,40.99903] ,[-73.383516,40.999082],[ - 73.382685,40.99924],[ - 73.382408,40.999293],[ - 73.38156,40.999453],[ - 73.379019,40.999935],[ - 73.378172,41.000097],[ - 73.377449,41.000289], [-73.375282,41.000867],[ - 73.37456,41.00106],[ - 73.358967,41.004214],[ - 73.312189,41.013675],[ - 73.296597,41.01683],[ - 73.296564,41.016837],[ - 73.295532,41.017045],[ -73.292437,41.017671],[ - 73.291406,41.01788],[ - 73.288203,41.018528],[ - 73.278594,41.020471],[ - 73.275392,41.02112],[ - 73.274206,41.021338],[ - 73.273019,41.021556],[ - 73.270225,41.022069],[ - 73.261288,41.023711],[ - 73.254724,41.024916],[ - 73.249557,41.02586 6],[ - 73.24916,41.025957],[ - 73.247968,41.026233],[ - 73.247572,41.026326],[ - 73.246328,41.026614],[ - 73.242596,41.027478],[ - 73.241353,41.027767], ... 端

提醒一下,如果我将输出直接粘贴到变量中,它就可以了。如果我的变量等于API的响应,则失败。

1 个答案:

答案 0 :(得分:-1)

查看this GeoJson页面,this GoogleMapsAPI页面

  

addGeoJson(geoJson:Object,options?:Data.GeoJsonOptions)

     

将GeoJSON功能添加到集合中。为此方法提供已解析的JSON。将返回导入的功能。如果无法导入GeoJSON,则会引发异常。

this所以问到接受的答案是如何包裹你的对象的那样:

 { "type": "FeatureCollection",
"features": [
  { "type": "Feature",
     "geometry": /** paste here the complete output of 
                     http://mapit.mysociety.org/area/11804.geojson **/
  }
 ]
}

编辑: 试试这个

var geojson = JSON.parse(data); 
map.data.addGeoJson(geojson);