Table of Contents for
OpenLayers 3 : Beginner's Guide

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition OpenLayers 3 : Beginner's Guide by Erik Hazzard Published by Packt Publishing, 2015
  1. Cover
  2. Table of Contents
  3. OpenLayers 3 Beginner's Guide
  4. OpenLayers 3 Beginner's Guide
  5. Credits
  6. About the Authors
  7. About the Reviewers
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Sections
  13. Time for action – heading
  14. Conventions
  15. Reader feedback
  16. Customer support
  17. 1. Getting Started with OpenLayers
  18. Advantages of using OpenLayers
  19. What, technically, is OpenLayers?
  20. Anatomy of a web mapping application
  21. Connecting to Google, Bing Maps, and other mapping APIs
  22. Time for action – downloading OpenLayers
  23. Time for action – creating your first map
  24. Where to go for help
  25. OpenLayers issues
  26. OpenLayers source code repository
  27. Getting live news from RSS and social networks
  28. Summary
  29. 2. Key Concepts in OpenLayers
  30. Time for action – creating a map
  31. Time for action – using the JavaScript console
  32. Time for action – overlaying information
  33. OpenLayers' super classes
  34. Key-Value Observing with the Object class
  35. Time for action – using bindTo
  36. Working with collections
  37. Summary
  38. 3. Charting the Map Class
  39. Time for action – creating a map
  40. Map renderers
  41. Time for action – rendering a masterpiece
  42. Map properties
  43. Time for action – target practice
  44. Map methods
  45. Time for action – creating animated maps
  46. Events
  47. Views
  48. Time for action – linking two views
  49. Summary
  50. 4. Interacting with Raster Data Source
  51. Layers in OpenLayers 3
  52. Common operations on layers
  53. Time for action – changing layer properties
  54. Tiled versus untiled layers
  55. Types of raster sources
  56. Tiled images' layers and their sources
  57. Time for action – creating a Stamen layer
  58. Time for action – creating a Bing Maps layer
  59. Time for action – creating tiles and adding Zoomify layer
  60. Image layers and their sources
  61. Using Spherical Mercator raster data with other layers
  62. Time For action – playing with various sources and layers together
  63. Time For action – applying Zoomify sample knowledge to a single raw image
  64. Summary
  65. 5. Using Vector Layers
  66. Time for action – creating a vector layer
  67. How the vector layer works
  68. The vector layer class
  69. Vector sources
  70. Time for action – using the cluster source
  71. Time for action – creating a loader function
  72. Time for action – working with the TileVector source
  73. Time for action – a drag and drop viewer for vector files
  74. Features and geometries
  75. Time for action – geometries in action
  76. Time for action – interacting with features
  77. Summary
  78. 6. Styling Vector Layers
  79. Time for action – basic styling
  80. The style class
  81. Time for action – using the icon style
  82. Have a go hero – using the circle style
  83. Multiple styles
  84. Time for action – using multiple styles
  85. Style functions
  86. Time for action – using properties to style features
  87. Interactive styles
  88. Time for action – creating interactive styles
  89. Summary
  90. 7. Wrapping Our Heads Around Projections
  91. Time for action – using different projection codes
  92. Time for action – determining coordinates
  93. OpenLayers projection class
  94. Transforming coordinates
  95. Time for action – coordinate transforms
  96. Time for action – setting up Proj4js.org
  97. Time for action – reprojecting extent
  98. Time for action – using custom projection with WMS sources
  99. Time for action – reprojecting geometries in vector layers
  100. Summary
  101. 8. Interacting with Your Map
  102. Time for action – converting your local or national authorities data into web mapping formats
  103. Time for action – testing the use cases for ol.interaction.Select
  104. Time for action – more options with ol.interaction.Select
  105. Introducing methods to get information from your map
  106. Time for action – understanding the forEachFeatureAtPixel method
  107. Time for action – understanding the getGetFeatureInfoUrl method
  108. Adding a pop-up on your map
  109. Time for action – introducing ol.Overlay with a static example
  110. Time for action – using ol.Overlay dynamically with layers information
  111. Time for action – using ol.interaction.Draw to share new information on the Web
  112. Time for action – using ol.interaction.Modify to update drawing
  113. Understanding interactions and their architecture
  114. Time for action – configuring default interactions
  115. Discovering the other interactions
  116. Time for action – using ol.interaction.DragRotateAndZoom
  117. Time for action – making rectangle export to GeoJSON with ol.interaction.DragBox
  118. Summary
  119. 9. Taking Control of Controls
  120. Adding controls to your map
  121. Time for action – starting with the default controls
  122. Controls overview
  123. Time for action – changing the default attribution styles
  124. Time for action – finding your mouse position
  125. Time for action – configuring ZoomToExtent and manipulate controls
  126. Creating a custom control
  127. Time for action – extending ol.control.Control to make your own control
  128. Summary
  129. 10. OpenLayers Goes Mobile
  130. Using a web server
  131. Time for action – go mobile!
  132. The Geolocation class
  133. Time for action – location, location, location
  134. The DeviceOrientation class
  135. Time for action – a sense of direction
  136. Debugging mobile web applications
  137. Debugging on iOS
  138. Debugging on Android
  139. Going offline
  140. Time for action – MANIFEST destiny
  141. Going native with web applications
  142. Time for action – track me
  143. Summary
  144. 11. Creating Web Map Apps
  145. Using geospatial data from Flickr
  146. Time for action – getting Flickr data
  147. A simple application
  148. Time for Action – adding data to your map
  149. Styling the features
  150. Time for action – creating a style function
  151. Creating a thumbnail style
  152. Time for action – switching to JSON data
  153. Time for action – creating a thumbnail style
  154. Turning our example into an application
  155. Time for action – adding the select interaction
  156. Time for action – handling selection events
  157. Time for action – displaying photo information
  158. Using real time data
  159. Time for action – getting dynamic data
  160. Wrapping up the application
  161. Time for action – adding dynamic tags to your map
  162. Deploying an application
  163. Creating custom builds
  164. Creating a combined build
  165. Time for action – creating a combined build
  166. Creating a separate build
  167. Time for action – creating a separate build
  168. Summary
  169. A. Object-oriented Programming – Introduction and Concepts
  170. Going further
  171. B. More details on Closure Tools and Code Optimization Techniques
  172. Introducing Closure Library, yet another JavaScript library
  173. Time for action – first steps with Closure Library
  174. Making custom build for optimizing performance
  175. Time for action – playing with Closure Compiler
  176. Applying your knowledge to the OpenLayers case
  177. Time for action - running official examples with the internal OpenLayers toolkit
  178. Time for action - building your custom OpenLayers library
  179. Syntax and styles
  180. Time for action – using Closure Linter to fix JavaScript
  181. Summary
  182. C. Squashing Bugs with Web Debuggers
  183. Time for action – opening Chrome Developer Tools
  184. Explaining Chrome Developer debugging controls
  185. Time for action – using DOM manipulation with OpenStreetMap map images
  186. Time for action – using breakpoints to explore your code
  187. Time for action – playing with zoom button and map copyrights
  188. Using the Console panel
  189. Time for action – executing code in the Console
  190. Time for action – creating object literals
  191. Time for action – interacting with a map
  192. Improving Chrome and Developer Tools with extensions
  193. Debugging in other browsers
  194. Summary
  195. D. Pop Quiz Answers
  196. Chapter 5, Using Vector Layers
  197. Chapter 7, Wrapping Our Heads Around Projections
  198. Chapter 8, Interacting with Your Map
  199. Chapter 9, Taking Control of Controls
  200. Chapter 10, OpenLayers Goes Mobile
  201. Appendix B, More details on Closure Tools and Code Optimization Techniques
  202. Appendix C, Squashing Bugs with Web Debuggers
  203. Index

Time for action – creating a loader function

Creating a loader function isn't as hard as it might sound, let's walk through a concrete example that loads features from a WFS server. In this example, we will be using the popular jQuery library to help us load data. If you are not familiar with jQuery, see http://jquery.com for more information.

  1. Start by creating a new HTML page using the same structure we've used before. We'll start from this for each of the vector source examples. Note the addition of a <script> tag to load jQuery:
    <!doctype html>
    <html>
      <head>
        <title>vector Examples</title>
        <link rel="stylesheet" href="../assets/ol3/ol.css" type="text/css" />
        <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
      </head>
      <body>
        <div id="map" class="map"></div>
        <script src="../assets/ol3/ol.js" type="text/javascript"></script>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script>
          var tiledRaster = new ol.layer.Tile({
            source: new ol.source.OSM()
          });
          var center = ol.proj.transform([-72.6, 41.7], 'EPSG:4326', 'EPSG:3857');
          var view = new ol.View({
            center: center,
            zoom: 12,
          });
          var map = new ol.Map({
            target: 'map',
            layers: [tiledRaster],
            view: view
          });
        </script>
      </body>
    </html>

    Next, we'll need to create a style object for displaying our vectors. Don't worry too much about what this is, we'll cover it in detail in Chapter 6, Styling Vector Layers. Add this after the tiledRaster and before the center:

    var fill = new ol.style.Fill({
      color: 'rgba(0,0,0,0.2)'
    });
    var stroke = new ol.style.Stroke({
      color: 'rgba(0,0,0,0.4)'
    });
    var circle = new ol.style.Circle({
      radius: 6,
      fill: fill,
      stroke: stroke
    });      
    var vectorStyle = new ol.style.Style({
      fill: fill,
      stroke: stroke,
      image: circle
    });
  2. Save this file as vector_template.html and make a copy of it to use for the rest of this example. We'll be using vector_template.html as the starting point for several examples.
  3. Now, add the following code after the vectorStyle object, which will handle loading features from the remote server:
    var vectorLoader = function(extent, resolution, projection) {
      var url = 'http://demo.boundlessgeo.com/geoserver/wfs?service=WFS&' +
      'version=1.1.0&request=GetFeature&typename=osm:builtup_area&' +
      'outputFormat=text/javascript&format_options=callback:loadFeatures' +
      '&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
      $.ajax({
        url: url,
        dataType: 'jsonp'
      });
    };
    var loadFeatures = function(response) {
      var features = vectorSource.readFeatures(response);
      vectorSource.addFeatures(features);
    };
  4. We now have everything needed to create the source and layer objects; so, add this code immediately following the loadFeatures function:
    var vectorSource = new ol.source.ServerVector({
      format: new ol.format.GeoJSON(),
      loader: vectorLoader,
      strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({
        maxZoom: 19
      })),
      projection: 'EPSG:3857',
    });
    var serverVector = new ol.layer.vector({
      source: vectorSource,
      style: vectorStyle
    });
  5. Finally, add the serverVector layer to the map's layers:
    var map = new ol.Map({
      renderer: 'canvas',
      target: 'map',
      layers: [tiledRaster, serverVector],
      view: view
    });
  6. Load the page in your browser and you should see something like the following screenshot:
    Time for action – creating a loader function
  7. Pan and zoom the map and observe what happens.

What just happened?

We just created a vector layer that reads features from a remote WFS server as the map is panned and zoomed. A lot just happened, so let's review each step in detail.

In step 1, we set up a new OpenLayers application using the same structure as we've used for all the other examples so far. Nothing new here, except we've chosen a center for the map view somewhere in the north eastern United States and named our base layer tiledRaster to help differentiate it from the vector layers we will be working with.

In step 2, we created a simple vector style object to use with all our vector layers. A vector style consists of several components, in this case, we are defining the style to use for fill (polygons), stroke (lines), and image (points). The color for each is defined using the rgba() syntax, which stands for red, green, blue, and alpha (opacity). In this case, we are using a simple black color and 20 percent opacity. We'll cover styles in much more detail in the next chapter.

Step 4 is really the heart of this example. First, we defined a vectorLoader function. This function is used by ol.source.ServerVector to fetch features from a remote server. The vectorLoader function declares a URL that points to a WFS server. You might think the URL looks a bit complicated, and you are right. For now, just trust that it does the right thing, which is to ask the server for all the vector features contained within the current extent. The jQuery ajax function is used to actually trigger loading the URL. The jsonp data type tells jQuery to request the data by inserting it as a <script> tag, and the callback option in the URL identifies the function that will be executed when the <script> tag is loaded; in this case, the loadFeatures function.

The loadFeatures function takes the features provided by the server, reads them using the vector source (which has a GeoJSON format for parsing the data), and adds them to the layer.

In step 5, we combined all the previous pieces to create the source and layer objects. To define the source, we used ol.source.ServerVector and provided it with a format (GeoJSON in this case), the loader function we defined in the previous step, a loading strategy, and a projection. We'll discuss the loading strategy a bit later. Finally, we created the actual layer object using ol.layer.vector and provide it with our source and style.

After we added this to the map's layers in step 5, we can see it in action. Every time the map is panned or zoomed, the vector layer checks its source for features. The ServerVector source requests data from a remote server using a function that we provide. This gives you a lot of flexibility, but also means that you have to understand how to load data from a remote server. Fortunately, libraries such as jQuery have very good convenience methods for doing just this. The ServerVector source uses its loading strategy to decide how to divide up the requests to the server and passes the appropriate parameters to your loader function. We'll talk a bit more about loading strategies in some time. Once the features are loaded, you can parse them and add them to the source directly. The vector layer then draws the features using the provided style.

To see what happens when features are requested from the server, open Web Inspector, switch to the Network tab, and make sure All is selected, then reload the page.

What just happened?

You can identify the feature requests because they start with wfs?service=WFS. Click on a request to view its response. Notice how some requests have no features, and some have features. Notice how the response is formatted—it looks like a JavaScript function call to loadFeatures() with an object literal as the argument. The loadFeatures() function is the one we specified and that we implemented. This is an example of how jsonp works.

Now that we've seen it in action, let's review the constructor options for a ServerVector source:

Name

Type

Description

attributions

Array.<ol.Attribution>

As with ol.source.vector, this is an optional array of attributions to display when features from this source are displayed on the map.

format

ol.format.Format

This is the format that the server features are represented in.

loader

function

This is a function that creates an appropriate request to the server for a given extent, resolution and projection. If the server responds successfully with data to be parsed, then the source's format should be used by the loader function to read the features from the data returned by the server.

logo

string | olx.LogoOptions | undefined

This is a logo to display when features from this source are displayed on the map.

strategy

function

This is a function that determines how the source will split up requests to the server. There are two built-in strategy functions:

  • ol.loadingstrategy.all: This strategy loads all the available data in a single request by specifying an infinite extent.
  • ol.loadingstrategy.bbox: This strategy loads data for the visible map extent. Panning or zooming the map can trigger additional calls to the loader function, possibly overlapping previously loaded regions.

There is one additional option available, ol.loadingstrategy.createTile. You do not use this as a loading strategy directly, instead it is a function you call to create a loading strategy function based on a tile-grid specification. The return value from this is a function to be used as a loading strategy that triggers requests based on regular tile boundaries. Unlike the BBOX strategy, the extent for each call to the loader function will not overlap previous extents.

projection

ol.proj.ProjectionLike

This is the projection for feature geometries after parsing.

The TileVector source

The final vector source is TileVector. This source loads features by requesting them in batches based on a tile grid exactly the same way that the raster sources work. The job of a tile grid is to divide the world up into rows and columns and convert geographic coordinates for the current view into row and column references.

If you were following closely in the previous section, you might wonder how TileVector is different from a ServerVector configured with a loading strategy based on ol.loadingstrategy.createTile. The main differences are as follows:

  1. The TileVector source has its own loading functionality—you do not need to provide one.
  2. The TileVector source uses the row, column, and zoom level rather than geographic coordinates to request features from the server.
  3. The TileVector source provides convenient options for working with tile-based servers.

    Note

    There are several ways of producing and serving vector tiles. One way is to use a program that splits vector data up into tiles based on a particular tile grid and save the tiles to disk in a directory structure based on the zoom level, column,and row. Another way is to use a server that can split up vector data on the fly. The OpenStreetMap wiki has a page dedicated to vector tiles and related resources at http://wiki.openstreetmap.org/wiki/vector_tiles.