OpenLayers

When working with maps and geographical information systems styling features is very important, on one hand it can make your map more flashy and on the other it can help to classify or organize your features visually.For example, in a map where you show the most populated cities of the world you can use circles with different color and radius.

OpenLayers offers the option to style our features in different ways:

  • using a style structure for the whole layer
  • styling a concrete feature

The order applying these style go from "out" to "in", that is, given a feature first is applied the layer style and later the concrete style the feature could have. And to show this nothing better than an example.

Supposing we have a Vector layer with some circles:

var vectorLayer = new OpenLayers.Layer.Vector("Vector"); // Create 50 random features, and give them a "type" attribute that // will be used to style them by size. var features = new Array(50); for (var i=0; i<features.length; i++) { features[i] = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point( (360 * Math.random()) - 180, (180 * Math.random()) - 90 ), { type: 5 + parseInt(5 * Math.random()) } ); } vectorLayer.addFeatures(features);

Now we define a layer style which applied to the layer and a feature style applied directly to a concrete feature:

var myStyles = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ pointRadius: 3, // sized according to type attribute fillColor: "#ff5566", strokeColor: "#ff9933", strokeWidth: 2, graphicZIndex: 1 }) }); vectorLayer.styleMap = myStyles; features[0].style = { pointRadius: 9, // sized according to type attribute fillColor: "#225566", strokeColor: "#ff9933", strokeWidth: 4, graphicZIndex: 1 };

As we expect the result is:

I have working on a web page using OpenLayers which among others shows a OpenStreetMap layer.

The issue is I need to move the mouse over the map and print on a label the tile name in the form level/x/y, for example, 5/15/10.

The first thing to do is to register a listener to the OpenLayers map object, then for every mouse event we need to get the lonlat and translate it from current map projection to the EPSG:4326 (WGS84).

 

map.events.register( 'mousemove', this, function(evt){ var lonlat = new OpenLayers.LonLat(0, 0); if(evt){ lonlat = map.getLonLatFromPixel(evt.xy); lonlat.transform(this.map.getProjectionObject(), new OpenLayers. Projection("EPSG:4326") ); } tileX = long2tile(lonlat.lon, map.getZoom()); tileY = latg2tile(lonlat.lat, map.getZoom()); tileZ = map.getZoom(); });

To compute the tile X,Y grid coordinate from latlon you can use next functions, obtained from OpenStreetMaps site:

// Functions to compute tiles from lat/lon function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }