Back top previously visited page (this function is disabled)Back to homepage (P)Back to previous page (E)Jump to next page (V)Display terms (this function is disabled)List of terms (this function is disabled)Print this page (this function is disabled)Jump to sitemap (D)Search in current page (this function is disabled)Help (S)

Using online maps for sociological and marketing research / Creating GIS applications with online map APIs

Creating GIS applications with online map APIs

If high customization is needed in our application, then we need a map API, which usually provides a flexible interface for creating GIS map applications by programming. There are several general-purpose web mapping API:

In the following the OpenLayers API will be introduced to represent how easily a web mapping application can be made with a little programming knowledge.

OpenLayers

In this chapter we introduce another great tool for creating web-mapping applications, the OpenLayers API, which gives mapping features in a very programmer-friendly way.

OpenLayers is an open source, client side JavaScript library for making interactive web maps, viewable in nearly any web browser including mobile web browsers. As a client side library no server side script or configuration needed, it can work with several different types of map servers seamlessly as we will see later in the chapter. As a library on the one hand it gives all the tools to display maps and data easily and fast, but on the other hand opens the door to control the fine details of the processes.

OpenLayers differs from Google Maps, Bing Maps, Yahoo! Maps, etc in more ways. First of all it does not work with one kind of data or map server, but as a mapping framework gives a chance to choose from them. Google Maps API is tied to the Google Maps server, to the Google Maps images. In the case of Bing Maps and Yahoo! Maps this is the same. Contrarily, OpenLayers can combine maps from different sources. Secondly, in the case of Google Maps, and any third party services, we are not in control of the backend, and there may be some commercial restrictions. With OpenLayers we have the chance to customize the server side (we won’t do that in this curriculum), and due to the open source code we do not depend on third party companies, and we are able to see the code during debugging. We can style OpenLayers much more than we can Google Maps, and finally we can change the map projection with a suitable server to make high precision geographical operations.

The main difference in OpenLayers API compared to Google Maps API is the layer philosophy. In OpenLayers a map can contain several layer on top of each other, each layer has its own type of data from even different map server. Each layer is above and will cover up the previous one; the order that you add in the layers is important. With OpenLayers, you can arbitrarily set the overall transparency of any layer, so you are easily able to control how much layers cover each other up, and dynamically change the layer order at any time. For example the first layer can contain Google maps, the next one can be an image layer containing weather information, and the third one can be a vector layer with different markers on it.

Preparations

The OpenLayers bundle can be downloaded from the official OpenLayers website. At the time of writing the version number of the latest stable release is 2.12. The compressed file contains a lot of files and folders, but we only need the OpenLayers.js file and the img and theme folder. To start, copy these files and folders into a new empty folder, and create a file for the HTML template (e.g. index.html ):

Source-code
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>My OpenLayers Map</title>
        <link type="text/css" rel="stylesheet" href="map.css" />
        <script type="text/javascript" src="OpenLayers.js"></script>
        <script type="text/javascript">
var  map;
function init() {
//The code goes here
}
        </script>
    </head>
    <body onload="init();">
        <div id="map">
    </div>
    </body>
</html>

This is a very basic HTML5 document. In the body we set out the place for the map with the <div> element. The map will be displayed in this element in the same size. In the <head> section we load the corresponding stylesheet (map.css ), the OpenLayers JavaScript library (OpenLayers.js ), and in the last <script> block we prepare a map variable for the map object, and the init() function will be called when the page loaded. (Of course this script block should be put to a separate JavaScript file, but for the sake of simplicity, the script code goes into the HTML file.)

The map.css file contains the minimal style informations. These settings make the map fill out the whole browser window.

Source-code
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}
#map {
    width: 100%;
    height: 100%;
}    

Finally it is recommended to install a JavaScript console, where the map and its attributes can be explored. Nowadays every major browser has its own JavaScript console, in Mozilla Firefox the Firebug plugin is advisable to use.

This curriculum is not an API reference. In the following a lot of OpenLayers class and object will be introduced. We suggest everybody to consult with the official API documentation on demand for detailed description.

Map and layers

In OpenLayers on the top of the hierarchy stands the map object itself. The map object is an instance of the OpenLayers.Map class, and generally can be created by the following code:

Source-code
map = new OpenLayers.Map(map_element, options);

Here map_element is the corresponding HTML element, tipically a<div> , in which the map will be displayed, the options is a JavaScript object with key-value pairs. We need to determine at least the first parameter. Hence the following code creates a map in the div element with ‘map’ id:

Source-code
map = new OpenLayers.Map('map');

Some of the options will be described later in this chapter.

The map consists of layers, so the next task is to add at least one layer to the map. There are different kind of layers according to type of the backend server and the map data. All of them are the subclasses of the OpenLayers.Layer class. For example Google maps can be displayed with the help of the OpenLayers.Layer.Google class. Each of these layer subclasses has its own parameters according to the specific map data. Generally they can be instantiated with the following code:

Source-code
var layer = new OpenLayers.Layer.TYPE(parameters);

After creating the layers, they can be added to the map one by one:

Source-code
map.addLayer(layer1);
map.addLayer(layer2);

or altogether as an array of layers:

Source-code
map.addLayers([layer1,layer2,...]);

In OpenLayers there are two types of layers. The first one is the base layer. This is always shown. There could be more than one base layer added to the map, but only one can be selected. The other type of layer is the overlay layer. There could be several overlay layer, and their visibility can be set independently. The layer type can be set through the layer options object with the isBaseLayer property set to true or false, or the setIsBaseLayer() function of the layer (e.g. layer.setIsBaseLayer(true) ).

This is the basic knowledge for creating a map, now let us look at the different types of raster layers in the following.

Raster layers

Google maps

In OpenLayers Google Maps can be a base layer with the help of the OpenLayers.Layer.Google class. The general form of instantiation is the following:

Source-code
var google_layer = new OpenLayers.Layer.Google(layer_title, layer_options); 

Both of the parameters are optional, the layer_title is mainly for human readability, it represents the layer on certain controls such as the layer switcher control; the layer_options are specific options influencing the behavior of the map (see the API reference). For displaying Google Maps in OpenLayers the minimum amount of code can be seen below (inside the init() function):

Source-code
var map = new OpenLayers.Map('map_element');
var google_streets = new OpenLayers.Layer.Google();
map.addLayer(google_streets);
map.setCenter(new OpenLayers.LonLat(2140236.7916869, 5918060.4771277), 7);

First of all we create the map, secondly a new Google layer is generated with no parameters. Then we add the layer to the map. The fourth line is not necessary; it centers the map above Hungary and set the zoom level to a proper size. The center is given in longitude and latitude coordinates in the spherical Mercator projection which is used by Google maps. It measures the distance in meters from the center of the coordinate system.

You can open the (larger) image in new window.Google Maps data in OpenLayers showing roadmapol_google1_full.jpgGoogle Maps data in OpenLayers showing roadmap

Google offers different type of maps to display. Of course it is possible to switch between these map types. To achieve this we have to create separate layers for each map type, and then add them to the map. Each layer will be a base layer. We have to add a special control, the so called layer switcher control allowing us to switch between the layers on the map. The map type can be determined in the options object of the Google layer with the type option.

Source-code
map = new OpenLayers.Map('map', {
    projection: 'EPSG:900913',
    units: 'm',
    maxResolution: 2000
});
var google_hybrid = new OpenLayers.Layer.Google(
    "Google Hybrid",
    {type: google.maps.MapTypeId.HYBRID}
);
var google_physical = new OpenLayers.Layer.Google(
    "Google Physical",
    {type: google.maps.MapTypeId.TERRAIN}
);
var google_satellite = new OpenLayers.Layer.Google(
    "Google Satellite",
    {type: google.maps.MapTypeId.SATELLITE}
);
var google_streets = new OpenLayers.Layer.Google(
    "Google Streets",
    {type: google.maps.MapTypeId.ROADMAP}
);
map.addLayers([google_hybrid,google_physical,google_satellite,google_streets]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(2140236.7916869, 5918060.4771277), 7);

Beside the map element some other options were set in the map constructor. This example shows that there can be multiple base layers, but only one can be activated at a time.

Bing

Microsoft’s map is available through the OpenLayers.Layer.Bing class. This constructor has only one parameter, the options object which has several layer-specific option. For example the title can be set with the name option, the map type depends on the type option. For using the map an API key is needed, which can be required on the Bing Maps portal. The minimum requirements for a Bing map can be seen below:

Source-code
map = new OpenLayers.Map('map');
var bingApiKey = "api_key";
var bing = new OpenLayers.Layer.Bing({key: bingApiKey});
map.addLayer(bing);
map.setCenter(new OpenLayers.LonLat(2140236.7916869, 5918060.4771277), 7);

Bing also has different types of map. The following code shows how to create a map with all possible map types with a layer switcher control.

Source-code
map = new OpenLayers.Map('map');
var bingApiKey = "api_key";
var road = new OpenLayers.Layer.Bing({
    name: "Road",
    type: "Road",
    key: bingApiKey
});
var hybrid = new OpenLayers.Layer.Bing({
    name: "Hybrid",        
    type: "AerialWithLabels",
    key: bingApiKey
});
var aerial = new OpenLayers.Layer.Bing({
    name: "Aerial",
    type: "Aerial",
    key: bingApiKey
});
map.addLayers([road, hybrid, aerial]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(2140236.7916869, 5918060.4771277), 7);

Yahoo!

Yahoo! has announced that its map service would be closed, but at the time of this writing the service is available. OpenLayers offers access for the Yahoo! map as well by the OpenLayers.Layer.Yahoo class. The constructor has two parameters, the layer title and the layer options object. To display a minimal Yahoo! map is as easy as the following four lines of code:

Source-code
map = new OpenLayers.Map('map_element');
var yahoo = new OpenLayers.Layer.Yahoo();
map.addLayer(yahoo);
map.setCenter(new OpenLayers.LonLat(19.072265625, 47.309034247748), 7);

The only difference contrary to the maps before that Yahoo uses another projection (EPSG:4326), so the longitude and latitude coordinates are in degrees, which could be familiar from the GPS coordinates.

Creating a multi layer Yahoo! map is similar to the others. The type option is responsible for the map type, without it the default map type, the street-like map will be shown.

Source-code
map = new OpenLayers.Map('map');
var yahoo_hybrid = new OpenLayers.Layer.Yahoo(
    "Hybrid",
    {type: YAHOO_MAP_HYB}
);
var yahoo_satellite = new OpenLayers.Layer.Yahoo(
    "Satellite",
    {type: YAHOO_MAP_SAT}
);
var yahoo_street = new OpenLayers.Layer.Yahoo(
    "Street",
    
);
map.addLayers([yahoo_hybrid, yahoo_satellite, yahoo_street]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(19.072265625, 47.309034247748), 7);

OpenStreetMap

OpenStreetMap is a free, wiki-style map of the world driven by user contributed content. Unlike the previous APIs, OpenStreetMap does not have different map types, only a street-like map is accessible.

Setting up an OpenStreetMap map in OpenLayers is very simple. The constructor of the OpenLayers.Layer.OSM class has three optional parameters: the layer title, a layer url, and the layer options object. A minimal OpenStreetMap map can be achieved by the following code:

Source-code
map = new OpenLayers.Map('map');
var osm_layer = new OpenLayers.Layer.OSM();
map.addLayer(osm_layer);
map.setCenter(new OpenLayers.LonLat(2140236.7916869, 5918060.4771277), 7);

In a typical scenario at least the layer title is set for user friendly purpose.

With OpenStreetMap layer it is possible to use our own tiles of images. All we have to do (after preparing the map data and the map server) is assigning the proper url-array to the second parameter:

Source-code
    var layer = new OpenLayers.Layer.OSM("OpenCycleMap",
      ["http://a.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png",
       "http://b.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png",
       "http://c.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png"]);

Web Map Service (WMS)

Web Map Service (WMS) is an international standard developed by the Open Geospatial Consortium (OGC). WMS is implemented by many geospatial servers, for example the free and open source GeoServer and MapServer. WMS is just another protocol to serve map data through a map server to the client. WMS is typically used for displaying user created, unique data. With WMS we can publish our own map data with ease to be reachable for everyone in the world.

There are many open WMS servers which can be used to display data. We will use the map data from OSGeo servers ( http://vmap0.tiles.osgeo.org/wms/vmap0 ), but further services can be found on the internet or on this site. To find out what kind of data or layers a WMS server can be served, we have to put the?request=GetCapabilities&service=WMS&version=1.1.1 . query string after the url of the WMS server. In the response we get an XML file describing the capabilities of the service.

WMS data consists of different layers on the server side. In a request the client can determine which layers would like to get in response, but these layers will be shown in one layer on the client side.

The OpenLayers.Layer.WMS constructor has four parameters: the title of the layer, the url of the WMS server, an object with key-value pairs representing the query string parameters and parameter values, and the object of the client side layer options.

Source-code
var wms = new OpenLayers.Layer.WMS(
    layer_title,
    url,
    server_options,
    client_options
);

For a minimal WMS map we only have to specify these parameters as it can be seen in the following code:

Source-code
map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS(
    'Basic WMS layer',
    'http://vmap0.tiles.osgeo.org/wms/vmap0',
    {
        layers: 'basic'
    }
);
map.addLayer(wms);
map.setCenter(new OpenLayers.LonLat(19.072265625, 47.309034247748), 7);

Here we ask the OSGeo server to give the data belonging to the basic layer on the server.

In the following example we will have two layers. The first one will be the base layer in which three server side layers will be displayed: the basic world map, the population data, and the state boundaries. The second client side layer will be an overlay layer, and this contains the three different kinds of labels. The overlay layer can be switched on or off with the help of a layer switcher control. The second layer has a server side option which controls the transparency. This is necessary because without it the overlay layer would cover the base layer. The client opacity option makes the overlay layer transparent in 50%, so the base layer shows through the second layer.

Source-code
map = new OpenLayers.Map('map');
var wms_basic = new OpenLayers.Layer.WMS(
    'Basic WMS layer',
    'http://vmap0.tiles.osgeo.org/wms/vmap0',
    {
        layers: 'basic,population,stateboundary'
    },
    {
        isBaseLayer: true
    }
);
var wms_labels = new OpenLayers.Layer.WMS(
    'Labels',
    'http://vmap0.tiles.osgeo.org/wms/vmap0',
    {
        layers: 'clabel,ctylabel,statelabel',
        transparent: true    //empty spaces are transparents
    },
    {
        isBaseLayer: false,
        opacity: 0.5
    }
);
map.addLayers([wms_basic,wms_labels]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(19.072265625, 47.309034247748), 7);

There are further developments in the WMS standard. For example WMTS is another OGC standard for serving tiled images. This protocol is used for example by the NASA map services, and can be used through the OpenLayers.Layer.WMTS class.

Fine tuning the map and layer options

There are several options for the map and layer objects. Here we list some options which are good to know if we plan a mapping application.

Back to table of contents (J)

Új Széchenyi terv
A projekt az Európai Unió támogatásával, az Európai Szociális Alap társfinanszirozásával valósul meg.

A Társadalominformatika: moduláris tananyagok, interdiszciplináris tartalom- és tudásmenedzsment rendszerek fejlesztése az Európai Unió támogatásával, az Európai Szociális Alap társfinanszírozásával, az ELTE TÁMOP 4.1.2.A/1-11/1-2011-0056 projekt keretében valósult meg.
Generated with ELTESCORM framework