added Graticule control and Util.getFormattedLonLat function. Thanks madair for this excellent patch. p=madair, r=me (closes #1083)

git-svn-id: http://svn.openlayers.org/trunk/openlayers@9757 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
This commit is contained in:
ahocevar
2009-10-24 05:36:34 +00:00
parent a864838e96
commit 6d43a28da6
7 changed files with 528 additions and 0 deletions

102
examples/graticule.html Normal file
View File

@@ -0,0 +1,102 @@
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>OpenLayers Graticule Example</title>
<link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
#map {
width: 600px;
height: 300px;
border: 1px solid black;
float:left;
}
#map2 {
width: 400px;
height: 400px;
border: 1px solid black;
float:left;
}
</style>
<script src="../lib/OpenLayers.js"></script>
<script src="http://proj4js.org/lib/proj4js-compressed.js"></script>
<script type="text/javascript">
Proj4js.defs["EPSG:42304"]="+title=Atlas of Canada, LCC +proj=lcc +lat_1=49 +lat_2=77 +lat_0=49 +lon_0=-95 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";
var map1, map2;
function init(){
initLonLat();
initProjected();
}
function initLonLat(){
map1 = new OpenLayers.Map('map', {
controls: [
new OpenLayers.Control.Graticule({
numPoints: 2,
labelled: true,
visible: true
}),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Navigation()
]
});
var ol_wms = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0",
{layers: 'basic'}, {wrapDateLine: true} );
map1.addLayers([ol_wms]);
if (!map1.getCenter()) map1.zoomToMaxExtent();
};
function initProjected(){
var extent = new OpenLayers.Bounds(-2200000,-712631,3072800,3840000);
var mapOptions = {
controls: [
new OpenLayers.Control.Graticule({
labelled: true,
targetSize: 200
}),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Navigation()
],
//scales: tempScales,
maxExtent: extent,
maxResolution: 50000,
units: 'm',
projection: 'EPSG:42304'
};
map2 = new OpenLayers.Map('map2', mapOptions);
var dm_wms = new OpenLayers.Layer.WMS( "DM Solutions Demo",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap", {
layers: "bathymetry",
format: "image/png"
},{
singleTile: true
});
map2.addLayers([dm_wms]);
if (!map2.getCenter()) map2.zoomToExtent(extent);
}
</script>
</head>
<body onload="init()">
<h1 id="title">Graticule Example</h1>
<div id="tags">
</div>
<p id="shortdesc">
Adds a Graticule control to the map to display a grid of
latitude and longitude.
</p>
<div id="map" class="smallmap"></div>
<div id="map2" class="smallmap"></div>
<div id="docs"></div>
</body>
</html>

View File

@@ -168,6 +168,7 @@
"OpenLayers/Control/NavigationHistory.js",
"OpenLayers/Control/Measure.js",
"OpenLayers/Control/WMSGetFeatureInfo.js",
"OpenLayers/Control/Graticule.js",
"OpenLayers/Geometry.js",
"OpenLayers/Geometry/Rectangle.js",
"OpenLayers/Geometry/Collection.js",

View File

@@ -0,0 +1,328 @@
/* Copyright (c) 2006-2009 MetaCarta, Inc., published under a modified BSD license.
* See http://svn.openlayers.org/trunk/openlayers/repository-license.txt
* for the full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Graticule
* The Graticule displays a grid of latitude/longitude lines reprojected on
* the map.
*
* Inherits from:
* - <OpenLayers.Control>
*
*/
OpenLayers.Control.Graticule = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: intervals
* {Array(Float)} A list of possible graticule widths in degrees.
*/
intervals: [ 45, 30, 20, 10, 5, 2, 1,
0.5, 0.2, 0.1, 0.05, 0.01,
0.005, 0.002, 0.001 ],
/**
* APIProperty: displayInLayerSwitcher
* {Boolean} Allows the Graticule control to be switched on and off.
* defaults to true.
*/
displayInLayerSwitcher: true,
/**
* APIProperty: visible
* {Boolean} should the graticule be initially visible (default=true)
*/
visible: true,
/**
* APIProperty: numPoints
* {Integer} The number of points to use in each graticule line. Higher
* numbers result in a smoother curve for projected maps
*/
numPoints: 50,
/**
* APIProperty: targetSize
* {Integer} The maximum size of the grid in pixels on the map
*/
targetSize: 200,
/**
* APIProperty: layerName
* {String} the name to be displayed in the layer switcher
*/
layerName: "Graticule",
/**
* APIProperty: labelled
* {Boolean} Should the graticule lines be labelled?. default=true
*/
labelled: true,
/**
* APIProperty: labelFormat
* {String} the format of the labels, default = 'dm'. See
* <OpenLayers.Util.getFormattedLonLat> for other options.
*/
labelFormat: 'dm',
/**
* APIProperty: lineSymbolizer
* {symbolizer} the symbolizer used to render lines
*/
lineSymbolizer: {
strokeColor: "#333",
strokeWidth: 1,
strokeOpacity: 0.5
},
/**
* APIProperty: labelSymbolizer
* {symbolizer} the symbolizer used to render labels
*/
labelSymbolizer: {},
/**
* Property: gratLayer
* {OpenLayers.Layer.Vector} vector layer used to draw the graticule on
*/
gratLayer: null,
/**
* Constructor: OpenLayers.Control.Graticule
* Create a new graticule control to display a grid of latitude longitude
* lines.
*
* Parameters:
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.labelSymbolizer.stroke = false;
this.labelSymbolizer.fill = false;
this.labelSymbolizer.label = "${label}";
this.labelSymbolizer.labelAlign = "${labelAlign}";
this.labelSymbolizer.labelXOffset = "${xOffset}";
this.labelSymbolizer.labelYOffset = "${yOffset}";
},
/**
* Method: draw
*
* initializes the graticule layer and does the initial update
*
* Returns:
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if (!this.gratLayer) {
var gratStyle = new OpenLayers.Style({},{
rules: [new OpenLayers.Rule({'symbolizer':
{"Point":this.labelSymbolizer,
"Line":this.lineSymbolizer}
})]
});
this.gratLayer = new OpenLayers.Layer.Vector(this.layerName, {
styleMap: new OpenLayers.StyleMap({'default':gratStyle}),
visibility: this.visible,
displayInLayerSwitcher: this.displayInLayerSwitcher
});
this.map.addLayer(this.gratLayer);
}
this.map.events.register('moveend', this, this.update);
this.update();
return this.div;
},
/**
* Method: update
*
* calculates the grid to be displayed and actually draws it
*
* Returns:
* {DOMElement}
*/
update: function() {
//wait for the map to be initialized before proceeding
var mapBounds = this.map.getExtent();
if (!mapBounds) {
return;
}
var mapRect = mapBounds.toGeometry();
//clear out the old grid
this.gratLayer.destroyFeatures();
//get the projection objects required
var llProj = new OpenLayers.Projection("EPSG:4326");
var mapProj = this.map.getProjectionObject();
var mapRes = this.map.getResolution();
//if the map is in lon/lat, then the lines are straight and only one
//point is required
if (mapProj.proj && mapProj.proj.projName == "longlat") {
this.numPoints = 1;
}
//get the map center in EPSG:4326
var mapCenter = this.map.getCenter(); //lon and lat here are really map x and y
var mapCenterLL = new OpenLayers.Pixel(mapCenter.lon, mapCenter.lat);
OpenLayers.Projection.transform(mapCenterLL, mapProj, llProj);
/* This block of code determines the lon/lat interval to use for the
* grid by calculating the diagonal size of one grid cell at the map
* center. Iterates through the intervals array until the diagonal
* length is less than the targetSize option.
*/
//find lat/lon interval that results in a grid of less than the target size
var testSq = this.targetSize*mapRes;
testSq *= testSq; //compare squares rather than doing a square root to save time
var llInterval;
for (var i=0; i<this.intervals.length; ++i) {
llInterval = this.intervals[i]; //could do this for both x and y??
var delta = llInterval/2;
var p1 = mapCenterLL.offset(new OpenLayers.Pixel(-delta, -delta)); //test coords in EPSG:4326 space
var p2 = mapCenterLL.offset(new OpenLayers.Pixel( delta, delta));
OpenLayers.Projection.transform(p1, llProj, mapProj); // convert them back to map projection
OpenLayers.Projection.transform(p2, llProj, mapProj);
var distSq = (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y);
if (distSq <= testSq) {
break;
}
}
//alert(llInterval);
//round the LL center to an even number based on the interval
mapCenterLL.x = Math.floor(mapCenterLL.x/llInterval)*llInterval;
mapCenterLL.y = Math.floor(mapCenterLL.y/llInterval)*llInterval;
//TODO adjust for minutses/seconds?
/* The following 2 blocks calculate the nodes of the grid along a
* line of constant longitude (then latitiude) running through the
* center of the map until it reaches the map edge. The calculation
* goes from the center in both directions to the edge.
*/
//get the central longitude line, increment the latitude
var iter = 0
var centerLonPoints = [mapCenterLL.clone()];
var newPoint = mapCenterLL.clone();
var mapXY;
do {
newPoint = newPoint.offset(new OpenLayers.Pixel(0,llInterval));
mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
centerLonPoints.unshift(newPoint);
} while (mapBounds.containsPixel(mapXY) && ++iter<1000);
newPoint = mapCenterLL.clone();
do {
newPoint = newPoint.offset(new OpenLayers.Pixel(0,-llInterval));
mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
centerLonPoints.push(newPoint);
} while (mapBounds.containsPixel(mapXY) && ++iter<1000);
//get the central latitude line, increment the longitude
iter = 0
var centerLatPoints = [mapCenterLL.clone()];
newPoint = mapCenterLL.clone();
do {
newPoint = newPoint.offset(new OpenLayers.Pixel(-llInterval, 0));
mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
centerLatPoints.unshift(newPoint);
} while (mapBounds.containsPixel(mapXY) && ++iter<1000);
newPoint = mapCenterLL.clone();
do {
newPoint = newPoint.offset(new OpenLayers.Pixel(llInterval, 0));
mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
centerLatPoints.push(newPoint);
} while (mapBounds.containsPixel(mapXY) && ++iter<1000);
//now generate a line for each node in the central lat and lon lines
//first loop over constant longitude
var lines = [];
for(var i=0; i < centerLatPoints.length; ++i) {
var lon = centerLatPoints[i].x;
var pointList = [];
var labelPoint = null;
var latEnd = Math.min(centerLonPoints[0].y, 90);
var latStart = Math.max(centerLonPoints[centerLonPoints.length - 1].y, -90);
var latDelta = (latEnd - latStart)/this.numPoints;
var lat = latStart;
for(var j=0; j<= this.numPoints; ++j) {
var gridPoint = new OpenLayers.Geometry.Point(lon,lat);
gridPoint.transform(llProj, mapProj);
pointList.push(gridPoint);
lat += latDelta;
if (gridPoint.y >= mapBounds.bottom && !labelPoint) {
labelPoint = gridPoint;
}
}
if (this.labelled) {
//keep track of when this grid line crosses the map bounds to set
//the label position
//labels along the bottom, add 10 pixel offset up into the map
//TODO add option for labels on top
var labelPos = new OpenLayers.Geometry.Point(labelPoint.x,mapBounds.bottom);
var labelAttrs = {
value: lon,
label: this.labelled?OpenLayers.Util.getFormattedLonLat(lon, "lon", this.labelFormat):"",
labelAlign: "cb",
xOffset: 0,
yOffset: 2
};
this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));
}
var geom = new OpenLayers.Geometry.LineString(pointList);
lines.push(new OpenLayers.Feature.Vector(geom));
}
//now draw the lines of constant latitude
for (var j=0; j < centerLonPoints.length; ++j) {
lat = centerLonPoints[j].y;
if (lat<-90 || lat>90) { //latitudes only valid between -90 and 90
continue;
}
var pointList = [];
var lonStart = centerLatPoints[0].x;
var lonEnd = centerLatPoints[centerLatPoints.length - 1].x;
var lonDelta = (lonEnd - lonStart)/this.numPoints;
var lon = lonStart;
var labelPoint = null;
for(var i=0; i <= this.numPoints ; ++i) {
var gridPoint = new OpenLayers.Geometry.Point(lon,lat);
gridPoint.transform(llProj, mapProj);
pointList.push(gridPoint);
lon += lonDelta;
if (gridPoint.x < mapBounds.right) {
labelPoint = gridPoint;
}
}
if (this.labelled) {
//keep track of when this grid line crosses the map bounds to set
//the label position
//labels along the right, 30 pixel offset left into the map
//TODO add option for labels on left
var labelPos = new OpenLayers.Geometry.Point(mapBounds.right, labelPoint.y);
var labelAttrs = {
value: lat,
label: this.labelled?OpenLayers.Util.getFormattedLonLat(lat, "lat", this.labelFormat):"",
labelAlign: "rb",
xOffset: -2,
yOffset: 2
};
this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));
}
var geom = new OpenLayers.Geometry.LineString(pointList);
lines.push(new OpenLayers.Feature.Vector(geom));
}
this.gratLayer.addFeatures(lines);
},
CLASS_NAME: "OpenLayers.Control.Graticule"
});

View File

@@ -81,6 +81,12 @@ OpenLayers.Lang.en = {
"target='_blank'>click here</a>",
'scale': "Scale = 1 : ${scaleDenom}",
//labels for the graticule control
'W': 'W',
'E': 'E',
'N': 'N',
'S': 'S',
// console message
'layerAlreadyAdded':

View File

@@ -958,6 +958,8 @@ OpenLayers.Util.getParameters = function(url) {
var end = OpenLayers.String.contains(url, "#") ?
url.indexOf('#') : url.length;
paramsString = url.substring(start, end);
} else {
paramsString = url;
}
var parameters = {};
@@ -1642,3 +1644,61 @@ OpenLayers.Util.getScrollbarWidth = function() {
return scrollbarWidth;
};
/**
* APIFunction: getFormattedLonLat
* This function will return latitude or longitude value formatted as
*
* Parameters:
* coordinate - {Float} the coordinate value to be formatted
* axis - {String} value of either 'lat' or 'lon' to indicate which axis is to
* to be formatted (default = lat)
* dmsOption - {String} specify the precision of the output can be one of:
* 'dms' show degrees minutes and seconds
* 'dm' show only degrees and minutes
* 'd' show only degrees
*
* Returns:
* {String} the coordinate value formatted as a string
*/
OpenLayers.Util.getFormattedLonLat = function(coordinate, axis, dmsOption) {
if (!dmsOption) {
dmsOption = 'dms'; //default to show degree, minutes, seconds
}
var abscoordinate = Math.abs(coordinate)
var coordinatedegrees = Math.floor(abscoordinate);
var coordinateminutes = (abscoordinate - coordinatedegrees)/(1/60);
var tempcoordinateminutes = coordinateminutes;
coordinateminutes = Math.floor(coordinateminutes);
var coordinateseconds = (tempcoordinateminutes - coordinateminutes)/(1/60);
coordinateseconds = Math.round(coordinateseconds*10);
coordinateseconds /= 10;
if( coordinatedegrees < 10 ) {
coordinatedegrees = "0" + coordinatedegrees;
}
var str = coordinatedegrees + " "; //get degree symbol here somehow for SVG/VML labelling
if (dmsOption.indexOf('dm') >= 0) {
if( coordinateminutes < 10 ) {
coordinateminutes = "0" + coordinateminutes;
}
str += coordinateminutes + "'";
if (dmsOption.indexOf('dms') >= 0) {
if( coordinateseconds < 10 ) {
coordinateseconds = "0" + coordinateseconds;
}
str += coordinateseconds + '"';
}
}
if (axis == "lon") {
str += coordinate < 0 ? OpenLayers.i18n("W") : OpenLayers.i18n("E");
} else {
str += coordinate < 0 ? OpenLayers.i18n("S") : OpenLayers.i18n("N");
}
return str;
};

View File

@@ -0,0 +1,30 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script src="http://proj4js.org/lib/proj4js-compressed.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(2);
var options = {};
map = new OpenLayers.Map("map",{projection:"EPSG:4326"});
var layer = new OpenLayers.Layer.WMS();
map.addLayers([layer]);
var control = new OpenLayers.Control.Graticule(options);
map.addControl(control);
map.zoomToMaxExtent();
t.ok(control.gratLayer instanceof OpenLayers.Layer.Vector,
"constructor sets layer correctly");
t.ok(control.gratLayer.features.length > 0,
"graticule has features");
control.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@@ -15,6 +15,7 @@
<li>Control/DragPan.html</li>
<li>Control/DrawFeature.html</li>
<li>Control/GetFeature.html</li>
<li>Control/Graticule.html</li>
<li>Control/KeyboardDefaults.html</li>
<li>Control/LayerSwitcher.html</li>
<li>Control/Measure.html</li>