Saturday, July 6, 2013

OpenLayers GeoJSON Vector Layer

[caption id="attachment_854" align="alignnone" width="602"]geojson Geojson[/caption]

Let's see how we can add a vector layer to OpenLayers map with the help of  GeoJSON response received from the server. Web Server can produce response in GML, GeoJSON, XML...etc after running a spatial query.
OpenLayers has Format classes for interpreting each kind of response.
This response consists of raw data which should be converted to features and added to a vector layer in order to render with OpenLayers.

[sourcecode language="javascript"]
var newLayer = new OpenLayers.Layer.Vector("Filtered by Zoom Level", {
strategies: [new OpenLayers.Strategy.BBOX(),
],

protocol: new OpenLayers.Protocol.HTTP({
url: "http://localhost/test/a.php?start=79.891119%207.078768&end=81.000609%207.940130&method=SPD",
format: new OpenLayers.Format.GeoJSON({
externalProjection: new OpenLayers.Projection("EPSG:4326"),
internalProject: new OpenLayers.Projection("EPSG:900913")
})
}),

//filter: filter,

// styleMap: styleMap,
format: new OpenLayers.Format.GeoJSON({
externalProjection: new OpenLayers.Projection("EPSG:4326"),
internalProject: new OpenLayers.Projection("EPSG:900913")
})

});
map.addLayers([newLayer]);
[/sourcecode]

Another Way

[sourcecode language="javascript"]
var newLayer = new OpenLayers.Layer.Vector("SPD", {
isBaseLayer: false,

styleMap: new OpenLayers.StyleMap({'default':{
strokeColor: "#F00",
strokeOpacity: 1,
strokeWidth: 2,
fillColor: "#FF5500",
fillOpacity: 0.5,
label : "${ad}",
fontSize: "8px",
fontFamily: "Courier New, monospace",
labelXOffset: "0.5",
labelYOffset: "0.5"
}})
});


OpenLayers.Request.GET({
url: "http://localhost/test/a.php?start=79.891119%207.078768&end=81.000609%207.940130&method=SPD",
headers: {'Accept':'application/json'},
success: function (req)
{
var g = new OpenLayers.Format.GeoJSON();
var feature_collection = g.read(req.responseText);
newLayer.destroyFeatures();
newLayer.addFeatures(feature_collection);
}
});
map.addLayers([newLayer]);
[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...