OpenLayers: Overview of Vector Layer

Exclusive offer: get 50% off this eBook here
OpenLayers 2.10 Beginner's Guide

OpenLayers 2.10 Beginner's Guide — Save 50%

Create, optimize, and deploy stunning cross-browser web maps with the OpenLayers JavaScript web mapping library

$26.99    $13.50
by Erik Hazzard | April 2011 | Beginner's Guides Open Source

Get exclusive offers on Open Source Graphic Application and Library books through out this month. For more information click here.

OpenLayers is a powerful, community driven, open source, pure JavaScript web-mapping library. With it, you can easily create your own web map mashup using WMS, Google Maps, and a myriad of other map backends.

In this article by Erik Hazzard, author of OpenLayers 2.10 Beginner's Guide, we will discuss what the Vector Layer class is and see how it works.

 

OpenLayers 2.10 Beginner's Guide

OpenLayers 2.10 Beginner's Guide

Create, optimize, and deploy stunning cross-browser web maps with the OpenLayers JavaScript web mapping library

        Read more about this book      

(For more resources on on this subject, see here.)

What is the Vector Layer?

OpenLayers' Vector Class is generally used to display data on top of a map and allow real time interaction with the data. What does this mean? Basically, it means we can load in data from geospatial files, such as KML or GeoJSON files, and display the contents on a map, styling the data however we see fit. For example, take a look at this map:

OpenLayers: Overview of Vector Layer

This shows a map with a Google layer as underlying base layer and a vector layer on top of it. The data (all the circles with numbers in them) are loaded in from a GeoJSON file, an open file format that many other applications support. In the vector layer, there are a bunch of data points throughout the map. Each dot on the map is an object in the vector layer, and these objects are referred to as Features.

In this case, each feature is actually a cluster of data points—the numbers in each circle represent how many points belong to that cluster. This clustering behavior is something we can use out of the box with OpenLayers via the Strategy class. Before we get to that point, let's talk about one of the main things that separate a vector layer from other layers.

What makes the Vector Layer special?

With a raster image, what you see is what you get. If you were to look at some close up satellite imagery on your map and see a bunch of buildings clustered together, you wouldn't necessarily know any additional information about those buildings. You might not even know they are buildings. Since raster layers are made up of images, it is up to the user to interpret what they see. This isn't necessarily a bad thing, but vector layers provide much more.

With a vector layer, you can show the actual geometry of the building and attach additional information to it—such as the value of it, who owns it, its square footage, etc. It's easy to put a vector layer on top of your existing raster layers and create features in a specific location.

The Vector Layer is client side

Another fundamental difference is that the vector layer is, generally, used as a client side layer. This means that, usually, interaction with the actual vector data happens only on the client side. When you navigate around the map, for instance, the vector layer does not send a request to a server to get more information about the layer. Once you get the initial data, it's in your browser and you do not have to request the same data again.

Since, in most cases, the vector data is loaded on the client side, interaction with the vector layer usually happens nearly instantaneously. However, there are some limitations. The vector layer is dependent on the user's browser and computer. While most browsers other than Internet Explorer have been progressing exceptionally well and are becoming more powerful each day, limitations do exist.

Due to browser limitations, too many features in a vector layer will start to slow things down. There is no hard number on the amount of features, but generally anything over a couple hundred of features will start to slow things down on most computers. However, there are many ways around this, such as deleting features when you don't need them, and we'll talk about performance issues in more depth later.

Other uses

With the vector layer, we can display any type of geometrical object we'd like—points, lines, polygons, squares, makers...any shape you can imagine. We can use the vector layer to draw lines or polygons and then calculate the distance between them. We can draw shapes and then export the data using a variety of formats, then import that data in other programs, such as Google Earth.

What is a 'Vector'?

In terms of graphics, there are essentially two types of images: raster and vector. Most images you see are raster images—meaning, basically, they are comprised of a grid of pixels and their quality degrades as you zoom in on them. A photograph, for example, would be a raster image. If you enlarge it, it tends to get blurry or stretched out. The majority of image files—.jpegs, .png, .gifs, any bitmap image—are raster images.

A vector, on the other hand, uses geometrical shapes based on math equations to form an image. Meaning that when you zoom in, the quality is preserved. If you were to zoom in on a vector image of a circle, the lines would always appear curved—with raster image, the lines would appear straight, as raster images are made up of a grid of colors. Vector graphics are not constrained to a grid, so they preserve shape at all scales.

Time for Action – creating a Vector Layer

Let's begin by creating a basic vector layer. In this example, after you add some points and other feature types to your vector layer, try to zoom in. You'll notice that the points you added don't lose quality as you zoom in. We'll go over how it works afterwards.

  1. We'll start off by using a basic WMS layer:

    var wms_layer = new OpenLayers.Layer.WMS(
    'OpenLayers WMS',
    'http://vmap0.tiles.osgeo.org/wms/vmap0',
    {layers: 'basic'},
    {}
    );

  2. Now, let's create the vector layer itself. We'll use the default projection and default values for the vector layer, so to create the layer all we need to do is create it:

    var vector_layer = new OpenLayers.Layer.Vector('Basic Vector
    Layer')

  3. Add the layers to the map now:

    map.addLayers([wms_layer, vector_layer]);

  4. If we looked at the map now, we would just see a simple map—our vector layer does not have any data loaded into it, nor do we have any controls to let us add vector data.
  5. Let's add the EditingToolbar control to the map, which allows us to add points and draw polygons on a vector layer. To do so, we just need to instantiate an object from OpenLayers.Control.EditingToolbar and pass in a vector layer. We'll pass in the vector_layer object we previously created:

    map.addControl(new OpenLayers.Control.EditingToolbar(vector_
    layer));

  6. Take a look at the map now. You should see the EditingToolbar control (which is basically a panel control with control buttons). Selecting different controls will allow you to place vector objects (called features) on the vector layer. Play around with the EditingToolbar control and place a few different points / polygons on the map:

    OpenLayers: Overview of Vector Layer

  7. Now, one more step. You've placed some features (points / polygons / lines / etc.) on the map, but if you were to refresh the page they would disappear. We can, however, get the information about those features and then export it to a geospatial file. We'll work with files later, but for now let's grab the information about the features we've created. To access the information about the vector layer's features, all we need to do is access its features array. In Firebug, type and run the following:

    map.layers[1].features

  8. You should see a bunch of objects listed, each object is a feature you placed on the map:

    [Object { layer=Object, more...}, Object { layer=Object,
    more...},
    Object { layer=Object, more...}, ...]

  9. Now, if you expand one of those objects, you'll get the information about a feature. The geometry property is an anonymous object each feature has which contains geometry information. You can also see the methods of the feature objects—try playing around with different functions. You can access the individual features by using map.layers[1].features[x], where x is the index of the feature in the features array. For instance, to destroy the first feature which we added to the map we could use:

    map.layers[1].features[0].destroy();

What Just Happened?

We just demonstrated how to create a basic vector layer and added features to it using the EditingToolbar control. Using the features array of the vector layer, we also destroyed some features. As you've just seen, it's not terribly difficult to start using the vector layer— pretty easy, in fact.

OpenLayers 2.10 Beginner's Guide Create, optimize, and deploy stunning cross-browser web maps with the OpenLayers JavaScript web mapping library
Published: March 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on on this subject, see here.)

How the Vector Layer works

There are primarily four things we need to cover to understand how the vector layer works.

  • How the Vector Layer is rendered
  • The Vector Layer class itself
  • The Geometry and Feature classes
  • How to use the related Strategy, Protocol, and Format classes

Let's go over rendering—fortunately, there's not much to it.

How the Vector Layer is rendered

As we discussed earlier, the vector layer doesn't use raster graphics. Other layer types use the <img> tag (image tag) to show images—in HTML, the image tag will only display raster images. So, we can't just use <img> tags like other layers. Instead, we have to use a vector image renderer. As we mentioned before, the vector data is not just an image, and can contain additional information such as the coordinates of the data.

The vector data must be rendered to be seen. OpenLayers supports three ways to render the vector layer: SVG, Canvas, and VML.

SVG

The default way to render the vector layer is to use the SVG renderer, which makes use of the <svg> tag. SVG is an acronym for Scalable Vector Graphics, and allows us to render vector images in the browser. All browsers (except Internet Explorer) support SVG, so by default OpenLayers uses SVG to render the vector layer.

Canvas

We can use the Canvas renderer, which makes use of the <canvas> HTML tag. Using this renderer tends to be a little slower however, as the vector is actually turned into a raster with the canvas tag—but this may be desirable in some cases.

VML

Internet Explorer does not follow web standards, and at the time of writing did not support SVG or Canvas. Fortunately, by default, OpenLayers will detect if the user's web browser does not support modern technologies and a fall back renderer called VML will be used (which is similar to SVG, but is Microsoft specific). SVG tends to be faster than VML, so the only case where you would want to use VML over SVG is when Internet Explorer is used.

'Renderers' array

When you create a vector layer, it looks for an array called renderers which contains the names of renderers, in order, to use. By default, the renderers array is set as:

["SVG", "VML", "Canvas"]

This means that OpenLayers will try to use SVG first, and if the browser does not support SVG it will fall back on VML—and if it does not support VML, it will try to use Canvas.

Time for Action – changing the Renderers array

  1. Make a copy of the previous example. We'll just be changing one line of the code.
  2. The only thing we'll need to do is set the renderers property when instantiating the vector layer. By default, it is set as ['SVG', 'VML', 'Canvas']. Let's make Canvas the default renderer. Replace your vector layer instantiation code with:

    var vector_layer = new OpenLayers.Layer.Vector('Basic Vector
    Layer', {
    renderers: ['Canvas', 'SVG', 'VML']
    });

  3. Open up the map and draw some points. It may look similar, but you will probably notice that the lines don't look as sharp as they do when using the SVG renderer. If you use Firebug to inspect the map element, you'll see a <canvas> tag:

    OpenLayers: Overview of Vector Layer

What Just Happened?

You just saw how easy it is to change the renderer used by the vector layer—although it is not usually necessary to change it.

Now that we know how the vector layer is rendered, let's talk about the class itself.

Vector Layer class

The Vector Layer, by itself, is a layer like the other layers we've discussed so far—but to really get the most out of it, we'll be working with other classes.

To even get a basic example working (like the first one in this article), we make use of a few other classes. Specifically, the Vector class makes use of the Feature class to show objects on the layer. But for the Feature class to work, it needs to use the Geometry class to create geometry objects. Therefore, the actual vector objects in your vector layers are Feature objects which are composed of Geometry objects—we'll cover all that soon.

Before we do that though, let's cover the Vector Layer class itself. We'll first go over the properties of the Vector class, and then the methods.

OpenLayers.Layer.Vector properties

Let's go over the properties that the Vector class contains. Some of them are instantiated objects from other classes.

  • drawn: {Boolean}. Returns true or false depending on whether the features have been drawn or not. You do not set this property when instantiating the vector layer object.
  • features: {Array {OpenLayers.Feature.Vector}}. This is an array of feature objects belonging to the vector layer. We saw this in the earlier example—by accessing this array, we can find out information about all the objects (features) which a vector layer contains. Since this is an array, you can access an individual feature by calling vector_layer.features[X], where X is the index of the desired feature.
  • filter: {OpenLayers.Filter}. By assigning a filter object to a vector layer object, you can (as the name implies) filter out certain data based on the properties supplied to the filter object. This is very useful when you want to display some, but not all, features from a data source.
  • isBaseLayer: {Boolean}. Default value is false. Specifies if the layer is a base layer or not. You could use a vector layer as a base layer, having an entirely vector based map instead of relying on a WMS or Google Maps Layers as a base layer.
  • isFixed: {Boolean}. Default value is false. Determines if the vector layer will move around when the map is dragged. This can come in handy if, for instance, you want to place a marker on your map that always stayed in the center of the map (in which case you would set this property to true).
  • isVector: {Boolean}. Returns true if the layer is a vector layer. You do not set this property when you instantiate the vector layer. This property is used primarily to check if an already instantiated layer is a vector layer or not. For instance, if you wanted to loop through all the layers on your map and determine if a layer was a vector layer or not, you would likely use this property.
  • protocol: {OpenLayers.Protocol}. Specifies a protocol object to use for the vector layer. In the section on strategies, protocols, and formats, we talk about this in much more depth.
  • renderers: {Array{String}}. Specifies an array containing strings which contain the renderers to use. Each renderer is tried, in order, and if it is not supported by the browser, the next one is tried. Earlier in the article we went over how to use this property.
  • rendererOptions: {Object}. The renderer will use an anonymous object consisting of properties. We won't talk any more about renderers in this article, but the properties this object can contain are listed in the OpenLayers docs for each renderer class at http://dev.openlayers.org/docs/files/OpenLayers/Renderer-js.html.
  • reportError: {Boolean}. Default is true. This property specifies whether or not to report error messages if the renderer fails to load.
  • selectedFeatures: {Array{OpenLayers.Feature.Vector}}. This property contains an array of features the layer contains that are currently selected. Features can be selected by, for instance, clicking on a feature. This property is discussed more in the section on interacting with features.
  • strategies: {Array{OpenLayers.Strategy}}. An array of strategy objects. Strategies tell the vector layer how to behave, such as clustering features together. In the section on strategies, protocols, and formats, we talk about this in much more depth.
  • style: {Object}. Contains style information for the vector layer. Using this, we can change the color, size, etc. of features in our vector layer.
  • styleMap: {OpenLayers.StyleMap}. A stylemap object that defines styles the vector layer will use.
  • unrenderedFeatures: {Object}. This contains an anonymous object of features that failed to render (if any exists). You do not set this property when instantiating the vector layer object.

OpenLayers.Layer.Vector methods

Now that we've gone over the Vector Layer class properties, let's discuss the methods we can call. We'll just cover functions specific to the Vector layer.

  • clone(): Makes a copy of the layer and the features it contains. Returns an {OpenLayers.Layer.Vector} object, which is a copy of the layer.
  • getDataExtent(): This function will return an {OpenLayers.Bounds} object consisting of the max extent that includes all the features of the layer.
  • refresh(obj): Causes the layer to request features and redraw them. If the layer is visible and in range of the map extent, the refresh event will be triggered. Takes in an optional obj object containing properties for event listeners.
  • assignRenderer(): Assigns a renderer to the layer based on the layer's renderers property.
  • displayError(): Shows an alert informing the user that their browser does not support the layer's renderers.

Working with features

The remaining methods that we'll discuss involve features. A feature, as we saw earlier, is an object that belongs to the vector layer. We'll cover methods first, and then walk through the related examples to show how to properly use them.

addFeatures(features, options): Calling this function will add features to the map. You must pass in at least an array of features objects, and you can optionally pass in an options object. The features parameter is an {Array{OpenLayer.Feature.Vector}}, and options is an anonymous {Object}.

Summary

In this article, we discussed what the Vector Layer class is and saw how it works.


Further resources on this subject:


OpenLayers 2.10 Beginner's Guide Create, optimize, and deploy stunning cross-browser web maps with the OpenLayers JavaScript web mapping library
Published: March 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Erik Hazzard

Erik Hazzard is a web developer – designer, Open Source advocate, and VI user. He loves to learn, teach, and occasionally blogs on his website at http://vasir.net. As a professional web developer of five years, Erik specializes in Python and Javascript, using open source software whenever possible. When he's not developing web applications, he's often developing or designing video games.

Books From Packt


OpenStreetMap
OpenStreetMap

Python Geospatial Development
Python Geospatial Development

Inkscape 0.48 Illustrator's Cookbook
Inkscape 0.48 Illustrator's Cookbook

R Graph Cookbook
R Graph Cookbook

Django JavaScript Integration: AJAX and jQuery
Django JavaScript Integration: AJAX and jQuery

OpenCart 1.4: Beginner's Guide
OpenCart 1.4: Beginner's Guide

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software