[GIS] How to get GeoJSON features using OpenLayers

geojsonjavascriptopenlayers-2

Can anybody explain how to get geojson features .Can somebody show way to get attributes from geojson text.

OpenLayers.ProxyHost = "/gt/proxy.cgi?url=";
     var lon = 5;
    var lat = 44;
    var zoom = 5;
    var map, layer;

    //function init(){
       var bounds = new OpenLayers.Bounds(
                -125051.196, 3967670.8507,
                1549596.1896, 4677667.0145
            );
            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 6541.59135,
                projection: "EPSG:23036",
                units: 'm'
            };
    map = new OpenLayers.Map('map', options);
    map.addControl(new OpenLayers.Control.PanZoomBar({
                position: new OpenLayers.Pixel(2,10)
            }));

            map.addControl(new OpenLayers.Control.Navigation());
            //map.addControl(new OpenLayers.Control.Scale($('scale')));
            map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
             var geojson_format = new OpenLayers.Format.GeoJSON();
        var vl2 = new OpenLayers.Layer.Vector("",
        {isBaseLayer: true,
         styleMap: new OpenLayers.StyleMap({'default':{
                strokeColor: "#00FF00",
                strokeOpacity: 1,
                strokeWidth: 1,
                fillColor: "#FF5500",
                fillOpacity: 0.5,
                label : "${ad}",
                fontSize: "8px",
                fontFamily: "Courier New, monospace", 
                labelXOffset: "0.5",
                labelYOffset: "0.5"
            }})
        });
        map.addLayer(vl2);

       function handler(request) {

        vl2.addFeatures(geojson_format.read(request.responseText))
        map.zoomToExtent(bounds);
        }
        var request = OpenLayers.Request.GET({
        url: "myurljson&srsName=EPSG:23036",
        params: {},
        callback: handler
    });

please show me some way

Best Answer

To create a vector layer for your map from a geojson string, the following should work (with changes depending on your environment). The documentation from the OpenLayers API on the GeoJSON read function would be worth taking a look at as well.

var in_options = {
                'internalProjection': map.projection,
                'externalProjection': map.projection
                 };
var geojson_format = new OpenLayers.Format.GeoJSON(in_options);
var vectors = new OpenLayers.Layer.Vector("Some name", {style_options_etc});

var features = geojson_format.read(geosjon_str, "FeatureCollection");

//vectors.addFeatures requires an array, thus
if(features.constructor != Array) {
    features = [features];
}

vectors.reportError = true;
vectors.addFeatures(features);
map.addLayers([features]);
Related Question