Playing with buildign blocks - Creating JavaScript Web Services¶
Introduction¶
This section illustrate how you can use JavaScript on the server-side to chain services together to build new ones. You will create a ZOO Services Provider using the services you seen before and the WFS server using the ZOO-API. The final goal is to query all POIs included in a buffer around a feature and to highlight them using a mask around this buffer. The following screenshot show you the expected result:
For the routing interface result should look like this:
You can decompose the result above in two different ones: the mask around the
buffer and the points included in the buffer. So you will create two different
Services: one called BufferMask
and another one called BufferRequest
.
But before implementing any JavaScript Service, you will get an overview of how to use ZOO-API from your ZOO-Project installation in the next section.
As before, you first create a new directory to store files for your new Services Provider:
mkdir -p ~/zoo-ws/jschains/cgi-env/
ZOO-API Overview¶
ZOO-API and ZOO-Kernel JavaScript support make you able to run services implemented in JavaScript on the server side. JavaScript is a popular programing language but mostly used on the client side. Let say from a browser, but here it is a bit different.
To support JavaScript language ZOO-Kernel use the
SpiderMonkey API to create a
javascript runtime environment from which it will load your JS file then extract
the function corresponding to the service to run it using the prefilled
parameters. The JavaScript runtime environment created by the ZOO-Kernel
depend on your setup. If you placed the ZOO-api.js
and ZOO-proj4js.js
in
the same directory as your ZOO-Kernel it means that your environment will
contains ZOO-API and Proj4js which will be loaded before your service. In such case you can access to the Classes defined in the JavaScript ZOO-API
to manipulate geographic data, for more informations please refer to the
ZOO-API Documentation.
Even if it can be useful to run JavaScript on the server side, you should
remember that some basic JavaScript functions you are familiar with does not
exist or get a different behavior. For instance the simple alert
function will display messages in apache error logs rather than in a window when
used from a browser. The alert
function can be used as follow:
alert("My alert message");
There is no XMLHttpRequest available in the JavaScript evironement your service
will run into. Hopefully, the ZOO-Kernel expose a C function to the JavaScript
world named: JSRequest
. This function make you able from your JavaScript
services to call other WPS services (locally or remotelly) or other kind OGC
services such as WFS. When you are using the ZOO-API it is possible to call
Services using a ZOO.Process
instance [1], to parse WPS Responses using
ZOO.Format.WPS
(cf. ref).
As for Python services you already seen in previous sections, the functions
corresponding to a Service should take three arguments: conf
, inputs
and
outputs
[2]. Nevertheless, as the ZOO-Kernel is not able to access the
values modified [3] by the Service code, rather than returning an integer as
in Python, here you’ll need to return both the integer value representing the
Status of your Service in a JavaScript Object and the resulting outputs
values as an Object [4]. You can see in the following an example of a JavaScript
Service code:
function SampleService(conf,inputs,outputs){
var resultValue=someComputation(inputs);
return
{
result: ZOO.SERVICE_SUCCEEDED,
outputs: { "Result": { "mimeType": "application/json", "value": resultValue } }
};
}
Before starting to implement the Services we will need to get our final BufferRequest service, let start with a simplier one.
The Mask Service¶
In this section you will learn how to create your first JavaScript service which will simply return a rectangular mask around a selected feature. To build this mask you will use the Buffer service to create a buffer big enough around a selected geometry to cover a significant part of your map. You can see the expected result in the following screenshot:
As before, you will first start by writting the ZCFG, then you will write the JavaScript source code and finish by publishing your Services Provider.
The ZCFG¶
Open a file named
~/zoo-ws/jschains/cgi-env/Mask.zcfg
with your favorite text editor and add the following content:
1[Mask]
2 Title = Compute mask
3 Abstract = Compute mask around a geometry
4 processVersion = 1
5 storeSupported = true
6 statusSupported = true
7 serviceProvider = foss4gws.js
8 serviceType = JS
9 <DataInputs>
10 [InputData]
11 Title = The feature
12 Abstract = The feature to run the service with
13 minOccurs = 1
14 maxOccurs = 1
15 <ComplexData>
16 <Default>
17 mimeType = text/xml
18 encoding = utf-8
19 </Default>
20 </ComplexData>
21 </DataInputs>
22 <DataOutputs>
23 [Result]
24 Title = The resulting feature
25 Abstract = The feature created by the service.
26 <ComplexOutput>
27 <Default>
28 mimeType = application/json
29 </Default>
30 </ComplexOutput>
31 </DataOutputs>
Here you simply define one default ComplexData
for both inputData
and
Result
: a GML and a GeoJSON respectively [5].
The JavaScript service¶
As you will have to request the Buffer service many times from your service, you
will first define a Buffer
function as follow. It uses the ZOO.Process
to request the Buffer service you seen in the previous section.
Open a file named
~/zoo-ws/jschains/cgi-env/foss4gws.js
and
add the following content:
1var zoo_url='http://localhost/cgi-bin/zoo_loader.cgi';
2var mapfile="/var/data/maps/project_WS2014.map";
3var mapserv_url="http://localhost/cgi-bin/mapserv?map="+mapfile;
4
5function Buffer(inputData,bDist){
6
7 // Create all required ZOO.formats
8 var fJ=new ZOO.Format.JSON();
9 var fGJ=new ZOO.Format.GeoJSON();
10 var fWPS=new ZOO.Format.WPS();
11
12 // Pass the value as json
13 var myInputs = {
14 InputPolygon: { type: 'complex', value: fGJ.write(inputData), mimeType: "application/json"},
15 BufferDistance: {type: 'float', "value": bDist }
16 };
17 var myOutputs= { Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
18 var myProcess = new ZOO.Process(zoo_url,'BufferPy');
19 var myExecuteResult=myProcess.Execute(myInputs,myOutputs);
20
21 return fGJ.read(myExecuteResult);
22
23}
From line 12 to 16, you give a GeoJSON string (created from inputData
) for
InputPolygon and, on line 15, you set the BufferDistance value to bDist
.
On line 17, you define Result as a RawDataOutput, so you won’tl have to parse the
WPS response using the ZOO.Format.WPS.
On line 18, you create a ZOO.Process instance providing the ZOO-Kernel url and the Service name. Then, on line 19, you run the request passing inputs and outputs previously defined (from line 12 to 15). On line 21 you return the GeoJSON red.
Now, you get your Buffer
function, it is time to create your first JavaScript
service. So, edit your foss4gws.js
file you created before and add the following content:
1function Mask(conf,inputs,outputs){
2
3 // Create all required ZOO.formats
4 var fGML=new ZOO.Format.GML();
5 var fGJ=new ZOO.Format.GeoJSON();
6
7 // Read the input GML
8 var inputData=fGML.read(inputs["InputData"]["value"]);
9
10 // Compute Buffer
11 var bufferResultAsJSON=Buffer(inputData,0.015);
12
13 // Create the Buffer result BBOX and store its geometry in a ZOO.Feature
14 var bbox = new ZOO.Bounds();
15 var bounds=bufferResultAsJSON[0].geometry.getVertices();
16 for(var t in bounds){
17 bbox.extend(bounds[t]);
18 }
19 var finalG=bbox.toGeometry();
20 var result=new ZOO.Feature(finalG,{"name": "Result1000"});
21
22 // Return the created feature
23 return {
24 result: ZOO.SERVICE_SUCCEEDED,
25 outputs: { "Result": { mimeType: "application/json", value: fGJ.write(result) } }
26 };
27
28}
Publish and use your Service¶
Now you get both your ZCFG and your service code ready, you need to deploy your new Services Provider using the following command:
sudo cp ~/zoo-ws/jschains/cgi-env/* /usr/lib/cgi-bin
Now you are ready to use your JavaScript service by loading the following url, click on a street then click on the “Mask” button.
BufferMask Service¶
In this section you will implement a simple JavaScript service which will be able create a hole in the mask you created in previous section. This service will be used to highlight the buffer zone around a selected fature. You get a preview of the expected result in the following screenshot:
The ZCFG¶
Open the file named
~/zoo-ws/jschains/cgi-env/BufferMask.zcfg
with your favorite text editor and copy / paste the following content:
1[BufferMask]
2 Title = Compute buffer mask
3 Abstract = Compute buffer mask around a geometry
4 processVersion = 1
5 storeSupported = true
6 statusSupported = true
7 serviceProvider = foss4gws.js
8 serviceType = JS
9 <DataInputs>
10 [InputData]
11 Title = The feature
12 Abstract = The feature to run the service with
13 minOccurs = 1
14 maxOccurs = 1
15 <ComplexData>
16 <Default>
17 mimeType = text/xml
18 encoding = utf-8
19 </Default>
20 </ComplexData>
21 </DataInputs>
22 <DataOutputs>
23 [Result]
24 Title = The resulting feature
25 Abstract = The feature created by the service.
26 <ComplexOutput>
27 <Default>
28 mimeType = application/json
29 </Default>
30 </ComplexOutput>
31 </DataOutputs>
This ZCFG is similar to the previous one. Please, refer to comments in the previous section for more informations.
The JavaScript service¶
In this Service you will use same source code (until line 19) you used in the previous section. Indeed, you should compute the Mask as you did before then compute Buffer for creating a hole in the mask (on line 22) to run the Difference service (from line 25 to 40).
1 function BufferMask(conf,inputs,outputs){
2
3 // Create all required ZOO.formats
4 var fGML=new ZOO.Format.GML();
5 var fGJ=new ZOO.Format.GeoJSON();
6
7 // Read the input GML
8 var inputData=fGML.read(inputs["InputData"]["value"]);
9
10 // Compute Buffer
11 var bufferResultAsJSON=Buffer(inputData,0.015);
12
13 // Create the Buffer result BBOX
14 var bbox = new ZOO.Bounds();
15 var bounds=bufferResultAsJSON[0].geometry.getVertices();
16 for(var t in bounds){
17 bbox.extend(bounds[t]);
18 }
19 var finalG=bbox.toGeometry();
20
21 // Compute Buffer standard buffer
22 var bufferResultAsJSON=Buffer(inputData,0.0015);
23
24 // Request Difference service using Buffer result and features in the BBOX
25 var result=new ZOO.Feature(finalG,{"name": "Result1000"});
26 var myProcess2 = new ZOO.Process(zoo_url,'DifferencePy');
27 var myInputs2 = {
28 InputEntity1: {
29 type: 'complex',
30 value: fGJ.write(finalG),
31 mimeType: "application/json"
32 },
33 InputEntity2: {
34 type: 'complex',
35 value: fGJ.write(bufferResultAsJSON),
36 mimeType: "application/json"
37 }
38 };
39 var myOutputs2= {Result: {type: 'RawDataOutput', mimeType: "application/json" } };
40 var myExecuteResult4=myProcess2.Execute(myInputs2,myOutputs2);
41
42 // Return the bbox
43 var result=new ZOO.Feature(finalG,{"name": "Result1000"});
44 return {
45 result: ZOO.SERVICE_SUCCEEDED,
46 outputs: { "Result": {mimeType: "application/json", value: myExecuteResult4 } }
47 };
48
49 }
Publish and use your Service¶
Now, you can publish your service as you did before. To use your service, please use the following url.
BufferRequest service¶
In this section, you will create a new Service: BufferRequest
which will request
POIs included in the Buffer around a selected feature [6]. You will use the poi
layer served as WFS through your local mapserver installation. You can see in the
following screenshot the expected result:
The ZCFG¶
Open the file named
~/zoo-ws/jschains/cgi-env/BufferRequest.zcfg
with your favorite text editor and copy / paste the following content:
1[BufferRequest]
2 Title = Compute buffer request
3 Abstract = Compute buffer request around a geometry
4 processVersion = 1
5 storeSupported = true
6 statusSupported = true
7 serviceProvider = foss4gws.js
8 serviceType = JS
9 <DataInputs>
10 [InputData]
11 Title = The feature
12 Abstract = The feature to run the service with
13 minOccurs = 1
14 maxOccurs = 1
15 <ComplexData>
16 <Default>
17 mimeType = text/xml
18 encoding = utf-8
19 </Default>
20 </ComplexData>
21 </DataInputs>
22 <DataOutputs>
23 [Result]
24 Title = The resulting feature
25 Abstract = The feature created by the service.
26 <ComplexOutput>
27 <Default>
28 mimeType = application/json
29 </Default>
30 </ComplexOutput>
31 </DataOutputs>
The JavaScript code¶
As in the previous Service, you will compute a buffer around the input feature. But then
you will request POIs available in the Buffer extent using a WFS request to use them to
run Intersection
service using the initial Buffer. The WFS request is useful to limit
the number of points to use when requesting the Intersection
Service.
1function BufferRequest(conf,inputs,outputs){
2
3 // Create all required ZOO.formats
4 var fGJ=new ZOO.Format.GeoJSON();
5 var fGML=new ZOO.Format.GML();
6
7 // Read the input GML
8 var inputData=fGML.read(inputs["InputData"]["value"]);
9
10 // Compute Buffer
11 var bufferResultAsJSON=Buffer(inputData,0.0015);
12
13 // Create the Buffer result BBOX
14 var bbox = new ZOO.Bounds();
15 var bounds=bufferResultAsJSON[0].geometry.getVertices();
16 for(var t in bounds){
17 bbox.extend(bounds[t]);
18 }
19
20 // Request Intersection service using Buffer result and WFS request using the
21 // BBOX
22 var myProcess2 = new ZOO.Process(zoo_url,'Intersection');
23 var req="&SERVICE=WFS&version=1.0.0&request=GetFeature&typename=poi1";
24 req+="&SRS=EPSG:4326&BBOX=";
25 var myInputs2 = {
26 InputEntity1: {
27 type: 'complex',
28 value: fGJ.write(bufferResultAsJSON),
29 mimeType: "application/json"
30 },
31 InputEntity2: {
32 type: 'complex',
33 xlink: mapserv_url+req+bbox.left+","+bbox.bottom+","+bbox.right+","+bbox.top,
34 mimeType: "text/xml"
35 }
36 };
37 var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
38 var myExecuteResult4=myProcess2.Execute(myInputs2,myOutputs2);
39
40 return {
41 result: ZOO.SERVICE_SUCCEEDED,
42 outputs: [ {name:"Result", mimeType: "application/json", value: myExecuteResult4} ]
43 };
44
45}
Warning
to take advantage of the ZOO-Kernel cache system, you directly use the WFS
request as xlink:href
rather than value for InputEntity2
(from line 31 to 34) and use text/xml
mimeType
(on line 40). Indeed, the ZOO-API doesn’t use the internal cache mechanisms.
Publish and use your Service¶
Now, you can publish your service as you did before. To use your service, please use the following url.
Note
You can click on “Buffer Request and Mask” to get the same result as presented in the initial screenshot.
Add Union into the chain¶
As you can see in the following screenshot, when using the Buffer service using a feature collection containing more than one geometry, the result is made of multiple geometries. So, running Buffer service on the routing interface will result in multiple buffer:
So, to get the same result as you got when selecting a single
road, you should use Union of geometry (input or the one outputed by the
Buffer
Service). As you are using the JavaScript ZOO-API, you can
simply update the Buffer
JavaScript function you defined earlier, to
first call the Union of each geometry avaible in a feature collection
prior to request (or after requesting) the Buffer Service. Hopefully,
there is already this Python Service available, its name is
UnionOne1
, so you just need to add it in your Service chain.
Here is the final code for the Buffer JavaScript function:
1function Buffer(inputData,bDist){
2
3 // Create all required ZOO.formats
4 var fJ=new ZOO.Format.JSON();
5 var fGJ=new ZOO.Format.GeoJSON();
6 var fWPS=new ZOO.Format.WPS();
7
8 // Call the UnionOne1 Service
9 var myInputs0 = {
10 InputPolygon: { type: 'complex', value: fGJ.write(inputData), mimeType: "application/json"},
11 BufferDistance: {type: 'float', "value": bDist }
12 };
13 var myOutputs0= { Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
14 var myProcess0 = new ZOO.Process(zoo_url,'UnionOne1');
15 var myExecuteResult0=myProcess0.Execute(myInputs0,myOutputs0);
16
17 // Call the BufferPy Service
18 var myInputs = {
19 InputPolygon: { type: 'complex', value: myExecuteResult0, mimeType: "application/json"},
20 BufferDistance: {type: 'float', "value": bDist }
21 };
22 var myOutputs= { Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
23 var myProcess = new ZOO.Process(zoo_url,'BufferPy');
24 var myExecuteResult=myProcess.Execute(myInputs,myOutputs);
25
26 return fGJ.read(myExecuteResult);
27
28}
Conclusion¶
After understanding how basic Geometric Operation Services works, here you built step by step new JavaScript services which reuse the previous ones and combine them in different ways. This was achieved using the ZOO-API, composed by C functions exposed by the ZOO-Kernel to the JavaScript services runtime environement and the JS files which can be optionally installed.
Footnotes