2017-04-06 103 views
0

如果要导入系统中的一个JSON文件到矢量图层,是一样简单:从API到矢量图层的OpenLayers JSON

var restaurantsold = new ol.layer.Vector({ 
    title: 'b_layer', 
    source: new ol.source.Vector({ 
     url: 'restaurantjson.geojson', 

     format: new ol.format.GeoJSON() 
    }), 
}); 

而且我可以直接添加层到地图。但是,如果我试图使一个API的调用,我不能在地图上显示出来,我最好的尝试一直是这样的:

var restaurants; 
    $.ajax({ 
     type: "GET", 
     url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita", 
     dataType:"json", 
     success:function(data){ 
      console.log(data) 
      restaurants = data; 
      $(restaurants).each(function(index, value) { 

       console.log(value.address); 
      }); 
      } 
    }); 
    var resta2 = new ol.layer.Vector({ 
     title : "Resta2", 
     source: new ol.source.Vector(restaurants) 
    }); 

我不能对这个地方找到一个妥善的解决办法,谢谢您的帮助!

编辑: 末尾的问题是,它得到一个JSON文件,并希望的OpenLayers一个GeoJSON的文件..我的方式来解决它是把它转换为GeoJSON的以下这一点: https://gis.stackexchange.com/questions/73756/is-it-possible-to-convert-regular-json-to-geojson

回答

1

的餐厅自创建Ajax调用以来,在创建矢量图层时,数据可能根本不可用。

因此,使用ol.format.GeoJSONreadFeatures()方法将GeoJSON转换为集合ol.Feature对象。然后使用addFeatures()方法添加它的矢量源。

修复:

var vectorSource = new ol.source.Vector({ 
     format: new ol.format.GeoJSON() 
    }) 

var restaurantsold = new ol.layer.Vector({ 
    title: 'b_layer', 
    source : vectorSource 
}); 

$.ajax({ 
     type: "GET", 
     url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita", 
     dataType:"json", 
     success:function(data){ 
      // If response is valid 
      var geojsonFormat = new ol.format.GeoJSON(); 

      // reads and converts GeoJSon to Feature Object 
      var features = geojsonFormat.readFeatures(data); 
      vectorSource.addFeatures(features); 
     } 
    }); 
+0

你是对的!我完全忘了在回调中做我的尝试,buuut,你的解决方案也无法正常工作:(控制台不显示任何错误,有什么我可以做的尝试跟踪错误? – ImanolUr

+0

检查从AJAX调用返回的数据。数据应该是GeoJSON格式或Data可能包含一些包含GeoJSON响应的对象 –

+0

我有一个控制台日志显示了我的第一个代码中的结果,结构是Array [Object,Object,Object],每个对象都有类似名称,拉特,lng,id ...看起来很漂亮geoJson。 – ImanolUr