Friday, 29 December 2017

Programatically export Openlayers maps to static image file


As far as I understand this example from the OpenLayers page and the linked source code for this example, OpenLayers3 now has the offical ability to save maps as static image files.


However, the saving is done via a button on the website (and I do not fully understand how as I am not too much into Javascript).


Is there also a possibility to do this programatically in the following way?




  1. Programatically create a webpage with an embedded OpenLayers3 map, displaying data from whatever sources

  2. Export the webpage's canvas (all layers that would be displayed when opening the page in a browser) into a static image file


I think that creating the webpage would not be that difficult. However, the question is more on whether it is possible to use the exporting without a clickable button but by calling it via a script, command-line or similar.


I did some testing with this approach using PhantomJS to save a screenshot of the webpage. However, I have not managed yet to get this working properly (map object from my webpage not found, when found then rendering is started before all tiles have been loaded, size parameters are ignored.




Removed the OpenLayers3 dependency from the title, solutions using OpenLayers2 are also welcome.



Answer



Are you using GeoServer as a backend?
You could construct a GetMap request via JavaScript and use a HTML GET request to get that image.

I use this same approach to programmatically embed static maps into reports in Ms-Access.

EDIT:
I use PostgreSQL to store my data, and GeoServer handles the rendering and serving of that data.
To embed static maps in Ms-Access reports I first get the BoundingBox of the area I'd like a map of. This is done purely in SQL via a custom function to query my PostgreSQL database.
You could get the same answers using ol.extent and its methods (e.g. ol.extent.getBottomLeft()) to get your BoundingBox.

Here is my VBA Code constructing the request.


    GetMapString = "http://" + GeoServerHost + "/geoserver/wms?request=GetMap&service=WMS&version=1.1.3" & _
"&layers=" + GeoServerWorkspace + ":" + LayerName & _
"&styles=" & _
"&srs=EPSG:27700" & _
"&bbox=" & x1 & "," & y1 & "," & x2 & "," & y2 & _
"&width=1200&height=1200" & _

"&format_options=dpi:300;antialiasing:on" & _
"&format=image%2Fpng8"

Building an equivalent GetMapString in JavaScript, then sending that with the HTML GET request, should return a PNG8 image.
Be sure to check & change the SRS parameter as you probably wouldn't want your image projected in British National Grid.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...