This is the P2PU Archive. If you want the current site, go to www.p2pu.org!

Online Maps with OpenLayers

OpenLayers Walkthrough

Nick Doiron's picture
Mon, 2011-02-07 18:44

(visit this page to see images, code highlighting, and formatting)

So you want to make a webpage with an OpenLayers map:

You can use http://jsfiddle.net to set up your page and show the code to us online.  We’ll explain how to get to this: http://jsfiddle.net/UAxun/45/  and you can send people a direct link to the viewer at http://jsfiddle.net/UAxun/45/show/light/

1. Add OpenLayers JavaScript file

Create your own jsFiddle page by going to jsFiddle.net.  You can click Run on the top menu bar to test your code, then click Save or Update to get a URL to your work-in-progress.

First: you need to import the OpenLayers library.  In jsFiddle, you can add a script in the left column. Click “Manage Resources” and paste the URL http://openlayers.org/api/OpenLayers.js into the text box which appears.  Then click the [+] button to add it.

If you’re making your own webpage, use this HTML: <script type=”text/javascript” src=”http://openlayers.org/api/OpenLayers.js”></script>

2. Create the interactive Map object

Now you’re ready to embed an interactive map, using map tiles from OpenStreetMap. First, you need to create a place to put it.  HTML forms the structure of the webpage.  In jsFiddle, most of the HTML is written for you.  Put this code into the top-left HTML box:

<b>A Map using OpenLayers</b>
<div id="map-div" style="width:450px;height:430px;"></div>

The first line is some HTML to describe your page.  We put it inside <b> tags so web browsers make it bold.

The second line is an HTML block, known as a <div>, with dimensions 450 pixels by 430 pixels.  This div has its id set to ”map-div”.  This becomes useful for our first line of JavaScript (bottom left section).

map = new OpenLayers.Map({div:"map-div"});

map is a variable, but instead of setting it to a number, we set it to a new OpenLayers.Map object.  One of the requirements for creating this object is sending it the ID of the div it should go into.  So we send it the word “map-div” inside quotes.  These words-in-quotes are called “strings” because the computer sees them as a list of letters.

3. Put OpenStreetMap onto your Map

You can try Run right now to see your OpenLayers controls, but your map will be empty without any sources. Our first source is going to be tiles from OpenStreetMap.  When we stack, mix, and match different sources on top of the map, so we call them layers.  Our first layer is the base layer of our map, which we'll build up from in the future.

Since we’ve all used the free editable OpenStreetMap.org (OSM), that’s the layer we’ll use.  The combination of these two maps is very common, so creating it and adding it to our map variable is easy.

var osm = new OpenLayers.Layer.OSM();
map.addLayer(osm);

We’re not quite done yet.  The map doesn’t know where to center and zoom yet.  Let’s add this line so we tell it to zoom to see everything.

map.zoomToMaxExtent();

That’s really handy to know, but what other functions can this OpenLayers.Map object do?  Every object in the OpenLayers API has a page, documenting how to create it and how to interact with it.  Here’s the page for OpenLayers.Map objects: dev.openlayers.org/docs/files/OpenLayers/Map-js.html

4. Centering the Map

Suppose we want to center the map on Cowboy Stadium in Dallas.  I typed the address into http://geohash.org and got the latitude 32.7478770 and longitude  -97.0928440.  How many digits do you need?  Using 6 digits after the decimal point gives you around 1 meter accuracy (though this depends on where you are in the world).  Most GPS devices are less accurate than that, so you don't need to add more digits.

If you look in the OpenLayers.Map reference dev.openlayers.org/docs/files/OpenLayers/Map-js.html you’ll see that there’s a setCenter function with this description:

Set the map center (and optionally, the zoom level).

Parameters



lonlat

{OpenLayers.LonLat} The new center location.

zoom

{Integer} Optional zoom level.

dragging

{Boolean} Specifies whether or not to trigger movestart/end events

forceZoomChange

{Boolean} Specifies whether or not to trigger zoom change events (needed on baseLayer change)

Only the first variable, lonlat, is required, but we’ll also zoom at the same time.  That means the line we’re writing will be

map.setCenter(centerlonlat,zoom);

Let’s create the centerlonlat and zoom variables.  Zoom needs to be an integer, so we’ll simply add a line before setMap that says

var zoom=15;

The center point has to be an OpenLayers.LonLat object, which can be created with longitude and latitude decimal numbers.

var longitude = -97.0928440;
var latitude = 32.7478770;
var centerlonlat = new OpenLayers.LonLat( longitude , latitude );

This next step will be explained shortly.  For now, just use it to adjust your map.  Change the map-creation line of your site to use two new variables:

map = new OpenLayers.Map({
   div: "map-div",
   projection: new OpenLayers.Projection('EPSG:900913'),
   'displayProjection': new OpenLayers.Projection('EPSG:4326')
});

And after the line where you created centerlonlat, but before map.setCenter, add this line:

centerlonlat=centerlonlat.transform(map.displayProjection, map.projection);

You now should have code looking like this example: http://jsfiddle.net/UAxun/46/

What are those projections and transforms for?

Whenever you make a flat, 2D map of Earth, you need to choose a projection such as Mercator or Peters to make it fit on one page.  The earth is not a perfect sphere, so specialists have chosen different methods to place latitude and longitude lines.  For example, “local” coordinate systems are offset from the Earth’s center to make a single part of the map -- such as North America or Europe -- closer to a true sphere (the red coordinate system matching the top left of the circle below), but they are unusually offset in other parts of the world.  Other coordinate systems use the true center of the Earth, but are distorted at the equator and the poles.

If you use two coordinate systems on your map, or use one with meters for units and another with miles, they won’t line up properly.  To easily use OpenStreetMap and OpenLayers, we’re going to use a projection that uses latitude and longitude degrees, then convert them to a more common projection.  You rarely memorize projections.  I used these projections because they are suggested by the example on wiki.OpenStreetMap.org.  Whenever you get a new source of geodata, it will give you a projection, or you can search and find its projection, or just check to see if their data lines up with your map.

The projections that we are using were suggested by OpenStreetMap’s article on OpenLayers: http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example#A_little_more_extensive_example

Comments

To see the OpenLayers

Nick Doiron's picture
Nick Doiron
Mon, 2011-02-07 18:47

To see the OpenLayers Walkthrough with proper formatting, use this link: https://docs.google.com/document/pub?id=1-T42OaXSCB0nXtC607kE8ecFZrRMJqb...

'Adding icons to the map' will be published soon.

nice write-up Nick; thanks

Sean Horgan's picture
Sean Horgan
Mon, 2011-02-07 19:45

nice write-up Nick; thanks for the google docs link as well.

Until I went through this

Mita Williams's picture
Mita Williams
Tue, 2011-02-15 03:32

Until I went through this exercise, I couldn't quite wrap my mind on what jsFiddle was. Now, I find I really like this environment to work and play around in. I might be using jsFiddle quite a bit after this course is done!