OpenLayers - 尝试使用JSON文件加载图层

时间:2013-09-03 19:54:44

标签: openlayers

我将需要加载到我的地图中的一堆图层,因此我不是单独加载每个图层而是尝试使用json文件和Openlayers.Request.GET加载,但不知道如何完成代码。

json文件:

{
"layers": [
{ "title":"Client Manholes" , "url":"./mh_file.geojson" , "style":"mh_style"}, 
{ "title":"Client Pipe" , "url":"./pipe_file.geojson" , "style":"pipe_style"}, 
{ "title":"Client Parcels" , "url":"./parcel_file.geojson" , "style":"parcel_style"}
]
}

的javascript:

var request = OpenLayers.Request.GET({
    url: "http://domain.com/layers.json",
    callback: handler
});

function handler(request) {
    //alert (request);
    var  response = json.read (request.responseText);
    //loop thru each layer
    for each (var layer in request) {
                //load layer
                layer = new OpenLayers.Layer.Vector(layer_title, {
                    strategies: [new OpenLayers.Strategy.Fixed()],
                    protocol: new OpenLayers.Protocol.HTTP({
                        url: layer_url,
                        format: new OpenLayers.Format.GeoJSON({
                        })
                    }),
                    //...load stylemap
                });
                //turn layer off
                layer.setVisibility(false);
            }

        };

1 个答案:

答案 0 :(得分:1)

修正了它!

function handler (request) {
            var  json = new  OpenLayers.Format.JSON ();
            var  response = json.read (request.responseText);
            //console.log(response); 
            var layer_data = response.layers
            for (var i in layer_data) {
                var layer_name = layer_data[i].title;
                //alert(layer_name);
                var layer_url = layer_data[i].url;
                //alert(layer_url);
                var layer_style = layer_data[i].style;
                //alert (layer_style);
                layer = new OpenLayers.Layer.Vector(layer_name, {
                    strategies: [new OpenLayers.Strategy.Fixed()],
                    protocol: new OpenLayers.Protocol.HTTP({
                        url: layer_url,
                        format: new OpenLayers.Format.GeoJSON({
                        })
                    }),
                    //...load stylemap
                });
                //turn layer off
                layer.styleMap = mh_style_map;
                layer.setVisibility(false);
                map.addLayer(layer);
            }
            //alert (response);
        };