简体   繁体   中英

Open Layers 2 Creating and adding Feature to Vector Layer from Ajax Response

as title suggest, create Feature and add it to already created vector layer. I am fetching GeoJSON from server and trying to somehow add to vector layer but I can't get it to work... So basically I am asking how to get Feature element from my GeoJSON, so I can add it to vector layer. What I currently have..

This is my GeoJSON fetched from server :

{"type":"MultiPolygon","coordinates":[[[[20.5629940201429,48.9488601183337],[20.5630121528311,48.9489447276126],[20.563289335522,48.9489141101973],[20.563260061873,48.9488286413488],[20.5629940201429,48.9488601183337]]]]}

next I have addVector function in JavaScript where I'm trying to the magic.(variable GeoJS is GeoJSON fetched from server)

function addVector(geoJS){
    var feature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.MultiPolygon(geoJS) );
    vector = new OpenLayers.Layer.Vector("Magic"); 
    map.addLayer(vector);
    vector.addFeatures([feature]);
}

and yep I know that second line where I creating feature is wrong, but i cant make it right so i guess id doesn't matter what I write there for now... I tried it with var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(-70.702451, 42.374473); and it worked position on the map was not where I want it to be but I know that i have to do something with projection... It just doesn't matter now.

and btw I have this

vector = new OpenLayers.Layer.Vector("GeoJSON",
{
    projection       : "EPSG:4326",
    onFeatureInsert  : postIns,
    strategies       : [new OpenLayers.Strategy.Fixed()],
    protocol         :  new OpenLayers.Protocol.HTTP({
                            url: "test.php",
                            format: new OpenLayers.Format.GeoJSON()
                        })
});

And this works, position is where I want it, its perfect except it only works when I make request on my domain, and server I try to reach is on another(I know I can set headers and it would work) but I don't want to do it this way.

So basically I am asking how to get Feature from my GeoJSON. I am really new to OpenLayers so I'm sorry if I asking something obvious.

To use a simplified version of the official example :

var inputGeoJson = '...some-GeoJSON-here...';
var geojson_format = new OpenLayers.Format.GeoJSON();
var vector_layer = new OpenLayers.Layer.Vector();
map.addLayer(vector_layer);
vector_layer.addFeatures(geojson_format.read(inputGeoJson));

You can find more details in the GeoJSON class documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM