[OpenLayers-Users] Pass layers array to php with json
Andreas Hocevar
ahocevar at opengeo.org
Fri Jul 31 08:03:22 EDT 2009
sendeman wrote:
> Hi All,
>
> I'm trying to load some php into a div in my mapping application through a
> http://docs.jquery.com/Ajax/load#urldatacallback jQuery load function .
>
> This works just fine, but now I want to pass all the maps layers to the php
> script, so the php script can use some of the layer properties (name, id,
> visibility, etc.)
>
> I think I have to use json to serialize layer information, but I'm not at
> all sure how to do this in openlayers. I tried:
>
> [CODE]
> var layers_json = openlayers.format.json.write(map.layers);
> jQuery("#modules").load("/geoviewer/includes/legend.php", {layers:
> layers_json});
>
> And in the php:
> if (isset($_REQUEST['layers'])) {
> $layers = json_decode($_REQUEST['layers']);
> }
> for ($intCounter = 0; $intCounter < count($layers); $intCounter++) {
> echo($layers[$intCounter]->{'name'});
> }
> [/CODE]
>
> However, this doesn't work at all. :-)
>
>
>
> Could someone get me on track with this?
>
Serializing a layer with OpenLayers.Format.JSON.write does not work
because of circular references (e.g. the layer has a map property, which
again references the layer in its layers array).
To make this work, you have to make sure that Format.JSON.write does not
serialize OpenLayers class instances:
// store the original serialize.object function
var serializeObject = OpenLayers.Format.JSON.prototype.serialize["object"];
var f = new OpenLayers.Format.JSON();
// create a new serialize.object function
f.serialize["object"] = function(object) {
if(object.CLASS_NAME && f.level > 1) {
return object.id;
}
// call the original serialize.object function
return serializeObject.call(f, object);
}
Now you can just say
var layers_json = f.write(map.layers);
Hope this helps.
Regards,
Andreas.
>
>
> Thanks a lot in advance for any help! It would be greatly appreciated.
>
> Best regards,
> Martijn Senden.
>
--
Andreas Hocevar
OpenGeo - http://opengeo.org/
Expert service straight from the developers.
More information about the Users
mailing list