Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015 .

122
Spatial Databases: Lecture 9 Web Spatial Databases: Lecture 9 Web Mapping Mapping DT211-4, DT228-4, MSc DT211-4, DT228-4, MSc Semester 2 2015 Semester 2 2015 http://www.archaeology.ie/smrmapviewer/mapviewer.aspx http://spatial.dcenr.gov.ie/imf/imf.jsp?site=GeoUrban http://www.dublindashboard.ie/pages/MappedDublinRegion http://maps.osi.ie/publicviewer/#V1,588882,739883,0,10 http://census.cso.ie/sapmap/

Transcript of Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015 .

Page 1: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Spatial Databases: Lecture 9 Web MappingSpatial Databases: Lecture 9 Web Mapping

DT211-4, DT228-4, MSc DT211-4, DT228-4, MSc Semester 2 2015Semester 2 2015

http://www.archaeology.ie/smrmapviewer/mapviewer.aspx

http://spatial.dcenr.gov.ie/imf/imf.jsp?site=GeoUrban

http://www.dublindashboard.ie/pages/MappedDublinRegion

http://maps.osi.ie/publicviewer/#V1,588882,739883,0,10

http://census.cso.ie/sapmap/

Page 2: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

W3C and locationW3C and location Location and geographical properties of resources has Location and geographical properties of resources has

always been something of a dilemma for the World Wide always been something of a dilemma for the World Wide Web, which has served so well to unlink the global Web, which has served so well to unlink the global identity of a resource from its physical location on the identity of a resource from its physical location on the globe. One of the Web's greatest values is its capacity globe. One of the Web's greatest values is its capacity for enabling the growth of communities which are not for enabling the growth of communities which are not constrained by distance and geography. Nonetheless, constrained by distance and geography. Nonetheless, physical location is at least an essential property if not a physical location is at least an essential property if not a part of the identity of any real entity. When appropriate, part of the identity of any real entity. When appropriate, the Local Web of resources identified by location and the Local Web of resources identified by location and geography is an essential aspect of Web discovery and geography is an essential aspect of Web discovery and communicationcommunication..

Joshua Lieberman, Geospatial Incubator Group Chair, Joshua Lieberman, Geospatial Incubator Group Chair, 2007/10/3, 2007/10/3, http://www.w3.org/2005/Incubator/geo/http://www.w3.org/2005/Incubator/geo/

Page 3: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Spatial Databases must integrate Spatial Databases must integrate with other applications and data.with other applications and data.

Map Renderer

Network

Wireless Mobile

Devices

HTML Viewer Java Viewer GIS Desktop

Applications

Custom Applications

Spatial DB

(Internet)

Server Side Applications

Page 4: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OutlineOutline Question: What need to be done to allow geographic Question: What need to be done to allow geographic

data to be available on the Web? data to be available on the Web? Answer: A lot!Answer: A lot! The a typical Open Geo-Stack:The a typical Open Geo-Stack:

PostGIS for persistence: We need some structured way to hold PostGIS for persistence: We need some structured way to hold spatial & non-spatial data.spatial & non-spatial data.

Geoserver for server side map specific function WMS,WFS.Geoserver for server side map specific function WMS,WFS. OpenLayers for client side programming to handle user interaction.OpenLayers for client side programming to handle user interaction.

A A web serviceweb service (WS) is a software system designed to (WS) is a software system designed to support interoperable machine-to-machine interaction support interoperable machine-to-machine interaction over a network (W3C). A WS is any service that is over a network (W3C). A WS is any service that is available over the Internet, uses a standardized XML available over the Internet, uses a standardized XML messaging system, and isn't tied to any one operating messaging system, and isn't tied to any one operating system or programming language.system or programming language.

Page 5: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Typical web mapping Typical web mapping configurationconfiguration

Page 6: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web ServicesWeb Services

The W3C defines a Web service as a software The W3C defines a Web service as a software system designed to support interoperable system designed to support interoperable machine-to-machine interaction over a network. machine-to-machine interaction over a network. It has an interface described in a machine-It has an interface described in a machine-processable format (specifically WSDL). Other processable format (specifically WSDL). Other systems interact with the Web service in a systems interact with the Web service in a manner prescribed by its description using manner prescribed by its description using SOAP messages, typically conveyed using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction HTTP with an XML serialization in conjunction with other Web-related standards.with other Web-related standards.

Page 7: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping The principle OGC web services are;The principle OGC web services are; WMS;WMS; standardizes the display of standardizes the display of map imagesmap images. WMS . WMS

can register and overlay maps from multiple remote can register and overlay maps from multiple remote sources.sources.

WFS-T: WFS-T: standardizes the retrieval and update of standardizes the retrieval and update of featuresfeatures..

WPS: WPS: can describe calculations or processes (inputs and can describe calculations or processes (inputs and outputs, triggers, execution) as a Web Service. The outputs, triggers, execution) as a Web Service. The processes can be supplied by a GIS (e.g. GRASS or processes can be supplied by a GIS (e.g. GRASS or special API) special API)

WCS: WCS: standardizes access to spatially extended standardizes access to spatially extended coverages, usually encoded in a binary format and coverages, usually encoded in a binary format and offered by a server (typically remotely sensed data).offered by a server (typically remotely sensed data).

Page 8: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping

Web services have reached a level of Web services have reached a level of sophistication that facilitates the delivery sophistication that facilitates the delivery and use of spatial information. and use of spatial information. Web Web services for mapping enable sharing services for mapping enable sharing information.information.

Web services for mapping allow Web services for mapping allow consumers and providers of information to consumers and providers of information to integrate diverse data sets.integrate diverse data sets.

Page 9: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping

To access remote data we need specific To access remote data we need specific knowledge about that data source: knowledge about that data source: server server addressaddress, , data layers availabledata layers available, , meta-datameta-data, , required and available required and available data formatdata format. .

Once the system knows the details, application Once the system knows the details, application can request exactly maps and other informationcan request exactly maps and other information

We will GeoServer as our map server.We will GeoServer as our map server. Another popular open source map server is Another popular open source map server is

simply called MapServer (http://mapserver.org/)simply called MapServer (http://mapserver.org/)

Page 10: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping

The course web site list many examples of The course web site list many examples of data sharing. Many of the links show how data sharing. Many of the links show how government departments share data with government departments share data with the public and other departments. Which the public and other departments. Which means data users don't need to store their means data users don't need to store their data locally. In many cases centralizing data locally. In many cases centralizing data storage can lead to cost savings and data storage can lead to cost savings and avoid redundancy. Web services for avoid redundancy. Web services for mapping can facilitate mapping can facilitate integrationintegration, , centralizationcentralization and and sharingsharing..

Page 11: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC Web Map Service (WMS)OGC Web Map Service (WMS)

The OpenGIS® Web Map Service Interface Standard The OpenGIS® Web Map Service Interface Standard (WMS) provides a simple HTTP interface for requesting (WMS) provides a simple HTTP interface for requesting geo-registered map images from one or more distributed geo-registered map images from one or more distributed geospatial databases. A WMS request defines the geospatial databases. A WMS request defines the geographic layer(s) and area of interest to be processed. geographic layer(s) and area of interest to be processed. The response to the request is one or more geo-The response to the request is one or more geo-registered map images (returned as JPEG, PNG, etc) registered map images (returned as JPEG, PNG, etc) that can be displayed in a browser application. The that can be displayed in a browser application. The interface also supports the ability to specify whether the interface also supports the ability to specify whether the returned images should be transparent which allows returned images should be transparent which allows layers from multiple servers can be combined.layers from multiple servers can be combined.

Page 12: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGS’s featuresOGS’s features Feature associated with a location relative to the Earth. Feature associated with a location relative to the Earth.

The starting point for modeling of geographic The starting point for modeling of geographic information. A feature is an abstraction of a real world information. A feature is an abstraction of a real world phenomenon. A geographic feature is a feature phenomenon. A geographic feature is a feature associated with a location relative to the Earth. A digital associated with a location relative to the Earth. A digital representation of the real world can be thought of as a representation of the real world can be thought of as a set of features. set of features.

Geographic features occur at two levels: feature Geographic features occur at two levels: feature instances and feature types. At the instance level, a instances and feature types. At the instance level, a geographic feature is represented as a discrete geographic feature is represented as a discrete phenomenon that is associated with its geographic and phenomenon that is associated with its geographic and temporal coordinates. These individual feature instances temporal coordinates. These individual feature instances are grouped into classes with common characteristics - are grouped into classes with common characteristics - feature types.feature types.

Page 13: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC WFSOGC WFS The OGS Web Feature Service Interface Standard (WFS) defines The OGS Web Feature Service Interface Standard (WFS) defines

an interface for specifying requests for retrieving an interface for specifying requests for retrieving geographic geographic featuresfeatures across the Web using platform-independent calls. The across the Web using platform-independent calls. The WFS standard defines interfaces and operations for data access WFS standard defines interfaces and operations for data access and manipulation on a set of geographic features, including:and manipulation on a set of geographic features, including: Get or Query features based on spatial and non-spatial constraintsGet or Query features based on spatial and non-spatial constraints Create a new feature instanceCreate a new feature instance Get a description of the properties of featuresGet a description of the properties of features Delete a feature instance (WFS-T)Delete a feature instance (WFS-T) Update a feature instance (WFS-T)Update a feature instance (WFS-T) Lock a feature instance (WFS-T)Lock a feature instance (WFS-T)

By default, the specified feature encoding for input and output is the By default, the specified feature encoding for input and output is the Geography Markup Language (GML) which in turn is written in XML.Geography Markup Language (GML) which in turn is written in XML.

Page 14: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC WFSOGC WFS

Via the WFS interfaces, a web user or service Via the WFS interfaces, a web user or service can combine, use and manage can combine, use and manage featuresfeatures from from different sources by invoking the following WFS different sources by invoking the following WFS operations on geographic features and operations on geographic features and elements:elements: Create a new feature instanceCreate a new feature instance Delete a feature instanceDelete a feature instance Update a feature instanceUpdate a feature instance Lock a feature instanceLock a feature instance Get or query features based on spatial and non-Get or query features based on spatial and non-

spatial constraintsspatial constraints

Page 15: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC WFSOGC WFS

WFS follows the web services model

Web Services Description Language is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.

Page 16: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC WFSOGC WFS

Basic sequence of events

Page 17: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS 1.1.0WFS 1.1.0 The following is a description of the Web

Feature Service 1.1.0 specification from the Open Geospatial Consortium (OGC). WFS-T is well suited to applications were a user needs to interact with the map data (e.g. select objects, query objects and update objects). We cover: a basic description, the main operations, the basic processing sequence for a simple

request.

Page 18: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Basic description of WFS 1.1.0Basic description of WFS 1.1.0

The Web Feature Service (WFS) is an interface The Web Feature Service (WFS) is an interface specified by the OGC that allows for the exchange of specified by the OGC that allows for the exchange of geographic data across the Web. It defines the rules for geographic data across the Web. It defines the rules for requesting and retrieving geographic information using requesting and retrieving geographic information using the Hyper Text Transmission Protocol (HTTP). The the Hyper Text Transmission Protocol (HTTP). The interface describes the data manipulation operations on interface describes the data manipulation operations on geographic features. Extensible Markup Language geographic features. Extensible Markup Language (XML) -based Geographic Markup Language (GML) is (XML) -based Geographic Markup Language (GML) is used for exchange of information. WFS-T supports the used for exchange of information. WFS-T supports the vector data model.vector data model.

Page 19: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Main Operations of WFS 1.1.0Main Operations of WFS 1.1.0

A WFS implementation allows a client to retrieve and A WFS implementation allows a client to retrieve and update features encoded in GML from multiple servers. update features encoded in GML from multiple servers. The WFS operations support INSERT, UPDATE, The WFS operations support INSERT, UPDATE, DELETE, LOCK, QUERY and DISCOVERY operations. DELETE, LOCK, QUERY and DISCOVERY operations. A g eographic feature is described by a set of properties A g eographic feature is described by a set of properties where each property can be thought of as a {name, type, where each property can be thought of as a {name, type, value} tuple. The name and type of each feature property value} tuple. The name and type of each feature property is determined by its type definition. Geographic features is determined by its type definition. Geographic features are those that may have at least one property that is are those that may have at least one property that is geometry-valued.geometry-valued.

See notes below for further detailSee notes below for further detail

Page 20: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Basic processing sequence for WFS 1.1.0WFS 1.1.0

Page 21: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Additional features of WFS 2.0Additional features of WFS 2.0 Supports temporal queries, versioning, stored queries, joins, and spatial joins Real time flight dispatch scenarios (disruption due to volcanic ash and snow) use WFS 2.0 to

retrieve and update data in real-time via web services (WFS and eventing). Web Feature Service 2.0 used for INSPIRE Compliance. Allows the distribution of data via the

latest web service standard. Integrated data validation - preview and fix XML/GML Temporal queries can improve decision making WFS 2.0 used for INSPIRE data publishing. Discovery operations allow the service to be interrogated to determine its capabilities and to

retrieve the application schema that defines the feature types that the service offers. Query operations allow features or values of feature properties to be retrieved from the

underlying data store based upon constraints, defined by the client, on feature properties. Locking operations allow exclusive access to features for the purpose of modifying or deleting

features. Transaction operations allow features to be created, changed, replaced and deleted from the

underlying data store. Stored query operations allow clients to create, drop, list and described parameterized query

expressions that are stored by the server and can be repeatedly invoked using different parameter values.

Page 22: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping

Data can be shared in a number of ways. A Data can be shared in a number of ways. A complete copy can be given to the remote user complete copy can be given to the remote user allowing them to use the data for any purpose. allowing them to use the data for any purpose. Alternatively, a more limited form of access can Alternatively, a more limited form of access can be granted. For example, users of Google Map be granted. For example, users of Google Map do not get the actual spatial data although they do not get the actual spatial data although they are granted a high degree of usage through the are granted a high degree of usage through the Google Map API. OGC WMS (see later) Google Map API. OGC WMS (see later) provide to bitmap image rather than the vector provide to bitmap image rather than the vector map itself, whereas WFS provides vectors.map itself, whereas WFS provides vectors.

Page 23: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web services for mappingWeb services for mapping

Some spatial data, such as hurricane Some spatial data, such as hurricane locations, is constantly changing locations, is constantly changing (streamed). It does not make sense to (streamed). It does not make sense to download such data. It would be better to download such data. It would be better to integrate the weather layer in your map integrate the weather layer in your map that accesses a web service in realtime. that accesses a web service in realtime.

Web services can make Web services can make very large data very large data setssets available to users, reducing the need available to users, reducing the need for continual data storage upgrades. for continual data storage upgrades.

Page 24: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Requesting a MapRequesting a Map

GeoServer can request map data from a remote web server

Page 25: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Typical web map services software Typical web map services software environmentenvironment

ModJK is the connector used to connect Tomcat servlet container with web servers such as Apache. We use GeoServers servlet container called Jetty and do not need to connect to Apache.

GEOS (Geometry Engine, Open Source) is a library used by PostGIS to perform all the operations in the OpenGIS Simple Features for SQL

Specification.

PROJ.4 is an open source library used by PostgIS to convert between geographic coordinate systems

OpenLayers is a JavaScript library for displaying map data in a web browser. We will look at OpenLayers later

Page 26: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

The OGC Web Service packageThe OGC Web Service package

Page 27: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Client and WFS messagesClient and WFS messages

Page 28: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

A Typical Web Page LayoutA Typical Web Page Layout

Page 29: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

GeoServer’s architecture GeoServer’s architecture

The JTS Topology Suite is an API of 2D spatial predicates and functions.

ArcSDE technology manages spatial data in a relational database management system (RDBMS) and enables it to be accessed by ArcGIS clients. It is the technology that provides the framework to support long transactions, which facilitates the versioned editing environment in multiuser geodatabases.

MapInfo Interchange Format (MIF) is a map and database exporting file format of MapInfo

software product.

Page 30: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

GeoServerGeoServer

GeoServer can access and provide data using a GeoServer can access and provide data using a web services framework.web services framework.

The Open Geospatial Consortium (OGC) has The Open Geospatial Consortium (OGC) has developed developed specificationsspecifications for web services for for web services for mapping. The OGC aim to increase mapping. The OGC aim to increase interoperability between applications by creating interoperability between applications by creating common interchange languages through common interchange languages through common standards. GeoServer common standards. GeoServer implementsimplements OGC’s web mapping services.OGC’s web mapping services.

Page 31: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

GeoServer & OGC specifications GeoServer & OGC specifications

Web Map Service (WMS) Share and request vector and raster map Web Map Service (WMS) Share and request vector and raster map data in plain image formatdata in plain image format

Web Feature Service (WFS) Share and request vector map data Web Feature Service (WFS) Share and request vector map data and attributes in GML formatand attributes in GML format

Web Feature Service Web Feature Service –Transactional (WFS-T ) is a WFS that –Transactional (WFS-T ) is a WFS that supports transactions - add, delete, or update features.supports transactions - add, delete, or update features.

Web Coverage Service (WCS) Share image/raster data with original Web Coverage Service (WCS) Share image/raster data with original data valuedata value

Web Map Context (WMC) Save and load views of a WMS Web Map Context (WMC) Save and load views of a WMS application as XMLapplication as XML

Styled Layer Descriptors (SLD) Request particular symbolization Styled Layer Descriptors (SLD) Request particular symbolization and styling from a WMS and styling from a WMS

Geography Markup Language (GML) XML-based format for spatial Geography Markup Language (GML) XML-based format for spatial and tabular data interchangeand tabular data interchange

Filter: Encoding XML-based format for defining queries on spatial Filter: Encoding XML-based format for defining queries on spatial datadata

Page 32: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

GeoServer & OGC specifications GeoServer & OGC specifications

GeoServer 1.6.0 and above supports WFS 1.1 GeoServer 1.6.0 and above supports WFS 1.1 WFS 1.1 supports on the fly re-projection of data, WFS 1.1 supports on the fly re-projection of data, which which

means data can be returned in a SRS other than the means data can be returned in a SRS other than the native one. We can check the WFS version as follows:native one. We can check the WFS version as follows:

http://localhost:8080/geoserver/wfs?request=GetCapabilities&service=WFS&version=1.0.0http://localhost:8080/geoserver/wfs?request=GetCapabilities&service=WFS&version=1.0.0

Here is the XML for the reference systemHere is the XML for the reference system <SRS>EPSG:4326</SRS><SRS>EPSG:4326</SRS>

Page 33: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Required WMS parameters for a Required WMS parameters for a GetMap requestGetMap request

Page 34: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 35: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Serving static files within Serving static files within GeoserverGeoserver

On Geoserve static web files are stored in On Geoserve static web files are stored in the www subfolder of the GeoServer data the www subfolder of the GeoServer data directory, and they are served at directory, and they are served at http:/myhost:8080/geoserver/www. http:/myhost:8080/geoserver/www.

In the www folder you can store html, In the www folder you can store html, images and Javascript and have images and Javascript and have Geoserver provide them on the web with Geoserver provide them on the web with AJAX callbacks.AJAX callbacks.

Page 36: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Using Servlets with GeoServerUsing Servlets with GeoServer

Geoserver uses Jetty as a servlet container.Geoserver uses Jetty as a servlet container. Jetty is an open-source embeddable web server Jetty is an open-source embeddable web server

and servlet container, written in Java.and servlet container, written in Java. http://www.mortbay.org/jetty/http://www.mortbay.org/jetty/

Jetty can handle Java servlets and Jetty can handle Java servlets and JavaServerPages (JSP) technologies and JavaServerPages (JSP) technologies and traditional static web pages.traditional static web pages.

There is a Jetty Servlet tutorial at:There is a Jetty Servlet tutorial at: http://www.seas.upenn.edu/~cis550/jetty.htmlhttp://www.seas.upenn.edu/~cis550/jetty.html

Page 37: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Using Servlets with GeoServerUsing Servlets with GeoServer

Each GeoServer service is provided by a Each GeoServer service is provided by a specific Servlet that intercepts the client specific Servlet that intercepts the client requests and builds up the response in requests and builds up the response in accordance to the GeoServer accordance to the GeoServer configuration.configuration.

Geoserver can be deployed as a standard Geoserver can be deployed as a standard WAR package inside Java Servlet WAR package inside Java Servlet containers.containers.

Page 38: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Configuration InterfaceConfiguration Interface

Page 39: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 40: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Managing a Geographic Database Managing a Geographic Database From Mobile Devices Through From Mobile Devices Through

OGC Web ServicesOGC Web Services

Page 41: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

The OGS’s Spatial WebThe OGS’s Spatial Web

Universal Description, Discovery and Integration (UDDI) is a platform-independent, XML-based registry for businesses worldwide to list themselves on the Internet.

Page 42: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

The OGS’s Spatial WebThe OGS’s Spatial Web

Page 43: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web Feature ServiceWeb Feature Service

•A WFS must implement the following operations: •GetCapabilities - queries the WFS service to determine available options.•DescribeFeatureType - retrieves the XML schema to allow the WFS client to parse the result sets.•GetFeature - performs the actual query - parameters such as bounding box and any other filters should be passed in, as appropriate, and the WFS service then returns a GML result set containing full geometry and feature attributes.

Page 44: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 45: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 46: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

Page 47: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

Page 48: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

OpenLayers (OL) is an open source JavaScript library OpenLayers (OL) is an open source JavaScript library for displaying map data in web browsers. OL provides an for displaying map data in web browsers. OL provides an API for building complex web-based geographic API for building complex web-based geographic applications. Data can be combined from a number of applications. Data can be combined from a number of sources without requiring any server side processing as sources without requiring any server side processing as layers can be assembled and rendered on the client. layers can be assembled and rendered on the client. Client side programming includes panning and zooming Client side programming includes panning and zooming of maps, client-side tiling, markers, popup windows, of maps, client-side tiling, markers, popup windows, various adjustable navigation components, keyboard various adjustable navigation components, keyboard commands, an event handling mechanism and client commands, an event handling mechanism and client server communications. Each part of OL is configurable. server communications. Each part of OL is configurable. OL can act as a Web Client for Geoserver.OL can act as a Web Client for Geoserver.

See; See; http://www.bostongis.com/?content_name=openlayers_tut_01http://www.bostongis.com/?content_name=openlayers_tut_01

Page 49: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers<html><html><head><head><script type='text/javascript'><script type='text/javascript'> function drawOnCanvas() {function drawOnCanvas() { var canvas = document.getElementById('example');var canvas = document.getElementById('example'); var context = canvas.getContext('2d');var context = canvas.getContext('2d'); context.fillStyle = 'red';context.fillStyle = 'red'; context.fillRect(10, 10, 50, 50);context.fillRect(10, 10, 50, 50); }}</script></script></head></head><body onload='drawOnCanvas()'><body onload='drawOnCanvas()'><canvas id='example' width='512' height='256'><canvas id='example' width='512' height='256'></canvas></canvas></body></body></html></html>See : http://localhost:8080/geoserver/www/box/htmlSee : http://localhost:8080/geoserver/www/box/htmlhttp://147.252.234.32:8080/geoserver/www/box.htmlhttp://147.252.234.32:8080/geoserver/www/box.html

Page 50: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

SQL OpenLayersSQL OpenLayers

get: function(key) {get: function(key) {             var name = this.name;var name = this.name; this.db.transaction( this.db.transaction(   function(tx) {          function(tx) {           console.log("Select value from OLTable where key=?");console.log("Select value from OLTable where key=?"); tx.executeSql("Select value from OLTable where key=?",  [key],           tx.executeSql("Select value from OLTable where key=?",  [key],          

        function(tx, result) {   if(result.rows.length)function(tx, result) {   if(result.rows.length) { return result.rows.item(0).data;1  } }, { return result.rows.item(0).data;1  } }, function(tx, error) { console.debug(error);  }); });   }function(tx, error) { console.debug(error);  }); });   }

Page 51: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

OL can act as a Web Client for:OL can act as a Web Client for:1.1. OGC web services (WFS-T,WMS, and WCS OGC web services (WFS-T,WMS, and WCS

(XML.GML)), (XML.GML)),

2.2. Commercial services such as Google Maps(KML), Commercial services such as Google Maps(KML), MSN Virtual Earth, ESRI products MSN Virtual Earth, ESRI products

3.3. Cpen source initiatives or defacto standards such as Cpen source initiatives or defacto standards such as Geographically Encoded Objects for RSS feeds Geographically Encoded Objects for RSS feeds (GeoRSS). The OL GeoRSS parser will (GeoRSS). The OL GeoRSS parser will automatically connect an information bubble to the automatically connect an information bubble to the map markers, similar to Google maps.map markers, similar to Google maps.

Page 52: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers OL helps integrates a diverse set of heterogeneous data sources OL helps integrates a diverse set of heterogeneous data sources

(e.g. shape file and database). A variation on OL is Mapbulider (e.g. shape file and database). A variation on OL is Mapbulider built into GeoServer which supports OGC WFS and WMS.built into GeoServer which supports OGC WFS and WMS.

OL facilitates a client-side JavaScript "map -mash-up” style OL facilitates a client-side JavaScript "map -mash-up” style application; A mash-up is a Web application that combines data application; A mash-up is a Web application that combines data from one or more sources into a single integrated tool. The term from one or more sources into a single integrated tool. The term Mashup implies easy, fast integration, frequently done by access Mashup implies easy, fast integration, frequently done by access to open APIs and data sources to produce results that were not to open APIs and data sources to produce results that were not the original reason for producing the raw source data. An example the original reason for producing the raw source data. An example of a mashup is the use of cartographic data from Google Maps to of a mashup is the use of cartographic data from Google Maps to add location information to real estate data, thereby creating a add location information to real estate data, thereby creating a new and distinct Web service that was not originally provided by new and distinct Web service that was not originally provided by either source.either source.

Page 53: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

OL can return projection information. A OL can return projection information. A projection is a way of converting geographic projection is a way of converting geographic coordinates (latitude and longitude) into a plane coordinates (latitude and longitude) into a plane (Irish National Grid). (Irish National Grid).

OL supports any projection, but needs PROJ4 OL supports any projection, but needs PROJ4 for OL for projections on the fly. OL can request for OL for projections on the fly. OL can request form map servers data in a particular form map servers data in a particular projection. Strong support for the Spherical projection. Strong support for the Spherical Mercator projection used by Google Map, Open Mercator projection used by Google Map, Open Street Map, and Virtual Earth.Street Map, and Virtual Earth.

Page 54: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayersOpenLayers

Two ways of getting data.Two ways of getting data. In one mode OL can request new data without In one mode OL can request new data without

refreshing an entire document, requests can be refreshing an entire document, requests can be made to any origin. Another way to retrieve made to any origin. Another way to retrieve data from a server is to update the location of a data from a server is to update the location of a document in a frame. These types of requests document in a frame. These types of requests can also be made to any origin. However, the can also be made to any origin. However, the code running in the original document is code running in the original document is restricted to reading data in documents that restricted to reading data in documents that come from the same origin. come from the same origin.

Page 55: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers uses AJAXOpenLayers uses AJAX Underlying technologyUnderlying technology The basic technology is The basic technology is AAsynchronous synchronous JJavaScript avaScript aand nd XXMLML (AJAX) which includes of JavaScript and XML. XML is the W3C (AJAX) which includes of JavaScript and XML. XML is the W3C

recommended standard for creating formats and sharing data on the recommended standard for creating formats and sharing data on the WebWeb

OL normally uses XML for data interchange (though JavaScript OL normally uses XML for data interchange (though JavaScript Object Notation (JSON) can be used as an alternative). Ajax is a Object Notation (JSON) can be used as an alternative). Ajax is a way of developing Web applications that combines:way of developing Web applications that combines:

XHTML and CSS standards based presentationXHTML and CSS standards based presentation Interaction with the page through the DOMInteraction with the page through the DOM Data interchange with XML and XSLTData interchange with XML and XSLT Asynchronous data retrieval with a XMLHttpRequestAsynchronous data retrieval with a XMLHttpRequest object which is object which is

used to read or send data on the server asynchronously.used to read or send data on the server asynchronously. JavaScript to tie it all togetherJavaScript to tie it all together

Page 56: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers uses AJAXOpenLayers uses AJAX

The Ajax interpreter works within the Web browser The Ajax interpreter works within the Web browser (through JavaScript and the DOM) to render the Web (through JavaScript and the DOM) to render the Web application and handle any requests that the user might application and handle any requests that the user might have of the Web server. Because the Ajax runtime is have of the Web server. Because the Ajax runtime is handling the requests, it can hold much of the handling the requests, it can hold much of the information in the Ajax environment, while allowing the information in the Ajax environment, while allowing the interaction with the application and the customer to interaction with the application and the customer to happen asynchronously and independently of any happen asynchronously and independently of any interaction with the server. This allows the browser to interaction with the server. This allows the browser to handle a lot of the map processing locally without handle a lot of the map processing locally without reference to the server e.g. display, rendering, scaling, reference to the server e.g. display, rendering, scaling, querying. querying.

Page 57: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers uses AJAXOpenLayers uses AJAX

Asynchronous data transfers through the XMLHttpRequest object. Asynchronous data transfers through the XMLHttpRequest object. This allows websites to be refreshed in the background instead of This allows websites to be refreshed in the background instead of having to be re-loaded after every modification. Because of this having to be re-loaded after every modification. Because of this technology, a web mapping application is able to execute a user’s technology, a web mapping application is able to execute a user’s command in a fairly short time period, as the necessary steps can command in a fairly short time period, as the necessary steps can be completed in the background. As a result, the usability of be completed in the background. As a result, the usability of interactive web mapping applications is approaching the features of interactive web mapping applications is approaching the features of classic Desktop (GIS) applications. The processing of web page classic Desktop (GIS) applications. The processing of web page formerly was only server-side, using web services or PHP scripts, formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network. But Ajax can before the whole page was sent within the network. But Ajax can selectively modify a part of a page displayed by the browser, and selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all update it without the need to reload the whole document with all images, menus, etc... For example, fields of forms, choices of user, images, menus, etc... For example, fields of forms, choices of user, may be processed and the result displayed immediately into the may be processed and the result displayed immediately into the same page.same page.

Page 58: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers SecurityOpenLayers Security

Browsers execute JavaScript code in a sandbox, a Browsers execute JavaScript code in a sandbox, a sealed environment with little or no access to the sealed environment with little or no access to the computer’s resources. Icomputer’s resources. In general OL uses AJAX security n general OL uses AJAX security features. All communication initiated by OpenLayers. features. All communication initiated by OpenLayers. Request methods are restricted to the same origin Request methods are restricted to the same origin policy: requests may only be issued with the same policy: requests may only be issued with the same protocol, to the same domain, and through the same port protocol, to the same domain, and through the same port as the document the code is running from. This is as the document the code is running from. This is because of the underlying JavaScript security model. because of the underlying JavaScript security model. JavaScript programs have control over their own page JavaScript programs have control over their own page inside the browser, but that is where their abilities end. inside the browser, but that is where their abilities end.

The underlying AJAX security can limit interaction; this The underlying AJAX security can limit interaction; this can be circumvented using proxy server. can be circumvented using proxy server.

Page 59: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Example of OL usageExample of OL usage

<html><html> <head><head> <script src = "<script src = "http://www.openlayers.org/api/OpenLayers.jshttp://www.openlayers.org/api/OpenLayers.js"></script>"></script> <script type = "text/javascript"> <script type = "text/javascript"> function test_Map_Zoom(t) function test_Map_Zoom(t) t.plan(1);t.plan(1); var map = new OpenLayers.Map("map");var map = new OpenLayers.Map("map"); var layer = new OpenLayers.Layer.WMS("ABC", var layer = new OpenLayers.Layer.WMS("ABC", "http://example.com/123", "http://example.com/123", 'layers':'test');'layers':'test'); map.addLayer(layer);map.addLayer(layer); map.zoomTo(0);map.zoomTo(0); t.eq(map.zoom, 0, "Map zoomed to level 0 correctly.");t.eq(map.zoom, 0, "Map zoomed to level 0 correctly."); </script></script> </head> </head> <body><body> <div id="map" style="width: 512px; height: 512px;"/><div id="map" style="width: 512px; height: 512px;"/></body></body></html></html>

Page 60: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Example of OL layersExample of OL layers

Osmarender is a rule-based rendering tool for generating SVG images of OSM data. It takes as its input an OpenStreetMap dataset and a rules file. It outputs an SVG image that is marked up in accordance with the styles defined in the rule file.Mapnik is the Open Source map renderer which we use to render the main Slippy Map layer for OSM. The slippy map is an AJAX component. JavaScript runs in the browser, which dynamically requests tiles from the server in the background (without reloading the whole HTML page) to give a smooth slippy zoomy map browsing experience. The implementation of this is mostly provided by OpenLayers.CycleMap contains cycling specific information, lanes, routes, networks.Cycle routes are named or numbered or otherwise signed routes, which may go along roads or dedicated cycle paths.

Page 61: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Example of OL codeExample of OL codevar DITKevinStreetLat=53.338var DITKevinStreetLon=-6.268var zoom=16var map2; function init() { map2 = new OpenLayers.Map ("map2", { controls:[ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.LayerSwitcher(), maxExtent: new OpenLayers.Bounds(-20037508.34,-0037508.34, 20037508.34,20037508.34), maxResolution: 156543.0399, numZoomLevels: 19, units: 'm', projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326")} ); layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map2.addLayer(layerMapnik); layerCycleMap = new OpenLayers.Layer.OSM.CycleMap("CycleMap"); map2.addLayer(layerCycleMap); var lonLat = new OpenLayers.LonLat(DITKevinStreetL, DITKevinStreetL).transform(new OpenLayers.Projection("EPSG:4326"), map2.getProjectionObject()); map2.setCenter (lonLat, zoom); }

Page 62: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers Core ClassesOpenLayers Core Classes OpenLayers.Map: is the main class of the OpenLayers API. It OpenLayers.Map: is the main class of the OpenLayers API. It

compiles the application's main map and provides numerous compiles the application's main map and provides numerous methods for the methods for the administrationadministration of the map display, including the of the map display, including the display of layers and operating components, zooming and display of layers and operating components, zooming and panning. In addition, this class allows for queries of current map panning. In addition, this class allows for queries of current map status through numerous 'get' methods. status through numerous 'get' methods.

OpenLayers.Layer: All map OpenLayers.Layer: All map displaysdisplays are based on the Layer are based on the Layer class. Layer.js produces individual layers, sets the transparency class. Layer.js produces individual layers, sets the transparency and resolution of each, and provides the basic 'get' methods.and resolution of each, and provides the basic 'get' methods.

OpenLayers.Control: Operating elements in OpenLayers are OpenLayers.Control: Operating elements in OpenLayers are elements related to map navigation as well the display of map elements related to map navigation as well the display of map information (e.g. scale). The Control class serves as a base class information (e.g. scale). The Control class serves as a base class for all operating elements, among them:Ajax avoids the traditional for all operating elements, among them:Ajax avoids the traditional Web client/server/web-page interaction between the customer and Web client/server/web-page interaction between the customer and the server. the server.

Page 63: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers Core ClassesOpenLayers Core Classes OpenLayers.Events: takes over the event handling from OpenLayers.Events: takes over the event handling from

OpenLayers. OpenLayers. OpenLayers.Pixel: displays monitor coordinates in n x- and y- OpenLayers.Pixel: displays monitor coordinates in n x- and y-

pixel values. pixel values. OpenLayers.Size: displays a pixel size value pair in width and OpenLayers.Size: displays a pixel size value pair in width and

height. height. OpenLayers.LonLat: displays geographic coordinates in longitude OpenLayers.LonLat: displays geographic coordinates in longitude

and latitude. and latitude. OpenLayers.Bounds: displays a rectangular area (bounding box) OpenLayers.Bounds: displays a rectangular area (bounding box)

whose four sides (left, below, right, above) are indicated with whose four sides (left, below, right, above) are indicated with geographic coordinates in float format. The Bounds class provides geographic coordinates in float format. The Bounds class provides different get-functions (e.g. center and pixel dimensions of the different get-functions (e.g. center and pixel dimensions of the bounding box) as well as comparative functions (e.g. whether a bounding box) as well as comparative functions (e.g. whether a pixel is located within the defined bounding box). pixel is located within the defined bounding box).

OpenLayers.Util: contains the different functions and settings OpenLayers.Util: contains the different functions and settings which cannot be assigned to any of the other OpenLayers classes.which cannot be assigned to any of the other OpenLayers classes.

Page 64: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenLayers Core ClassesOpenLayers Core Classes OpenLayers.Events: takes over the event handling from OpenLayers.Events: takes over the event handling from

OpenLayers. OpenLayers. OpenLayers.Pixel: displays monitor coordinates in n x- and y- OpenLayers.Pixel: displays monitor coordinates in n x- and y-

pixel values. pixel values. OpenLayers.Size: displays a pixel size value pair in width and OpenLayers.Size: displays a pixel size value pair in width and

height. height. OpenLayers.LonLat: displays geographic coordinates in longitude OpenLayers.LonLat: displays geographic coordinates in longitude

and latitude. and latitude. OpenLayers.Bounds: displays a rectangular area (bounding box) OpenLayers.Bounds: displays a rectangular area (bounding box)

whose four sides (left, below, right, above) are indicated with whose four sides (left, below, right, above) are indicated with geographic coordinates in float format. The Bounds class provides geographic coordinates in float format. The Bounds class provides different get-functions (e.g. center and pixel dimensions of the different get-functions (e.g. center and pixel dimensions of the bounding box) as well as comparative functions (e.g. whether a bounding box) as well as comparative functions (e.g. whether a pixel is located within the defined bounding box). pixel is located within the defined bounding box).

OpenLayers.Util: contains the different functions and settings OpenLayers.Util: contains the different functions and settings which cannot be assigned to any of the other OpenLayers classes.which cannot be assigned to any of the other OpenLayers classes.

Page 65: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

MapbuilderMapbuilder

Mapbuilder is a client-side Javascript library for Mapbuilder is a client-side Javascript library for putting mapping in a web page, using an AJAX putting mapping in a web page, using an AJAX style of interaction. It works by retrieving XML style of interaction. It works by retrieving XML data from the various sources and rendering that data from the various sources and rendering that using the browser's built in XSL processor, so using the browser's built in XSL processor, so the initial HTML page never has to reload. the initial HTML page never has to reload. Server-side requirements are minimal: at Server-side requirements are minimal: at minimum an HTTP server, at most 2 other minimum an HTTP server, at most 2 other server scripts which are provided (for PHP and server scripts which are provided (for PHP and J2EE environments).J2EE environments).

Page 66: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 67: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web Map Context FileWeb Map Context File<ViewContext><General><Window width="500" height="285" /><BoundingBox SRS="EPSG:4326"minx="-179.14734"miny="17.884813"maxx="179.77847000000006"maxy="71.35256064399981" /><Title>g4wd:st99_d00 Map</Title><KeywordList><Keyword>g4wd:st99_d00</Keyword></KeywordList><Abstract></Abstract></General><LayerList><Layer queryable="1" hidden="0" ><Server service="OGC:WMS" version="1.1.1"title="g4wd:st99_d00 Preview" ><OnlineResource xlink:type="simple" xlink:href="../wms" /></Server><Name>g4wd:st99_d00</Name><Title>g4wd:st99_d00</Title><SRS>EPSG:4326</SRS><FormatList><Format current="1" >image/png</Format></FormatList></Layer></LayerList></ViewContext>

Page 68: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web Map Context FileWeb Map Context File

The OGC Web Map Context FileThe OGC Web Map Context File The Context file defines the viewableThe Context file defines the viewable Non-spatial attributes of the map such as Non-spatial attributes of the map such as

the size and the title. It also identifies the the size and the title. It also identifies the data layers that should be included on the data layers that should be included on the map. map.

Page 69: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web Map Context FileWeb Map Context File

The Context file is an OGC standard that The Context file is an OGC standard that can be shared across server can be shared across server implementations. Write this file once, and implementations. Write this file once, and it is reusable from one server to the next.it is reusable from one server to the next.

The newer OWS Context documents The newer OWS Context documents support WFS and WCS layers as well as support WFS and WCS layers as well as WMS layers.WMS layers.

Page 70: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Web Map ContextWeb Map Context

OGS Web Map Context (WMC) Implementation OGS Web Map Context (WMC) Implementation Specification is a companion to the OGC Web Specification is a companion to the OGC Web Map Service, it describes how to save a map Map Service, it describes how to save a map view comprised of many different layers from view comprised of many different layers from different Web Map Servers. A 'context' can be different Web Map Servers. A 'context' can be encoded and saved so that Web maps created encoded and saved so that Web maps created by users can be automatically reconstructed and by users can be automatically reconstructed and augmented by the authoring user or other users augmented by the authoring user or other users in the future. A Context document is structured in the future. A Context document is structured using eXtensible Markup Language (XML).using eXtensible Markup Language (XML).

Page 71: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OGC Web Services (OWS) Context OGC Web Services (OWS) Context DocumentDocument

WMS WMS WMS WMS

VisualizationApplicationor Tool A

VisualizationApplicationor Tool B

Shareable content,session, area ofinterest

Context

Page 72: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPSWPS A WPS can be configured to offer any sort of GIS functionality to A WPS can be configured to offer any sort of GIS functionality to

clients across a network, including access to pre-programmed clients across a network, including access to pre-programmed calculations and/or computation models that operate on spatially calculations and/or computation models that operate on spatially referenced data. A WPS may offer calculations as simple as referenced data. A WPS may offer calculations as simple as subtracting one set of spatially referenced numbers from another subtracting one set of spatially referenced numbers from another (e.g., determining the difference in influenza cases between two (e.g., determining the difference in influenza cases between two different seasons), or as complicated as a global climate change different seasons), or as complicated as a global climate change model. The data required by the WPS can be delivered across a model. The data required by the WPS can be delivered across a network, or available at the server.network, or available at the server.

This interface specification provides mechanisms to identify the This interface specification provides mechanisms to identify the spatially-referenced data required by the calculation, initiate the spatially-referenced data required by the calculation, initiate the calculation, and manage the output from the calculation so that it calculation, and manage the output from the calculation so that it can be accessed by the client. This Web Processing Service is can be accessed by the client. This Web Processing Service is targeted at processing both vector and raster data. targeted at processing both vector and raster data.

Page 73: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPSWPS

Page 74: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPSWPS

http://dev.bnhelp.cz/inspire/client/

Page 75: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenlayersOpenlayers

Page 76: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenlayersOpenlayers

Page 77: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

GeoserverGeoserver

Page 78: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OWSOWS

Page 79: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WMS WFSWMS WFS

Page 80: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WMS WFSWMS WFS

Page 81: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

OpenlayersOpenlayers

Page 82: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Many formats for LayersMany formats for Layers

OGC WFSOGC WFS GeoRSSGeoRSS CSVCSV GMLGML KMLKML WKTWKT

OGC WMS OGC WMS Google MapsGoogle Maps MSN Live MSN Live

LocalLocal Yahoo! MapsYahoo! Maps MultimapMultimap ka-Mapka-Map WorldWindWorldWind

Raster Layers, tiled

Vector Layers, points, lines, polygons

rendered with SVG / VML

Page 83: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPS Operations

GetCapabilities – This operation allows a client to request and receive back service metadata (or Capabilities) documents that describe the abilities of the specific server implementation. The GetCapabilities operation provides the names and general descriptions of each of the processes offered by a WPS instance. This operation also supports negotiation of the specification version being used for client-server interactions.

DescribeProcess – This operation allows a client to request and receive back detailed information about the processes that can be run on the service instance, including the inputs required, their allowable formats, and the outputs that can be produced.

Execute – This operation allows a client to run a specified process implemented by the WPS, using provided input parameter values and returning the outputs produced.

Page 84: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPS Example

Consider the case of a process that can intersect two polygons. The response to a GetCapabilities request might indicate that the WPS supports an operation called ―intersect, and that this operation is limited to intersecting one polygon with a second polygon. The response to a DescribeProcess request for the ―intersect process might indicate that it requires two inputs, namely: ―FirstPolygon and ―SecondPolygon, and that these inputs must be provided in GML 2.2. Furthermore, the process will produce one output, in either GML 2.2, or GML 3.1, and it can be delivered as a web-accessible resource.

Page 85: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPS Example (continued)

The client would run the process by calling the Execute operation, and might choose to provide the two input polygons embedded directly within the request, and identify that the output should be stored as a web-accessible resource. After completion, the process would return an ExecuteResponse XML document that identifies the inputs and outputs, indicates whether or not the process executed successfully, and if successful, contains a reference to the web-accessible resource.

Page 86: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WPS Interaction DiagramWPS Interaction Diagram

Page 87: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

What WPS doesWhat WPS does

Describes the service interface, it specifies a Describes the service interface, it specifies a request/response interface that defines how to:request/response interface that defines how to: encode requests for process executionencode requests for process execution encode responses from process executionencode responses from process execution embed data and metadata in process execution embed data and metadata in process execution

inputs/outputsinputs/outputs reference web-accessible data inputs/outputsreference web-accessible data inputs/outputs support long-running processessupport long-running processes return process status informationreturn process status information return processing errorsreturn processing errors request storage of process outputsrequest storage of process outputs

Page 88: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 89: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .
Page 90: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-TWFS-T

The Web Feature Service (WFS) is an interface specified The Web Feature Service (WFS) is an interface specified by the OGC that allows for the exchange of geographic by the OGC that allows for the exchange of geographic data across the Web. data across the Web.

It defines the rules for requesting and retrieving It defines the rules for requesting and retrieving geographic information using the Hyper Text Transmission geographic information using the Hyper Text Transmission Protocol (HTTP). Protocol (HTTP).

The interface describes the data manipulation operations The interface describes the data manipulation operations on geographic features. on geographic features.

Extensible Markup Language (XML) -based Geographic Extensible Markup Language (XML) -based Geographic Markup Language (GML) is used for exchange of Markup Language (GML) is used for exchange of information. information.

WFS-T supports the vector data model.WFS-T supports the vector data model.

Page 91: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-TWFS-T A WFS implementation allows a client to retrieve and update features encoded in GML from A WFS implementation allows a client to retrieve and update features encoded in GML from

multiple servers. multiple servers. The WFS operations support INSERT, UPDATE, DELETE, LOCK, QUERY and DISCOVERY The WFS operations support INSERT, UPDATE, DELETE, LOCK, QUERY and DISCOVERY

operations. operations. A geographic feature is described by a set of properties where each property can be thought of A geographic feature is described by a set of properties where each property can be thought of

as a {name, type, value} tuple. as a {name, type, value} tuple. The name and type of each feature property is determined by its type definition. The name and type of each feature property is determined by its type definition. Geographic features are those that may have at least one property that is geometry-valued.Geographic features are those that may have at least one property that is geometry-valued. A WFS a transaction is a logical unit of work that is composed of one or more data manipulation A WFS a transaction is a logical unit of work that is composed of one or more data manipulation

operations. operations. Though not directly addressed by WFS, WFS assumes that geographic features are persistently Though not directly addressed by WFS, WFS assumes that geographic features are persistently

stored and that transaction semantics, such as atomic failure, stored and that transaction semantics, such as atomic failure, are assumed to exist. It is the function of a web feature service, in its interaction with the data are assumed to exist. It is the function of a web feature service, in its interaction with the data

storage system used to persistently store features, storage system used to persistently store features, to ensure that changes to data are consistent. (e.g. shape files or relational database systems to ensure that changes to data are consistent. (e.g. shape files or relational database systems

based on SQL). based on SQL). Typical WFS transaction simple request Typical WFS transaction simple request

Page 92: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-TWFS-T

Typical WFS transaction simple requestTypical WFS transaction simple request

Page 93: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-TWFS-T

The WFS specification details all the required XML and The WFS specification details all the required XML and GML definitions, of meta data and map data, GML definitions, of meta data and map data,

predicate or filter language will be defined in XML and be predicate or filter language will be defined in XML and be derived from CQL(like SQL where) as defined inderived from CQL(like SQL where) as defined in

the OpenGIS Catalogue Interface Implementation the OpenGIS Catalogue Interface Implementation Specification.Specification.

The following diagram shows the basic WFS client server The following diagram shows the basic WFS client server model (WFS follows a general web service model ).model (WFS follows a general web service model ).

WFS-T is well suited to applications were user needs to WFS-T is well suited to applications were user needs to interact with the map data (e.g. select objects, query interact with the map data (e.g. select objects, query objects and update objects).objects and update objects).

Page 94: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-T 2.0WFS-T 2.0

WFS-T 2.0 upports temporal queries, versioning, stored WFS-T 2.0 upports temporal queries, versioning, stored queries, joins, and spatial joinsqueries, joins, and spatial joins

Real time flight dispatch scenarios (disruption due to Real time flight dispatch scenarios (disruption due to volcanic ash and snow) use WFS 2.0 to retrieve and volcanic ash and snow) use WFS 2.0 to retrieve and update data in real-time via web services (WFS and update data in real-time via web services (WFS and eventing).eventing).

Web Feature Service 2.0 used for INSPIRE Compliance. Web Feature Service 2.0 used for INSPIRE Compliance. Allows the distribution of data via the latest web service Allows the distribution of data via the latest web service standard.standard.

Integrated data validation - preview and fix XML/GMLIntegrated data validation - preview and fix XML/GML Temporal queries can improve decision making Temporal queries can improve decision making WFS 2.0 used for INSPIRE data publishing.WFS 2.0 used for INSPIRE data publishing.

Page 95: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

WFS-T 2.0WFS-T 2.0

Discovery operations allow the service to be interrogated to determine Discovery operations allow the service to be interrogated to determine its capabilities and its capabilities and

to retrieve the application schema that defines the feature types that the to retrieve the application schema that defines the feature types that the service offers.service offers.

Query operations allow features or values of feature properties to be Query operations allow features or values of feature properties to be retrieved from the underlying data store based upon constraints,retrieved from the underlying data store based upon constraints,

defined by the client, on feature properties.defined by the client, on feature properties. Locking operations allow exclusive access to features for the purpose of Locking operations allow exclusive access to features for the purpose of

modifying or deleting features.modifying or deleting features. Transaction operations allow features to be created, changed, replaced Transaction operations allow features to be created, changed, replaced

and deleted from the underlying data store.and deleted from the underlying data store. Stored query operations allow clients to create, drop, list and described Stored query operations allow clients to create, drop, list and described

parametrized query expressions that are stored by the server and can parametrized query expressions that are stored by the server and can be repeatedly invoked using different parameter values.be repeatedly invoked using different parameter values.

Page 96: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

PL/pgSQLPL/pgSQL PL/pgSQL is a loadable procedural language for the PostgreSQL database PL/pgSQL is a loadable procedural language for the PostgreSQL database

system. The design goals of PL/pgSQL were to create a loadable system. The design goals of PL/pgSQL were to create a loadable procedural language thatprocedural language that

can be used to create functions and trigger procedures,can be used to create functions and trigger procedures, adds control structures to the SQL language,adds control structures to the SQL language, can perform complex computations,can perform complex computations, inherits all user-defined types, functions, and operators,inherits all user-defined types, functions, and operators, can be defined to be trusted by the server,can be defined to be trusted by the server, a method of creating stored procedures or SQL-proceduresa method of creating stored procedures or SQL-procedures Functions created with PL/pgSQL can be used anywhere that built-in Functions created with PL/pgSQL can be used anywhere that built-in

functions could be used. For example, it is possible to create complex functions could be used. For example, it is possible to create complex conditional computation functions and later use them to define operators or conditional computation functions and later use them to define operators or use them in index expressions.use them in index expressions.

Page 97: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Advantages of Using Advantages of Using PL/pgSQLPL/pgSQL

SQL is the language PostgreSQL and most other SQL is the language PostgreSQL and most other relational databases use as query language. It's portable relational databases use as query language. It's portable and easy to learn. But every SQL statement must be and easy to learn. But every SQL statement must be executed individually by the database server.executed individually by the database server.

That means that your client application must send each That means that your client application must send each query to the database server, wait for it to be processed, query to the database server, wait for it to be processed, receive and process the results, do some computation, receive and process the results, do some computation, then send further queries to the server. All this incurs then send further queries to the server. All this incurs interprocess communication and will also incur network interprocess communication and will also incur network overhead if your client is on a different machine than the overhead if your client is on a different machine than the database server.database server.

Page 98: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Advantages of Using Advantages of Using PL/pgSQLPL/pgSQL

With PL/pgSQL you can group a block of computation and a series With PL/pgSQL you can group a block of computation and a series of queries inside the database server, thus having the power of a of queries inside the database server, thus having the power of a procedural language and the ease of use of SQL, but with procedural language and the ease of use of SQL, but with considerable savings of client/server communication overhead.considerable savings of client/server communication overhead.

Extra round trips between client and server are eliminatedExtra round trips between client and server are eliminated Intermediate results that the client does not need do not have to be Intermediate results that the client does not need do not have to be

marshalled or transferred between server and clientmarshalled or transferred between server and client Multiple rounds of query parsing can be avoidedMultiple rounds of query parsing can be avoided This can result in a considerable performance increase as This can result in a considerable performance increase as

compared to an application that does not use stored functions.compared to an application that does not use stored functions. Also, with PL/pgSQL you can use all the data types, operators and Also, with PL/pgSQL you can use all the data types, operators and

functions of SQL.functions of SQL.

Page 99: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

PL/pgSQL FunctionPL/pgSQL Function This function returns the Fibonacci number for a position in the Fibonacci This function returns the Fibonacci number for a position in the Fibonacci

sequence. You must be in the postgis database for this definition to work.sequence. You must be in the postgis database for this definition to work. CREATE OR REPLACE FUNCTION fib ( fib_for integer ) CREATE OR REPLACE FUNCTION fib ( fib_for integer ) RETURNS integer AS $$RETURNS integer AS $$ BEGINBEGIN IF fib_for < 2 THENIF fib_for < 2 THEN RETURN fib_for;RETURN fib_for; END IF;END IF; RETURN fib(fib_for - 2) + fib(fib_for - 1);RETURN fib(fib_for - 2) + fib(fib_for - 1); END;END; $$ LANGUAGE plpgsql;$$ LANGUAGE plpgsql;

Call the function in the SQL shellCall the function in the SQL shell select fib(8);select fib(8);

Page 100: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

PL/SQLPL/SQL

Page 101: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Triggers and stored proceduresTriggers and stored procedures

PostgreSQL can used triggers to execute PostgreSQL can used triggers to execute a stored procedure when certain actions a stored procedure when certain actions are taken, like an INSERT, DELETE, or are taken, like an INSERT, DELETE, or UPDATE in a table. Or a procedure may UPDATE in a table. Or a procedure may be executed on a regular basis, perhaps be executed on a regular basis, perhaps once a day.once a day.

Page 102: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Triggers and stored proceduresTriggers and stored procedures

Execute the function Execute the function check_account_updatecheck_account_update whenever a row of the table accounts is about to be whenever a row of the table accounts is about to be updated, only if column updated, only if column balancebalance is specified as a target is specified as a target in the UPDATE command:in the UPDATE command:

CREATE TRIGGER check_updateCREATE TRIGGER check_update

BEFORE UPDATE OF balance ON accountsBEFORE UPDATE OF balance ON accounts

FOR EACH ROWFOR EACH ROW

EXECUTE PROCEDURE EXECUTE PROCEDURE check_account_update();check_account_update();

Page 103: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Why Use Stored Procedures Why Use Stored Procedures and Triggers?and Triggers?

Provide central validationProvide central validation Track changesTrack changes Enhance securityEnhance security Defer deletionsDefer deletions

Page 104: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Find Road segment near a pointFind Road segment near a point

Here is a PL/pgSQL function that finds a road segment that is closest to a given point P as shown. The query returns the source attribute.

Page 105: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Create a lineCreate a line

The following PL/pgSQL function makes a line   CREATE FUNCTION make_line() RETURNS GEOMETRY AS $$ BEGIN RETURN ST_LineFromMultiPoint( st_collect(ARRAY['POINT(10 10)', 'POINT(20 30)', 'POINT(20 60)', 'POINT(100 100)'])); END; $$ LANGUAGE plpgsql;

Page 106: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Find the midpoint of a lineFind the midpoint of a line

Given the previous make_line here is the SQL that finds the mid point.

SELECT ST_AsText(Line_Interpolate_Point(make_line(), 0.5));   The function returns a point interpolated along a line. The second

argument is a float8 between 0 and 1 representing fraction of total length of linestring the point has to be located. Linear Interpolation. (LI) is a piecewise linear function (piece = line segment) applied between two know (or measured) adjacent points. It is assumed that all intermediate points between the know points satisfy the equation of that line. This interpretation is important because it influences the definitions of spatial operations that use line e.g. the union of two regions. This usage of the term is employed by the OGC in relation to line representation

Page 107: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams &Voronoi diagrams & Delaunay triangulationDelaunay triangulation

A set of points S in the plane can be considered as Voronoi sites. Each site s has a Voronoi cell V(s) consisting of all points closer to s than to any other site. The segments of the Voronoi diagram are all the points in the plane that are equidistant to two sites. The Voronoi nodes are the points equidistant to three (or more) sites. The Voronoi diagram of a set of sites partitions space into regions one per site the region for a site S consists of all points closer to S than to any other site

Page 108: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

108108

The Voronoi diagram problemThe Voronoi diagram problem Given a set of n points, the Voronoi diagram Given a set of n points, the Voronoi diagram

consists of all the Voronoi polygons of these points.consists of all the Voronoi polygons of these points. E.g. A Voronoi diagram of 6 points: E.g. A Voronoi diagram of 6 points:

The vertices of the Voronoi diagram are called The vertices of the Voronoi diagram are called Voronoi pointsVoronoi points and its segments are called and its segments are called Voronoi Voronoi edgesedges. .

Page 109: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Summary of Voronoi Summary of Voronoi PropertiesProperties

A point A point qq lies on a Voronoi edge between sites lies on a Voronoi edge between sites ppii

and and ppjj iffiff the largest empty circle centered at the largest empty circle centered at qq

touches only touches only ppii and and ppjj

A Voronoi edge is a subset of locus of points A Voronoi edge is a subset of locus of points equidistant from equidistant from ppii and and ppjj

e

e : Voronoi edge

v

v : Voronoi vertex

pipi : site points

q pj

Page 110: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Summary of Voronoi Summary of Voronoi PropertiesProperties

A point A point qq is a vertex is a vertex iffiff the largest empty the largest empty circle centered at circle centered at qq touches at least 3 sites touches at least 3 sites A Voronoi vertex is an intersection of 3 more A Voronoi vertex is an intersection of 3 more

segments, each equidistant from a pair of sitessegments, each equidistant from a pair of sites

e

e : Voronoi edge

v

v : Voronoi vertex

pi

pi : site pointsq

Page 111: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Applications of Voronoi diagrams Applications of Voronoi diagrams

Nearest neighbour search -- For a query point q, finding its nearest neighbour from a fixed set of points S (pi in last slide) is simply a matter of determining which cell in the Voronoi diagram of S contains q.Facility location -- Suppose burger chain wanted to open another restaurant. To minimize interference with existing outlets, it should be located as far away from the closest restaurant as possible. This location is always at a vertex of the Voronoi diagram.

Page 112: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams Voronoi diagrams

Largest empty circle -- Suppose you needed to obtain a large, contiguous, undeveloped piece of land on which to build a undesirable facility, that has to be as far as possible from any relevant sites of interest. A Voronoi vertex defines the centre of the largest empty circle among the points. Path planning -- If the sites of S are the centres of obstacles we seek to avoid, the edges of the Voronoi diagram define the possible channels that maximize the distance to the obstacles. Thus in planning paths among the sites, it will be safest to stick to the edges of the Voronoi diagram.

Page 113: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams PL/R codeVoronoi diagrams PL/R code DROP FUNCTION voronoi(text, text, text);

CREATE OR REPLACE FUNCTION voronoi(text, text, text)

RETURNS SETOF voronoi AS

$BODY$

library(deldir)

# select the point x/y coordinates into a data frame...

points <- pg.spi.exec(sprintf("select x(%2$s) as x, y(%2$s) as y from %1$s;",arg1,arg2))

# calculate an approprate buffer distance (~10%):

buffer = ((abs(max(points$x)-min(points$x))+abs(max(points$y)-min(points$y)))/2)*(0.10)

Page 114: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams PL/R codeVoronoi diagrams PL/R code # get EWKB for the overall buffer of the convex hull for all points:

buffer <- pg.spi.exec(sprintf("select buffer(convexhull(st_union(%2$s)),%3$.6f) as ewkb from %1$s;",arg1,arg2,buffer))

# the following use of deldir uses high precision and digits to prevent slivers between the output polygons, and uses

# a relatively large bounding box with four dummy points included to ensure that points in the peripheral areas of the

# dataset are appropriately enveloped by their corresponding polygons:

voro = deldir(points$x, points$y, digits=22, frac=0.00000000000000000000000001,list(ndx=2,ndy=2), rw=c(min(points$x)-abs(min(points$x)-max(points$x)), max(points$x)+abs(min(points$x)-max(points$x)), min(points$y)-abs(min(points$y)-max(points$y)), max(points$y)+abs(min(points$y)-max(points$y))))

tiles = tile.list(voro)

Page 115: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams PL/R codeVoronoi diagrams PL/R codepoly = array()

id = array()

p = 1

for (i in 1:length(tiles)) {

tile = tiles[[i]]

curpoly = "POLYGON(("

for (j in 1:length(tile$x)) {

curpoly = sprintf("%s %.6f %.6f,",curpoly,tile$x[[j]],tile$y[[j]]) }

curpoly = sprintf("%s %.6f %.6f))",curpoly,tile$x[[1]],tile$y[[1]])

# this bit will find the original point that corresponds to the current polygon, along with its id and the SRID used for the

# point geometry (presumably this is the same for all points)...this will also filter out the extra polygons created for the

# four dummy points, as they will not return a result from this query:

ipoint <- pg.spi.exec(sprintf("select %3$s as id, intersection('SRID='||srid(%2$s)||';%4$s','%5$s') as polygon from %1$s where intersects(%2$s,'SRID='||srid(%2$s)||';%4$s');",arg1,arg2,arg3,curpoly,buffer$ewkb[1]))

if (length(ipoint) > 0)

{

poly[[p]] <- ipoint$polygon[1]

id[[p]] <- ipoint$id[1]

p = (p + 1)

}

}

return(data.frame(id,poly))

$BODY$

LANGUAGE 'plr' VOLATILE

COST 100

ROWS 1000;

ALTER FUNCTION voronoi(text, text, text) OWNER TO postgres;

Page 116: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams PL/R codeVoronoi diagrams PL/R code# this bit will find the original point that corresponds to the current polygon, along with its id and the SRID used for the point geometry (presumably this is the same for all points)...this will also filter out the extra polygons created for the four dummy points, as they will not return a result from this query:

ipoint <- pg.spi.exec(sprintf("select %3$s as id, intersection('SRID='||srid(%2$s)||';%4$s','%5$s') as polygon from %1$s where intersects(%2$s,'SRID='||srid(%2$s)||';%4$s');",arg1,arg2,arg3,curpoly,buffer$ewkb[1]))

if (length(ipoint) > 0) {

poly[[p]] <- ipoint$polygon[1]

id[[p]] <- ipoint$id[1]

p = (p + 1) } }

return(data.frame(id,poly))

$BODY$

LANGUAGE 'plr' VOLATILE

COST 100

ROWS 1000;

ALTER FUNCTION voronoi(text, text, text) OWNER TO postgres;

Page 117: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams SQLVoronoi diagrams SQL

To make your own Voronoi diagrams you will need to create a Voronoi table.

Then you will need to run your queries against that table:

For example to get all historical monuments that are nearest to each hospital.

Select hospitals.name,substr(d.name,1,10)

from hospitals_voroni as h, dublin_historical as d,hospitals where contains(h.the_geom,d.the_geom) order by hospitals.name;

Page 118: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Voronoi diagrams for hospitalsVoronoi diagrams for hospitals

Page 119: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Delaunay Triangles PL/R codeDelaunay Triangles PL/R codeCREATE OR REPLACE FUNCTION r_delaunay2D(p_query text)

RETURNS SETOF text AS

' library(deldir)

# select the point x/y/z coordinates into a data frame

points <- pg.spi.exec(p_query)

# calculate an approprate buffer distance (~10%):

buffer_distance = (

(

abs(max(points$x) - min(points$x)) +

abs(max(points$y) - min(points$y))

) / 2

) * (0.10)

Page 120: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Delaunay Triangles PL/R codeDelaunay Triangles PL/R code# the following use of deldir uses high precision and digits to prevent

# slivers between the output triangles, and uses a relatively large bounding

# box with four dummy points included to ensure that points in the

# peripheral areas of the dataset are appropriately enveloped by their

# corresponding triangles:

# points$x,

# points$y,

voro = deldir(

list( x=points$x, y=points$y),

digits=22,

frac=0.00000000000000000000000001,

list(ndx=2,ndy=2),

rw=c(

min(points$x) - abs(min(points$x) - max(points$x)),

max(points$x) + abs(min(points$x) - max(points$x)),

min(points$y) - abs(min(points$y) - max(points$y)),

max(points$y) + abs(min(points$y) - max(points$y))

)

)

Page 121: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Delaunay Triangles PL/R codeDelaunay Triangles PL/R code# Do the triangulation

#

triangles = triang.list(voro)

# Now create the output

#

poly = array()

id = array()

p = 1

# construct the outgoing WKT now

#

for (i in 1:length(triangles)) {

triangle = triangles[[i]]

wktpoly = "POLYGON(("

for (j in 1:length(triangle$x)) {

wktpoly = sprintf(

"%s%.8f %.8f,",

wktpoly,

triangle$x[[j]],

triangle$y[[j]]

)

}

wktpoly = sprintf(

"%s%.8f %.8f))",

wktpoly,

triangle$x[[1]],

triangle$y[[1]]

)

poly[[p]] <- wktpoly

p = (p + 1)

}

return(data.frame(poly))

' LANGUAGE 'plr';

Page 122: Spatial Databases: Lecture 9 Web Mapping DT211-4, DT228-4, MSc Semester 2 2015  .

Delaunay Triangles SQL codeDelaunay Triangles SQL code

select r_delaunay2D('select x(the_geom) as x, y(the_geom) as y from ho spitals');

select ger_delaunay2D('select x(the_geom) as x, y(the_geom) as y from ho spitals');

select astext(r_delaunay2D('select x(the_geom) as x, y(the_geom) as y from hospitals'),29900);

select GeometryFromText(r_delaunay2D('select x(the_geom) as x, y(the_geom) as y from hospitals'),29900);