option is
* provided or if you intend to call the
method later.
* options - {Object} Optional object with properties to tag onto the map.
*
* Examples:
* (code)
* // create a map with default options in an element with the id "map1"
* var map = new OpenLayers.Map("map1");
*
* // create a map with non-default options in an element with id "map2"
* var options = {
* maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
* maxResolution: 156543,
* units: 'm',
* projection: "EPSG:41001"
* };
* var map = new OpenLayers.Map("map2", options);
*
* // map with non-default options - same as above but with a single argument
* var map = new OpenLayers.Map({
* div: "map_id",
* maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
* maxResolution: 156543,
* units: 'm',
* projection: "EPSG:41001"
* });
*
* // create a map without a reference to a container - call render later
* var map = new OpenLayers.Map({
* maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
* maxResolution: 156543,
* units: 'm',
* projection: "EPSG:41001"
* });
* (end)
*/
initialize: function (div, options) {
// If only one argument is provided, check if it is an object.
if(arguments.length === 1 && typeof div === "object") {
options = div;
div = options && options.div;
}
// Simple-type defaults are set in class definition.
// Now set complex-type defaults
this.tileSize = new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH,
OpenLayers.Map.TILE_HEIGHT);
this.maxExtent = new OpenLayers.Bounds(-180, -90, 180, 90);
this.paddingForPopups = new OpenLayers.Bounds(15, 15, 15, 15);
this.theme = OpenLayers._getScriptLocation() +
'theme/default/style.css';
// now override default options
OpenLayers.Util.extend(this, options);
// initialize layers array
this.layers = [];
this.id = OpenLayers.Util.createUniqueID("OpenLayers.Map_");
this.div = OpenLayers.Util.getElement(div);
if(!this.div) {
this.div = document.createElement("div");
this.div.style.height = "1px";
this.div.style.width = "1px";
}
OpenLayers.Element.addClass(this.div, 'olMap');
// the viewPortDiv is the outermost div we modify
var id = this.id + "_OpenLayers_ViewPort";
this.viewPortDiv = OpenLayers.Util.createDiv(id, null, null, null,
"relative", null,
"hidden");
this.viewPortDiv.style.width = "100%";
this.viewPortDiv.style.height = "100%";
this.viewPortDiv.className = "olMapViewport";
this.div.appendChild(this.viewPortDiv);
// the eventsDiv is where we listen for all map events
var eventsDiv = document.createElement("div");
eventsDiv.id = this.id + "_events";
eventsDiv.style.position = "absolute";
eventsDiv.style.width = "100%";
eventsDiv.style.height = "100%";
eventsDiv.style.zIndex = this.Z_INDEX_BASE.Control - 1;
this.viewPortDiv.appendChild(eventsDiv);
this.eventsDiv = eventsDiv;
this.events = new OpenLayers.Events(
this, this.eventsDiv, this.EVENT_TYPES, this.fallThrough,
{includeXY: true}
);
// the layerContainerDiv is the one that holds all the layers
id = this.id + "_OpenLayers_Container";
this.layerContainerDiv = OpenLayers.Util.createDiv(id);
this.layerContainerDiv.style.zIndex=this.Z_INDEX_BASE['Popup']-1;
this.eventsDiv.appendChild(this.layerContainerDiv);
this.updateSize();
if(this.eventListeners instanceof Object) {
this.events.on(this.eventListeners);
}
// update the map size and location before the map moves
this.events.register("movestart", this, this.updateSize);
// Because Mozilla does not support the "resize" event for elements
// other than "window", we need to put a hack here.
if (OpenLayers.String.contains(navigator.appName, "Microsoft")) {
// If IE, register the resize on the div
this.events.register("resize", this, this.updateSize);
} else {
// Else updateSize on catching the window's resize
// Note that this is ok, as updateSize() does nothing if the
// map's size has not actually changed.
this.updateSizeDestroy = OpenLayers.Function.bind(this.updateSize,
this);
OpenLayers.Event.observe(window, 'resize',
this.updateSizeDestroy);
}
// only append link stylesheet if the theme property is set
if(this.theme) {
// check existing links for equivalent url
var addNode = true;
var nodes = document.getElementsByTagName('link');
for(var i=0, len=nodes.length; i=0; --i) {
this.controls[i].destroy();
}
this.controls = null;
}
if (this.layers != null) {
for (var i = this.layers.length - 1; i>=0; --i) {
//pass 'false' to destroy so that map wont try to set a new
// baselayer after each baselayer is removed
this.layers[i].destroy(false);
}
this.layers = null;
}
if (this.viewPortDiv) {
this.div.removeChild(this.viewPortDiv);
}
this.viewPortDiv = null;
if(this.eventListeners) {
this.events.un(this.eventListeners);
this.eventListeners = null;
}
this.events.destroy();
this.events = null;
},
/**
* APIMethod: setOptions
* Change the map options
*
* Parameters:
* options - {Object} Hashtable of options to tag to the map
*/
setOptions: function(options) {
var updatePxExtent = this.minPx &&
options.restrictedExtent != this.restrictedExtent;
OpenLayers.Util.extend(this, options);
// force recalculation of minPx and maxPx
updatePxExtent && this.moveTo(this.getCachedCenter(), this.zoom, {
forceZoomChange: true
});
},
/**
* APIMethod: getTileSize
* Get the tile size for the map
*
* Returns:
* {}
*/
getTileSize: function() {
return this.tileSize;
},
/**
* APIMethod: getBy
* Get a list of objects given a property and a match item.
*
* Parameters:
* array - {String} A property on the map whose value is an array.
* property - {String} A property on each item of the given array.
* match - {String | Object} A string to match. Can also be a regular
* expression literal or object. In addition, it can be any object
* with a method named test. For reqular expressions or other, if
* match.test(map[array][i][property]) evaluates to true, the item will
* be included in the array returned. If no items are found, an empty
* array is returned.
*
* Returns:
* {Array} An array of items where the given property matches the given
* criteria.
*/
getBy: function(array, property, match) {
var test = (typeof match.test == "function");
var found = OpenLayers.Array.filter(this[array], function(item) {
return item[property] == match || (test && match.test(item[property]));
});
return found;
},
/**
* APIMethod: getLayersBy
* Get a list of layers with properties matching the given criteria.
*
* Parameter:
* property - {String} A layer property to be matched.
* match - {String | Object} A string to match. Can also be a regular
* expression literal or object. In addition, it can be any object
* with a method named test. For reqular expressions or other, if
* match.test(layer[property]) evaluates to true, the layer will be
* included in the array returned. If no layers are found, an empty
* array is returned.
*
* Returns:
* {Array()} A list of layers matching the given criteria.
* An empty array is returned if no matches are found.
*/
getLayersBy: function(property, match) {
return this.getBy("layers", property, match);
},
/**
* APIMethod: getLayersByName
* Get a list of layers with names matching the given name.
*
* Parameter:
* match - {String | Object} A layer name. The name can also be a regular
* expression literal or object. In addition, it can be any object
* with a method named test. For reqular expressions or other, if
* name.test(layer.name) evaluates to true, the layer will be included
* in the list of layers returned. If no layers are found, an empty
* array is returned.
*
* Returns:
* {Array()} A list of layers matching the given name.
* An empty array is returned if no matches are found.
*/
getLayersByName: function(match) {
return this.getLayersBy("name", match);
},
/**
* APIMethod: getLayersByClass
* Get a list of layers of a given class (CLASS_NAME).
*
* Parameter:
* match - {String | Object} A layer class name. The match can also be a
* regular expression literal or object. In addition, it can be any
* object with a method named test. For reqular expressions or other,
* if type.test(layer.CLASS_NAME) evaluates to true, the layer will
* be included in the list of layers returned. If no layers are
* found, an empty array is returned.
*
* Returns:
* {Array()} A list of layers matching the given class.
* An empty array is returned if no matches are found.
*/
getLayersByClass: function(match) {
return this.getLayersBy("CLASS_NAME", match);
},
/**
* APIMethod: getControlsBy
* Get a list of controls with properties matching the given criteria.
*
* Parameter:
* property - {String} A control property to be matched.
* match - {String | Object} A string to match. Can also be a regular
* expression literal or object. In addition, it can be any object
* with a method named test. For reqular expressions or other, if
* match.test(layer[property]) evaluates to true, the layer will be
* included in the array returned. If no layers are found, an empty
* array is returned.
*
* Returns:
* {Array()} A list of controls matching the given
* criteria. An empty array is returned if no matches are found.
*/
getControlsBy: function(property, match) {
return this.getBy("controls", property, match);
},
/**
* APIMethod: getControlsByClass
* Get a list of controls of a given class (CLASS_NAME).
*
* Parameter:
* match - {String | Object} A control class name. The match can also be a
* regular expression literal or object. In addition, it can be any
* object with a method named test. For reqular expressions or other,
* if type.test(control.CLASS_NAME) evaluates to true, the control will
* be included in the list of controls returned. If no controls are
* found, an empty array is returned.
*
* Returns:
* {Array()} A list of controls matching the given class.
* An empty array is returned if no matches are found.
*/
getControlsByClass: function(match) {
return this.getControlsBy("CLASS_NAME", match);
},
/********************************************************/
/* */
/* Layer Functions */
/* */
/* The following functions deal with adding and */
/* removing Layers to and from the Map */
/* */
/********************************************************/
/**
* APIMethod: getLayer
* Get a layer based on its id
*
* Parameter:
* id - {String} A layer id
*
* Returns:
* {} The Layer with the corresponding id from the map's
* layer collection, or null if not found.
*/
getLayer: function(id) {
var foundLayer = null;
for (var i=0, len=this.layers.length; i}
* zIdx - {int}
*/
setLayerZIndex: function (layer, zIdx) {
layer.setZIndex(
this.Z_INDEX_BASE[layer.isBaseLayer ? 'BaseLayer' : 'Overlay']
+ zIdx * 5 );
},
/**
* Method: resetLayersZIndex
* Reset each layer's z-index based on layer's array index
*/
resetLayersZIndex: function() {
for (var i=0, len=this.layers.length; i}
*/
addLayer: function (layer) {
for(var i=0, len=this.layers.length; i )}
*/
addLayers: function (layers) {
for (var i=0, len=layers.length; i}
* setNewBaseLayer - {Boolean} Default is true
*/
removeLayer: function(layer, setNewBaseLayer) {
if (this.events.triggerEvent("preremovelayer", {layer: layer}) === false) {
return;
}
if (setNewBaseLayer == null) {
setNewBaseLayer = true;
}
if (layer.isFixed) {
this.viewPortDiv.removeChild(layer.div);
} else {
this.layerContainerDiv.removeChild(layer.div);
}
OpenLayers.Util.removeItem(this.layers, layer);
layer.removeMap(this);
layer.map = null;
// if we removed the base layer, need to set a new one
if(this.baseLayer == layer) {
this.baseLayer = null;
if(setNewBaseLayer) {
for(var i=0, len=this.layers.length; i}
*
* Returns:
* {Integer} The current (zero-based) index of the given layer in the map's
* layer stack. Returns -1 if the layer isn't on the map.
*/
getLayerIndex: function (layer) {
return OpenLayers.Util.indexOf(this.layers, layer);
},
/**
* APIMethod: setLayerIndex
* Move the given layer to the specified (zero-based) index in the layer
* list, changing its z-index in the map display. Use
* map.getLayerIndex() to find out the current index of a layer. Note
* that this cannot (or at least should not) be effectively used to
* raise base layers above overlays.
*
* Parameters:
* layer - {}
* idx - {int}
*/
setLayerIndex: function (layer, idx) {
var base = this.getLayerIndex(layer);
if (idx < 0) {
idx = 0;
} else if (idx > this.layers.length) {
idx = this.layers.length;
}
if (base != idx) {
this.layers.splice(base, 1);
this.layers.splice(idx, 0, layer);
for (var i=0, len=this.layers.length; i}
* delta - {int}
*/
raiseLayer: function (layer, delta) {
var idx = this.getLayerIndex(layer) + delta;
this.setLayerIndex(layer, idx);
},
/**
* APIMethod: setBaseLayer
* Allows user to specify one of the currently-loaded layers as the Map's
* new base layer.
*
* Parameters:
* newBaseLayer - {}
*/
setBaseLayer: function(newBaseLayer) {
if (newBaseLayer != this.baseLayer) {
// ensure newBaseLayer is already loaded
if (OpenLayers.Util.indexOf(this.layers, newBaseLayer) != -1) {
// preserve center and scale when changing base layers
var center = this.getCachedCenter();
var newResolution = OpenLayers.Util.getResolutionFromScale(
this.getScale(), newBaseLayer.units
);
// make the old base layer invisible
if (this.baseLayer != null && !this.allOverlays) {
this.baseLayer.setVisibility(false);
}
// set new baselayer
this.baseLayer = newBaseLayer;
// Increment viewRequestID since the baseLayer is
// changing. This is used by tiles to check if they should
// draw themselves.
this.viewRequestID++;
if(!this.allOverlays || this.baseLayer.visibility) {
this.baseLayer.setVisibility(true);
}
// recenter the map
if (center != null) {
// new zoom level derived from old scale
var newZoom = this.getZoomForResolution(
newResolution || this.resolution, true
);
// zoom and force zoom change
this.setCenter(center, newZoom, false, true);
}
this.events.triggerEvent("changebaselayer", {
layer: this.baseLayer
});
}
}
},
/********************************************************/
/* */
/* Control Functions */
/* */
/* The following functions deal with adding and */
/* removing Controls to and from the Map */
/* */
/********************************************************/
/**
* APIMethod: addControl
* Add the passed over control to the map. Optionally
* position the control at the given pixel.
*
* Parameters:
* control - {}
* px - {}
*/
addControl: function (control, px) {
this.controls.push(control);
this.addControlToMap(control, px);
},
/**
* APIMethod: addControls
* Add all of the passed over controls to the map.
* You can pass over an optional second array
* with pixel-objects to position the controls.
* The indices of the two arrays should match and
* you can add null as pixel for those controls
* you want to be autopositioned.
*
* Parameters:
* controls - {Array()}
* pixels - {Array()}
*/
addControls: function (controls, pixels) {
var pxs = (arguments.length === 1) ? [] : pixels;
for (var i=0, len=controls.length; i}
* px - {}
*/
addControlToMap: function (control, px) {
// If a control doesn't have a div at this point, it belongs in the
// viewport.
control.outsideViewport = (control.div != null);
// If the map has a displayProjection, and the control doesn't, set
// the display projection.
if (this.displayProjection && !control.displayProjection) {
control.displayProjection = this.displayProjection;
}
control.setMap(this);
var div = control.draw(px);
if (div) {
if(!control.outsideViewport) {
div.style.zIndex = this.Z_INDEX_BASE['Control'] +
this.controls.length;
this.viewPortDiv.appendChild( div );
}
}
if(control.autoActivate) {
control.activate();
}
},
/**
* APIMethod: getControl
*
* Parameters:
* id - {String} ID of the control to return.
*
* Returns:
* {} The control from the map's list of controls
* which has a matching 'id'. If none found,
* returns null.
*/
getControl: function (id) {
var returnControl = null;
for(var i=0, len=this.controls.length; i} The control to remove.
*/
removeControl: function (control) {
//make sure control is non-null and actually part of our map
if ( (control) && (control == this.getControl(control.id)) ) {
if (control.div && (control.div.parentNode == this.viewPortDiv)) {
this.viewPortDiv.removeChild(control.div);
}
OpenLayers.Util.removeItem(this.controls, control);
}
},
/********************************************************/
/* */
/* Popup Functions */
/* */
/* The following functions deal with adding and */
/* removing Popups to and from the Map */
/* */
/********************************************************/
/**
* APIMethod: addPopup
*
* Parameters:
* popup - {}
* exclusive - {Boolean} If true, closes all other popups first
*/
addPopup: function(popup, exclusive) {
if (exclusive) {
//remove all other popups from screen
for (var i = this.popups.length - 1; i >= 0; --i) {
this.removePopup(this.popups[i]);
}
}
popup.map = this;
this.popups.push(popup);
var popupDiv = popup.draw();
if (popupDiv) {
popupDiv.style.zIndex = this.Z_INDEX_BASE['Popup'] +
this.popups.length;
this.layerContainerDiv.appendChild(popupDiv);
}
},
/**
* APIMethod: removePopup
*
* Parameters:
* popup - {}
*/
removePopup: function(popup) {
OpenLayers.Util.removeItem(this.popups, popup);
if (popup.div) {
try { this.layerContainerDiv.removeChild(popup.div); }
catch (e) { } // Popups sometimes apparently get disconnected
// from the layerContainerDiv, and cause complaints.
}
popup.map = null;
},
/********************************************************/
/* */
/* Container Div Functions */
/* */
/* The following functions deal with the access to */
/* and maintenance of the size of the container div */
/* */
/********************************************************/
/**
* APIMethod: getSize
*
* Returns:
* {} An object that represents the
* size, in pixels, of the div into which OpenLayers
* has been loaded.
* Note - A clone() of this locally cached variable is
* returned, so as not to allow users to modify it.
*/
getSize: function () {
var size = null;
if (this.size != null) {
size = this.size.clone();
}
return size;
},
/**
* APIMethod: updateSize
* This function should be called by any external code which dynamically
* changes the size of the map div (because mozilla wont let us catch
* the "onresize" for an element)
*/
updateSize: function() {
// the div might have moved on the page, also
var newSize = this.getCurrentSize();
if (newSize && !isNaN(newSize.h) && !isNaN(newSize.w)) {
this.events.clearMouseCache();
var oldSize = this.getSize();
if (oldSize == null) {
this.size = oldSize = newSize;
}
if (!newSize.equals(oldSize)) {
// store the new size
this.size = newSize;
//notify layers of mapresize
for(var i=0, len=this.layers.length; i} A new object with the dimensions
* of the map div
*/
getCurrentSize: function() {
var size = new OpenLayers.Size(this.div.clientWidth,
this.div.clientHeight);
if (size.w == 0 && size.h == 0 || isNaN(size.w) && isNaN(size.h)) {
size.w = this.div.offsetWidth;
size.h = this.div.offsetHeight;
}
if (size.w == 0 && size.h == 0 || isNaN(size.w) && isNaN(size.h)) {
size.w = parseInt(this.div.style.width);
size.h = parseInt(this.div.style.height);
}
return size;
},
/**
* Method: calculateBounds
*
* Parameters:
* center - {} Default is this.getCenter()
* resolution - {float} Default is this.getResolution()
*
* Returns:
* {} A bounds based on resolution, center, and
* current mapsize.
*/
calculateBounds: function(center, resolution) {
var extent = null;
if (center == null) {
center = this.getCachedCenter();
}
if (resolution == null) {
resolution = this.getResolution();
}
if ((center != null) && (resolution != null)) {
var size = this.getSize();
var w_deg = size.w * resolution;
var h_deg = size.h * resolution;
extent = new OpenLayers.Bounds(center.lon - w_deg / 2,
center.lat - h_deg / 2,
center.lon + w_deg / 2,
center.lat + h_deg / 2);
}
return extent;
},
/********************************************************/
/* */
/* Zoom, Center, Pan Functions */
/* */
/* The following functions handle the validation, */
/* getting and setting of the Zoom Level and Center */
/* as well as the panning of the Map */
/* */
/********************************************************/
/**
* APIMethod: getCenter
*
* Returns:
* {}
*/
getCenter: function () {
var center = null;
var cachedCenter = this.getCachedCenter();
if (cachedCenter) {
center = cachedCenter.clone();
}
return center;
},
/**
* Method: getCachedCenter
*
* Returns:
* {}
*/
getCachedCenter: function() {
if (!this.center && this.size) {
this.center = this.getLonLatFromViewPortPx(
new OpenLayers.Pixel(this.size.w / 2, this.size.h / 2)
);
}
return this.center;
},
/**
* APIMethod: getZoom
*
* Returns:
* {Integer}
*/
getZoom: function () {
return this.zoom;
},
/**
* APIMethod: pan
* Allows user to pan by a value of screen pixels
*
* Parameters:
* dx - {Integer}
* dy - {Integer}
* options - {Object} Options to configure panning:
* - *animate* {Boolean} Use panTo instead of setCenter. Default is true.
* - *dragging* {Boolean} Call setCenter with dragging true. Default is
* false.
*/
pan: function(dx, dy, options) {
options = OpenLayers.Util.applyDefaults(options, {
animate: true,
dragging: false
});
if (options.dragging) {
if (dx != 0 || dy != 0) {
this.moveByPx(dx, dy);
}
} else {
// getCenter
var centerPx = this.getViewPortPxFromLonLat(this.getCachedCenter());
// adjust
var newCenterPx = centerPx.add(dx, dy);
if (this.dragging || !newCenterPx.equals(centerPx)) {
var newCenterLonLat = this.getLonLatFromViewPortPx(newCenterPx);
if (options.animate) {
this.panTo(newCenterLonLat);
} else {
this.moveTo(newCenterLonLat);
this.dragging = false;
this.events.triggerEvent("moveend");
}
}
}
},
/**
* APIMethod: panTo
* Allows user to pan to a new lonlat
* If the new lonlat is in the current extent the map will slide smoothly
*
* Parameters:
* lonlat - {}
*/
panTo: function(lonlat) {
if (this.panMethod && this.getExtent().scale(this.panRatio).containsLonLat(lonlat)) {
if (!this.panTween) {
this.panTween = new OpenLayers.Tween(this.panMethod);
}
var center = this.getCachedCenter();
// center will not change, don't do nothing
if (lonlat.equals(center)) {
return;
}
var from = this.getPixelFromLonLat(center);
var to = this.getPixelFromLonLat(lonlat);
var vector = { x: to.x - from.x, y: to.y - from.y };
var last = { x: 0, y: 0 };
this.panTween.start( { x: 0, y: 0 }, vector, this.panDuration, {
callbacks: {
eachStep: OpenLayers.Function.bind(function(px) {
var x = px.x - last.x,
y = px.y - last.y;
this.moveByPx(x, y);
last.x = Math.round(px.x);
last.y = Math.round(px.y);
}, this),
done: OpenLayers.Function.bind(function(px) {
this.moveTo(lonlat);
this.dragging = false;
this.events.triggerEvent("moveend");
}, this)
}
});
} else {
this.setCenter(lonlat);
}
},
/**
* APIMethod: setCenter
* Set the map center (and optionally, the zoom level).
*
* Parameters:
* 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)
*
* TBD: reconsider forceZoomChange in 3.0
*/
setCenter: function(lonlat, zoom, dragging, forceZoomChange) {
this.panTween && this.panTween.stop();
this.moveTo(lonlat, zoom, {
'dragging': dragging,
'forceZoomChange': forceZoomChange
});
},
/**
* Method: moveByPx
* Drag the map by pixels.
*
* Parameters:
* dx - {Number}
* dy - {Number}
*/
moveByPx: function(dx, dy) {
var hw = this.size.w / 2;
var hh = this.size.h / 2;
var x = hw + dx;
var y = hh + dy;
var wrapDateLine = this.baseLayer.wrapDateLine;
var xRestriction = 0;
var yRestriction = 0;
if (this.restrictedExtent) {
xRestriction = hw;
yRestriction = hh;
// wrapping the date line makes no sense for restricted extents
wrapDateLine = false;
}
dx = wrapDateLine ||
x <= this.maxPx.x - xRestriction &&
x >= this.minPx.x + xRestriction ? Math.round(dx) : 0;
dy = y <= this.maxPx.y - yRestriction &&
y >= this.minPx.y + yRestriction ? Math.round(dy) : 0;
var minX = this.minPx.x, maxX = this.maxPx.x;
if (dx || dy) {
if (!this.dragging) {
this.dragging = true;
this.events.triggerEvent("movestart");
}
this.center = null;
if (dx) {
this.layerContainerDiv.style.left =
parseInt(this.layerContainerDiv.style.left) - dx + "px";
this.minPx.x -= dx;
this.maxPx.x -= dx;
if (wrapDateLine) {
if (this.maxPx.x > maxX) {
this.maxPx.x -= (maxX - minX);
}
if (this.minPx.x < minX) {
this.minPx.x += (maxX - minX);
}
}
}
if (dy) {
this.layerContainerDiv.style.top =
parseInt(this.layerContainerDiv.style.top) - dy + "px";
this.minPx.y -= dy;
this.maxPx.y -= dy;
}
var layer, i, len;
for (i=0, len=this.layers.length; i}
* zoom - {Integer}
* options - {Object}
*/
moveTo: function(lonlat, zoom, options) {
if (!options) {
options = {};
}
if (zoom != null) {
zoom = parseFloat(zoom);
if (!this.fractionalZoom) {
zoom = Math.round(zoom);
}
}
// dragging is false by default
var dragging = options.dragging || this.dragging;
// forceZoomChange is false by default
var forceZoomChange = options.forceZoomChange;
if (!this.getCachedCenter() && !this.isValidLonLat(lonlat)) {
lonlat = this.maxExtent.getCenterLonLat();
this.center = lonlat.clone();
}
if(this.restrictedExtent != null) {
// In 3.0, decide if we want to change interpretation of maxExtent.
if(lonlat == null) {
lonlat = this.center;
}
if(zoom == null) {
zoom = this.getZoom();
}
var resolution = this.getResolutionForZoom(zoom);
var extent = this.calculateBounds(lonlat, resolution);
if(!this.restrictedExtent.containsBounds(extent)) {
var maxCenter = this.restrictedExtent.getCenterLonLat();
if(extent.getWidth() > this.restrictedExtent.getWidth()) {
lonlat = new OpenLayers.LonLat(maxCenter.lon, lonlat.lat);
} else if(extent.left < this.restrictedExtent.left) {
lonlat = lonlat.add(this.restrictedExtent.left -
extent.left, 0);
} else if(extent.right > this.restrictedExtent.right) {
lonlat = lonlat.add(this.restrictedExtent.right -
extent.right, 0);
}
if(extent.getHeight() > this.restrictedExtent.getHeight()) {
lonlat = new OpenLayers.LonLat(lonlat.lon, maxCenter.lat);
} else if(extent.bottom < this.restrictedExtent.bottom) {
lonlat = lonlat.add(0, this.restrictedExtent.bottom -
extent.bottom);
}
else if(extent.top > this.restrictedExtent.top) {
lonlat = lonlat.add(0, this.restrictedExtent.top -
extent.top);
}
}
}
var zoomChanged = forceZoomChange || (
(this.isValidZoomLevel(zoom)) &&
(zoom != this.getZoom()) );
var centerChanged = (this.isValidLonLat(lonlat)) &&
(!lonlat.equals(this.center));
// if neither center nor zoom will change, no need to do anything
if (zoomChanged || centerChanged || dragging) {
dragging || this.events.triggerEvent("movestart");
if (centerChanged) {
if (!zoomChanged && this.center) {
// if zoom hasnt changed, just slide layerContainer
// (must be done before setting this.center to new value)
this.centerLayerContainer(lonlat);
}
this.center = lonlat.clone();
}
var res = zoomChanged ?
this.getResolutionForZoom(zoom) : this.getResolution();
// (re)set the layerContainerDiv's location
if (zoomChanged || this.layerContainerOrigin == null) {
this.layerContainerOrigin = this.getCachedCenter();
this.layerContainerDiv.style.left = "0px";
this.layerContainerDiv.style.top = "0px";
var maxExtent = this.getMaxExtent({restricted: true});
var maxExtentCenter = maxExtent.getCenterLonLat();
var lonDelta = this.center.lon - maxExtentCenter.lon;
var latDelta = maxExtentCenter.lat - this.center.lat;
var extentWidth = Math.round(maxExtent.getWidth() / res);
var extentHeight = Math.round(maxExtent.getHeight() / res);
var left = (this.size.w - extentWidth) / 2 - lonDelta / res;
var top = (this.size.h - extentHeight) / 2 - latDelta / res;
this.minPx = new OpenLayers.Pixel(left, top);
this.maxPx = new OpenLayers.Pixel(left + extentWidth, top + extentHeight);
}
if (zoomChanged) {
this.zoom = zoom;
this.resolution = res;
// zoom level has changed, increment viewRequestID.
this.viewRequestID++;
}
var bounds = this.getExtent();
//send the move call to the baselayer and all the overlays
if(this.baseLayer.visibility) {
this.baseLayer.moveTo(bounds, zoomChanged, options.dragging);
options.dragging || this.baseLayer.events.triggerEvent(
"moveend", {zoomChanged: zoomChanged}
);
}
bounds = this.baseLayer.getExtent();
for (var i=this.layers.length-1; i>=0; --i) {
var layer = this.layers[i];
if (layer !== this.baseLayer && !layer.isBaseLayer) {
var inRange = layer.calculateInRange();
if (layer.inRange != inRange) {
// the inRange property has changed. If the layer is
// no longer in range, we turn it off right away. If
// the layer is no longer out of range, the moveTo
// call below will turn on the layer.
layer.inRange = inRange;
if (!inRange) {
layer.display(false);
}
this.events.triggerEvent("changelayer", {
layer: layer, property: "visibility"
});
}
if (inRange && layer.visibility) {
layer.moveTo(bounds, zoomChanged, options.dragging);
options.dragging || layer.events.triggerEvent(
"moveend", {zoomChanged: zoomChanged}
);
}
}
}
this.events.triggerEvent("move");
dragging || this.events.triggerEvent("moveend");
if (zoomChanged) {
//redraw popups
for (var i=0, len=this.popups.length; i}
*/
centerLayerContainer: function (lonlat) {
var originPx = this.getViewPortPxFromLonLat(this.layerContainerOrigin);
var newPx = this.getViewPortPxFromLonLat(lonlat);
if ((originPx != null) && (newPx != null)) {
var oldLeft = parseInt(this.layerContainerDiv.style.left);
var oldTop = parseInt(this.layerContainerDiv.style.top);
var newLeft = Math.round(originPx.x - newPx.x);
var newTop = Math.round(originPx.y - newPx.y);
this.layerContainerDiv.style.left = newLeft + "px";
this.layerContainerDiv.style.top = newTop + "px";
var dx = oldLeft - newLeft;
var dy = oldTop - newTop;
this.minPx.x -= dx;
this.maxPx.x -= dx;
this.minPx.y -= dy;
this.maxPx.y -= dy;
}
},
/**
* Method: isValidZoomLevel
*
* Parameters:
* zoomLevel - {Integer}
*
* Returns:
* {Boolean} Whether or not the zoom level passed in is non-null and
* within the min/max range of zoom levels.
*/
isValidZoomLevel: function(zoomLevel) {
return ( (zoomLevel != null) &&
(zoomLevel >= 0) &&
(zoomLevel < this.getNumZoomLevels()) );
},
/**
* Method: isValidLonLat
*
* Parameters:
* lonlat - {}
*
* Returns:
* {Boolean} Whether or not the lonlat passed in is non-null and within
* the maxExtent bounds
*/
isValidLonLat: function(lonlat) {
var valid = false;
if (lonlat != null) {
var maxExtent = this.getMaxExtent();
valid = maxExtent.containsLonLat(lonlat);
}
return valid;
},
/********************************************************/
/* */
/* Layer Options */
/* */
/* Accessor functions to Layer Options parameters */
/* */
/********************************************************/
/**
* APIMethod: getProjection
* This method returns a string representing the projection. In
* the case of projection support, this will be the srsCode which
* is loaded -- otherwise it will simply be the string value that
* was passed to the projection at startup.
*
* FIXME: In 3.0, we will remove getProjectionObject, and instead
* return a Projection object from this function.
*
* Returns:
* {String} The Projection string from the base layer or null.
*/
getProjection: function() {
var projection = this.getProjectionObject();
return projection ? projection.getCode() : null;
},
/**
* APIMethod: getProjectionObject
* Returns the projection obect from the baselayer.
*
* Returns:
* {} The Projection of the base layer.
*/
getProjectionObject: function() {
var projection = null;
if (this.baseLayer != null) {
projection = this.baseLayer.projection;
}
return projection;
},
/**
* APIMethod: getMaxResolution
*
* Returns:
* {String} The Map's Maximum Resolution
*/
getMaxResolution: function() {
var maxResolution = null;
if (this.baseLayer != null) {
maxResolution = this.baseLayer.maxResolution;
}
return maxResolution;
},
/**
* APIMethod: getMaxExtent
*
* Parameters:
* options - {Object}
*
* Allowed Options:
* restricted - {Boolean} If true, returns restricted extent (if it is
* available.)
*
* Returns:
* {} The maxExtent property as set on the current
* baselayer, unless the 'restricted' option is set, in which case
* the 'restrictedExtent' option from the map is returned (if it
* is set).
*/
getMaxExtent: function (options) {
var maxExtent = null;
if(options && options.restricted && this.restrictedExtent){
maxExtent = this.restrictedExtent;
} else if (this.baseLayer != null) {
maxExtent = this.baseLayer.maxExtent;
}
return maxExtent;
},
/**
* APIMethod: getNumZoomLevels
*
* Returns:
* {Integer} The total number of zoom levels that can be displayed by the
* current baseLayer.
*/
getNumZoomLevels: function() {
var numZoomLevels = null;
if (this.baseLayer != null) {
numZoomLevels = this.baseLayer.numZoomLevels;
}
return numZoomLevels;
},
/********************************************************/
/* */
/* Baselayer Functions */
/* */
/* The following functions, all publicly exposed */
/* in the API?, are all merely wrappers to the */
/* the same calls on whatever layer is set as */
/* the current base layer */
/* */
/********************************************************/
/**
* APIMethod: getExtent
*
* Returns:
* {} A Bounds object which represents the lon/lat
* bounds of the current viewPort.
* If no baselayer is set, returns null.
*/
getExtent: function () {
var extent = null;
if (this.baseLayer != null) {
extent = this.baseLayer.getExtent();
}
return extent;
},
/**
* APIMethod: getResolution
*
* Returns:
* {Float} The current resolution of the map.
* If no baselayer is set, returns null.
*/
getResolution: function () {
var resolution = null;
if (this.baseLayer != null) {
resolution = this.baseLayer.getResolution();
} else if(this.allOverlays === true && this.layers.length > 0) {
// while adding the 1st layer to the map in allOverlays mode,
// this.baseLayer is not set yet when we need the resolution
// for calculateInRange.
resolution = this.layers[0].getResolution();
}
return resolution;
},
/**
* APIMethod: getUnits
*
* Returns:
* {Float} The current units of the map.
* If no baselayer is set, returns null.
*/
getUnits: function () {
var units = null;
if (this.baseLayer != null) {
units = this.baseLayer.units;
}
return units;
},
/**
* APIMethod: getScale
*
* Returns:
* {Float} The current scale denominator of the map.
* If no baselayer is set, returns null.
*/
getScale: function () {
var scale = null;
if (this.baseLayer != null) {
var res = this.getResolution();
var units = this.baseLayer.units;
scale = OpenLayers.Util.getScaleFromResolution(res, units);
}
return scale;
},
/**
* APIMethod: getZoomForExtent
*
* Parameters:
* bounds - {}
* closest - {Boolean} Find the zoom level that most closely fits the
* specified bounds. Note that this may result in a zoom that does
* not exactly contain the entire extent.
* Default is false.
*
* Returns:
* {Integer} A suitable zoom level for the specified bounds.
* If no baselayer is set, returns null.
*/
getZoomForExtent: function (bounds, closest) {
var zoom = null;
if (this.baseLayer != null) {
zoom = this.baseLayer.getZoomForExtent(bounds, closest);
}
return zoom;
},
/**
* APIMethod: getResolutionForZoom
*
* Parameter:
* zoom - {Float}
*
* Returns:
* {Float} A suitable resolution for the specified zoom. If no baselayer
* is set, returns null.
*/
getResolutionForZoom: function(zoom) {
var resolution = null;
if(this.baseLayer) {
resolution = this.baseLayer.getResolutionForZoom(zoom);
}
return resolution;
},
/**
* APIMethod: getZoomForResolution
*
* Parameter:
* resolution - {Float}
* closest - {Boolean} Find the zoom level that corresponds to the absolute
* closest resolution, which may result in a zoom whose corresponding
* resolution is actually smaller than we would have desired (if this
* is being called from a getZoomForExtent() call, then this means that
* the returned zoom index might not actually contain the entire
* extent specified... but it'll be close).
* Default is false.
*
* Returns:
* {Integer} A suitable zoom level for the specified resolution.
* If no baselayer is set, returns null.
*/
getZoomForResolution: function(resolution, closest) {
var zoom = null;
if (this.baseLayer != null) {
zoom = this.baseLayer.getZoomForResolution(resolution, closest);
}
return zoom;
},
/********************************************************/
/* */
/* Zooming Functions */
/* */
/* The following functions, all publicly exposed */
/* in the API, are all merely wrappers to the */
/* the setCenter() function */
/* */
/********************************************************/
/**
* APIMethod: zoomTo
* Zoom to a specific zoom level
*
* Parameters:
* zoom - {Integer}
*/
zoomTo: function(zoom) {
if (this.isValidZoomLevel(zoom)) {
this.setCenter(null, zoom);
}
},
/**
* APIMethod: zoomIn
*
*/
zoomIn: function() {
this.zoomTo(this.getZoom() + 1);
},
/**
* APIMethod: zoomOut
*
*/
zoomOut: function() {
this.zoomTo(this.getZoom() - 1);
},
/**
* APIMethod: zoomToExtent
* Zoom to the passed in bounds, recenter
*
* Parameters:
* bounds - {}
* closest - {Boolean} Find the zoom level that most closely fits the
* specified bounds. Note that this may result in a zoom that does
* not exactly contain the entire extent.
* Default is false.
*
*/
zoomToExtent: function(bounds, closest) {
var center = bounds.getCenterLonLat();
if (this.baseLayer.wrapDateLine) {
var maxExtent = this.getMaxExtent();
//fix straddling bounds (in the case of a bbox that straddles the
// dateline, it's left and right boundaries will appear backwards.
// we fix this by allowing a right value that is greater than the
// max value at the dateline -- this allows us to pass a valid
// bounds to calculate zoom)
//
bounds = bounds.clone();
while (bounds.right < bounds.left) {
bounds.right += maxExtent.getWidth();
}
//if the bounds was straddling (see above), then the center point
// we got from it was wrong. So we take our new bounds and ask it
// for the center. Because our new bounds is at least partially
// outside the bounds of maxExtent, the new calculated center
// might also be. We don't want to pass a bad center value to
// setCenter, so we have it wrap itself across the date line.
//
center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
}
this.setCenter(center, this.getZoomForExtent(bounds, closest));
},
/**
* APIMethod: zoomToMaxExtent
* Zoom to the full extent and recenter.
*
* Parameters:
* options -
*
* Allowed Options:
* restricted - {Boolean} True to zoom to restricted extent if it is
* set. Defaults to true.
*/
zoomToMaxExtent: function(options) {
//restricted is true by default
var restricted = (options) ? options.restricted : true;
var maxExtent = this.getMaxExtent({
'restricted': restricted
});
this.zoomToExtent(maxExtent);
},
/**
* APIMethod: zoomToScale
* Zoom to a specified scale
*
* Parameters:
* scale - {float}
* closest - {Boolean} Find the zoom level that most closely fits the
* specified scale. Note that this may result in a zoom that does
* not exactly contain the entire extent.
* Default is false.
*
*/
zoomToScale: function(scale, closest) {
var res = OpenLayers.Util.getResolutionFromScale(scale,
this.baseLayer.units);
var size = this.getSize();
var w_deg = size.w * res;
var h_deg = size.h * res;
var center = this.getCachedCenter();
var extent = new OpenLayers.Bounds(center.lon - w_deg / 2,
center.lat - h_deg / 2,
center.lon + w_deg / 2,
center.lat + h_deg / 2);
this.zoomToExtent(extent, closest);
},
/********************************************************/
/* */
/* Translation Functions */
/* */
/* The following functions translate between */
/* LonLat, LayerPx, and ViewPortPx */
/* */
/********************************************************/
//
// TRANSLATION: LonLat <-> ViewPortPx
//
/**
* Method: getLonLatFromViewPortPx
*
* Parameters:
* viewPortPx - {}
*
* Returns:
* {} An OpenLayers.LonLat which is the passed-in view
* port , translated into lon/lat
* by the current base layer.
*/
getLonLatFromViewPortPx: function (viewPortPx) {
var lonlat = null;
if (this.baseLayer != null) {
lonlat = this.baseLayer.getLonLatFromViewPortPx(viewPortPx);
}
return lonlat;
},
/**
* APIMethod: getViewPortPxFromLonLat
*
* Parameters:
* lonlat - {}
*
* Returns:
* {} An OpenLayers.Pixel which is the passed-in
* , translated into view port
* pixels by the current base layer.
*/
getViewPortPxFromLonLat: function (lonlat) {
var px = null;
if (this.baseLayer != null) {
px = this.baseLayer.getViewPortPxFromLonLat(lonlat);
}
return px;
},
//
// CONVENIENCE TRANSLATION FUNCTIONS FOR API
//
/**
* APIMethod: getLonLatFromPixel
*
* Parameters:
* px - {}
*
* Returns:
* {} An OpenLayers.LonLat corresponding to the given
* OpenLayers.Pixel, translated into lon/lat by the
* current base layer
*/
getLonLatFromPixel: function (px) {
return this.getLonLatFromViewPortPx(px);
},
/**
* APIMethod: getPixelFromLonLat
* Returns a pixel location given a map location. The map location is
* translated to an integer pixel location (in viewport pixel
* coordinates) by the current base layer.
*
* Parameters:
* lonlat - {} A map location.
*
* Returns:
* {} An OpenLayers.Pixel corresponding to the
* translated into view port pixels by the current
* base layer.
*/
getPixelFromLonLat: function (lonlat) {
var px = this.getViewPortPxFromLonLat(lonlat);
px.x = Math.round(px.x);
px.y = Math.round(px.y);
return px;
},
/**
* Method: getGeodesicPixelSize
*
* Parameters:
* px - {} The pixel to get the geodesic length for. If
* not provided, the center pixel of the map viewport will be used.
*
* Returns:
* {} The geodesic size of the pixel in kilometers.
*/
getGeodesicPixelSize: function(px) {
var lonlat = px ? this.getLonLatFromPixel(px) : (
this.getCachedCenter() || new OpenLayers.LonLat(0, 0));
var res = this.getResolution();
var left = lonlat.add(-res / 2, 0);
var right = lonlat.add(res / 2, 0);
var bottom = lonlat.add(0, -res / 2);
var top = lonlat.add(0, res / 2);
var dest = new OpenLayers.Projection("EPSG:4326");
var source = this.getProjectionObject() || dest;
if(!source.equals(dest)) {
left.transform(source, dest);
right.transform(source, dest);
bottom.transform(source, dest);
top.transform(source, dest);
}
return new OpenLayers.Size(
OpenLayers.Util.distVincenty(left, right),
OpenLayers.Util.distVincenty(bottom, top)
);
},
//
// TRANSLATION: ViewPortPx <-> LayerPx
//
/**
* APIMethod: getViewPortPxFromLayerPx
*
* Parameters:
* layerPx - {}
*
* Returns:
* {} Layer Pixel translated into ViewPort Pixel
* coordinates
*/
getViewPortPxFromLayerPx:function(layerPx) {
var viewPortPx = null;
if (layerPx != null) {
var dX = parseInt(this.layerContainerDiv.style.left);
var dY = parseInt(this.layerContainerDiv.style.top);
viewPortPx = layerPx.add(dX, dY);
}
return viewPortPx;
},
/**
* APIMethod: getLayerPxFromViewPortPx
*
* Parameters:
* viewPortPx - {}
*
* Returns:
* {} ViewPort Pixel translated into Layer Pixel
* coordinates
*/
getLayerPxFromViewPortPx:function(viewPortPx) {
var layerPx = null;
if (viewPortPx != null) {
var dX = -parseInt(this.layerContainerDiv.style.left);
var dY = -parseInt(this.layerContainerDiv.style.top);
layerPx = viewPortPx.add(dX, dY);
if (isNaN(layerPx.x) || isNaN(layerPx.y)) {
layerPx = null;
}
}
return layerPx;
},
//
// TRANSLATION: LonLat <-> LayerPx
//
/**
* Method: getLonLatFromLayerPx
*
* Parameters:
* px - {}
*
* Returns:
* {}
*/
getLonLatFromLayerPx: function (px) {
//adjust for displacement of layerContainerDiv
px = this.getViewPortPxFromLayerPx(px);
return this.getLonLatFromViewPortPx(px);
},
/**
* APIMethod: getLayerPxFromLonLat
*
* Parameters:
* lonlat - {} lonlat
*
* Returns:
* {} An OpenLayers.Pixel which is the passed-in
* , translated into layer pixels
* by the current base layer
*/
getLayerPxFromLonLat: function (lonlat) {
//adjust for displacement of layerContainerDiv
var px = this.getPixelFromLonLat(lonlat);
return this.getLayerPxFromViewPortPx(px);
},
CLASS_NAME: "OpenLayers.Map"
});
/**
* Constant: TILE_WIDTH
* {Integer} 256 Default tile width (unless otherwise specified)
*/
OpenLayers.Map.TILE_WIDTH = 256;
/**
* Constant: TILE_HEIGHT
* {Integer} 256 Default tile height (unless otherwise specified)
*/
OpenLayers.Map.TILE_HEIGHT = 256;
/* ======================================================================
OpenLayers/Projection.js
====================================================================== */
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/BaseTypes/Class.js
* @requires OpenLayers/Util.js
*/
/**
* Class: OpenLayers.Projection
* Class for coordinate transforms between coordinate systems.
* Depends on the proj4js library. If proj4js is not available,
* then this is just an empty stub.
*/
OpenLayers.Projection = OpenLayers.Class({
/**
* Property: proj
* {Object} Proj4js.Proj instance.
*/
proj: null,
/**
* Property: projCode
* {String}
*/
projCode: null,
/**
* Property: titleRegEx
* {RegExp} regular expression to strip the title from a proj4js definition
*/
titleRegEx: /\+title=[^\+]*/,
/**
* Constructor: OpenLayers.Projection
* This class offers several methods for interacting with a wrapped
* pro4js projection object.
*
* Parameters:
* projCode - {String} A string identifying the Well Known Identifier for
* the projection.
* options - {Object} An optional object to set additional properties
* on the layer.
*
* Returns:
* {} A projection object.
*/
initialize: function(projCode, options) {
OpenLayers.Util.extend(this, options);
this.projCode = projCode;
if (window.Proj4js) {
this.proj = new Proj4js.Proj(projCode);
}
},
/**
* APIMethod: getCode
* Get the string SRS code.
*
* Returns:
* {String} The SRS code.
*/
getCode: function() {
return this.proj ? this.proj.srsCode : this.projCode;
},
/**
* APIMethod: getUnits
* Get the units string for the projection -- returns null if
* proj4js is not available.
*
* Returns:
* {String} The units abbreviation.
*/
getUnits: function() {
return this.proj ? this.proj.units : null;
},
/**
* Method: toString
* Convert projection to string (getCode wrapper).
*
* Returns:
* {String} The projection code.
*/
toString: function() {
return this.getCode();
},
/**
* Method: equals
* Test equality of two projection instances. Determines equality based
* soley on the projection code.
*
* Returns:
* {Boolean} The two projections are equivalent.
*/
equals: function(projection) {
var p = projection, equals = false;
if (p) {
if (window.Proj4js && this.proj.defData && p.proj.defData) {
equals = this.proj.defData.replace(this.titleRegEx, "") ==
p.proj.defData.replace(this.titleRegEx, "");
} else if (p.getCode) {
var source = this.getCode(), target = p.getCode();
equals = source == target ||
!!OpenLayers.Projection.transforms[source] &&
OpenLayers.Projection.transforms[source][target] ===
OpenLayers.Projection.nullTransform;
}
}
return equals;
},
/* Method: destroy
* Destroy projection object.
*/
destroy: function() {
delete this.proj;
delete this.projCode;
},
CLASS_NAME: "OpenLayers.Projection"
});
/**
* Property: transforms
* Transforms is an object, with from properties, each of which may
* have a to property. This allows you to define projections without
* requiring support for proj4js to be included.
*
* This object has keys which correspond to a 'source' projection object. The
* keys should be strings, corresponding to the projection.getCode() value.
* Each source projection object should have a set of destination projection
* keys included in the object.
*
* Each value in the destination object should be a transformation function,
* where the function is expected to be passed an object with a .x and a .y
* property. The function should return the object, with the .x and .y
* transformed according to the transformation function.
*
* Note - Properties on this object should not be set directly. To add a
* transform method to this object, use the method. For an
* example of usage, see the OpenLayers.Layer.SphericalMercator file.
*/
OpenLayers.Projection.transforms = {};
/**
* APIMethod: addTransform
* Set a custom transform method between two projections. Use this method in
* cases where the proj4js lib is not available or where custom projections
* need to be handled.
*
* Parameters:
* from - {String} The code for the source projection
* to - {String} the code for the destination projection
* method - {Function} A function that takes a point as an argument and
* transforms that point from the source to the destination projection
* in place. The original point should be modified.
*/
OpenLayers.Projection.addTransform = function(from, to, method) {
if(!OpenLayers.Projection.transforms[from]) {
OpenLayers.Projection.transforms[from] = {};
}
OpenLayers.Projection.transforms[from][to] = method;
};
/**
* APIMethod: transform
* Transform a point coordinate from one projection to another. Note that
* the input point is transformed in place.
*
* Parameters:
* point - { | Object} An object with x and y
* properties representing coordinates in those dimensions.
* source - {OpenLayers.Projection} Source map coordinate system
* dest - {OpenLayers.Projection} Destination map coordinate system
*
* Returns:
* point - {object} A transformed coordinate. The original point is modified.
*/
OpenLayers.Projection.transform = function(point, source, dest) {
if (source.proj && dest.proj) {
point = Proj4js.transform(source.proj, dest.proj, point);
} else if (source && dest &&
OpenLayers.Projection.transforms[source.getCode()] &&
OpenLayers.Projection.transforms[source.getCode()][dest.getCode()]) {
OpenLayers.Projection.transforms[source.getCode()][dest.getCode()](point);
}
return point;
};
/**
* APIFunction: nullTransform
* A null transformation - useful for defining projection aliases when
* proj4js is not available:
*
* (code)
* OpenLayers.Projection.addTransform("EPSG:4326", "EPSG:3857",
* OpenLayers.Layer.SphericalMercator.projectForward);
* OpenLayers.Projection.addTransform("EPSG:3857", "EPSG:3857",
* OpenLayers.Layer.SphericalMercator.projectInverse);
* OpenLayers.Projection.addTransform("EPSG:3857", "EPSG:900913",
* OpenLayers.Projection.nullTransform);
* OpenLayers.Projection.addTransform("EPSG:900913", "EPSG:3857",
* OpenLayers.Projection.nullTransform);
* (end)
*/
OpenLayers.Projection.nullTransform = function(point) {
return point;
};
/* ======================================================================
OpenLayers/Layer.js
====================================================================== */
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/BaseTypes/Class.js
* @requires OpenLayers/Map.js
* @requires OpenLayers/Projection.js
*/
/**
* Class: OpenLayers.Layer
*/
OpenLayers.Layer = OpenLayers.Class({
/**
* APIProperty: id
* {String}
*/
id: null,
/**
* APIProperty: name
* {String}
*/
name: null,
/**
* APIProperty: div
* {DOMElement}
*/
div: null,
/**
* Property: opacity
* {Float} The layer's opacity. Float number between 0.0 and 1.0.
*/
opacity: null,
/**
* APIProperty: alwaysInRange
* {Boolean} If a layer's display should not be scale-based, this should
* be set to true. This will cause the layer, as an overlay, to always
* be 'active', by always returning true from the calculateInRange()
* function.
*
* If not explicitly specified for a layer, its value will be
* determined on startup in initResolutions() based on whether or not
* any scale-specific properties have been set as options on the
* layer. If no scale-specific options have been set on the layer, we
* assume that it should always be in range.
*
* See #987 for more info.
*/
alwaysInRange: null,
/**
* Constant: EVENT_TYPES
* {Array(String)} Supported application event types. Register a listener
* for a particular event with the following syntax:
* (code)
* layer.events.register(type, obj, listener);
* (end)
*
* Listeners will be called with a reference to an event object. The
* properties of this event depends on exactly what happened.
*
* All event objects have at least the following properties:
* object - {Object} A reference to layer.events.object.
* element - {DOMElement} A reference to layer.events.element.
*
* Supported map event types:
* loadstart - Triggered when layer loading starts.
* loadend - Triggered when layer loading ends.
* loadcancel - Triggered when layer loading is canceled.
* visibilitychanged - Triggered when layer visibility is changed.
* move - Triggered when layer moves (triggered with every mousemove
* during a drag).
* moveend - Triggered when layer is done moving, object passed as
* argument has a zoomChanged boolean property which tells that the
* zoom has changed.
* added - Triggered after the layer is added to a map. Listeners will
* receive an object with a *map* property referencing the map and a
* *layer* property referencing the layer.
* removed - Triggered after the layer is removed from the map. Listeners
* will receive an object with a *map* property referencing the map and
* a *layer* property referencing the layer.
*/
EVENT_TYPES: ["loadstart", "loadend", "loadcancel", "visibilitychanged",
"move", "moveend", "added", "removed"],
/**
* Constant: RESOLUTION_PROPERTIES
* {Array} The properties that are used for calculating resolutions
* information.
*/
RESOLUTION_PROPERTIES: [
'scales', 'resolutions',
'maxScale', 'minScale',
'maxResolution', 'minResolution',
'numZoomLevels', 'maxZoomLevel'
],
/**
* APIProperty: events
* {}
*/
events: null,
/**
* APIProperty: map
* {} This variable is set when the layer is added to
* the map, via the accessor function setMap().
*/
map: null,
/**
* APIProperty: isBaseLayer
* {Boolean} Whether or not the layer is a base layer. This should be set
* individually by all subclasses. Default is false
*/
isBaseLayer: false,
/**
* Property: alpha
* {Boolean} The layer's images have an alpha channel. Default is false.
*/
alpha: false,
/**
* APIProperty: displayInLayerSwitcher
* {Boolean} Display the layer's name in the layer switcher. Default is
* true.
*/
displayInLayerSwitcher: true,
/**
* APIProperty: visibility
* {Boolean} The layer should be displayed in the map. Default is true.
*/
visibility: true,
/**
* APIProperty: attribution
* {String} Attribution string, displayed when an
* has been added to the map.
*/
attribution: null,
/**
* Property: inRange
* {Boolean} The current map resolution is within the layer's min/max
* range. This is set in whenever the zoom
* changes.
*/
inRange: false,
/**
* Propery: imageSize
* {} For layers with a gutter, the image is larger than
* the tile by twice the gutter in each dimension.
*/
imageSize: null,
/**
* Property: imageOffset
* {} For layers with a gutter, the image offset
* represents displacement due to the gutter.
*/
imageOffset: null,
// OPTIONS
/**
* Property: options
* {Object} An optional object whose properties will be set on the layer.
* Any of the layer properties can be set as a property of the options
* object and sent to the constructor when the layer is created.
*/
options: null,
/**
* APIProperty: eventListeners
* {Object} If set as an option at construction, the eventListeners
* object will be registered with . Object
* structure must be a listeners object as shown in the example for
* the events.on method.
*/
eventListeners: null,
/**
* APIProperty: gutter
* {Integer} Determines the width (in pixels) of the gutter around image
* tiles to ignore. By setting this property to a non-zero value,
* images will be requested that are wider and taller than the tile
* size by a value of 2 x gutter. This allows artifacts of rendering
* at tile edges to be ignored. Set a gutter value that is equal to
* half the size of the widest symbol that needs to be displayed.
* Defaults to zero. Non-tiled layers always have zero gutter.
*/
gutter: 0,
/**
* APIProperty: projection
* {} or {} Set in the layer options to
* override the default projection string this layer - also set maxExtent,
* maxResolution, and units if appropriate. Can be either a string or
* an object when created -- will be converted
* to an object when setMap is called if a string is passed.
*/
projection: null,
/**
* APIProperty: units
* {String} The layer map units. Defaults to 'degrees'. Possible values
* are 'degrees' (or 'dd'), 'm', 'ft', 'km', 'mi', 'inches'.
*/
units: null,
/**
* APIProperty: scales
* {Array} An array of map scales in descending order. The values in the
* array correspond to the map scale denominator. Note that these
* values only make sense if the display (monitor) resolution of the
* client is correctly guessed by whomever is configuring the
* application. In addition, the units property must also be set.
* Use instead wherever possible.
*/
scales: null,
/**
* APIProperty: resolutions
* {Array} A list of map resolutions (map units per pixel) in descending
* order. If this is not set in the layer constructor, it will be set
* based on other resolution related properties (maxExtent,
* maxResolution, maxScale, etc.).
*/
resolutions: null,
/**
* APIProperty: maxExtent
* {} The center of these bounds will not stray outside
* of the viewport extent during panning. In addition, if
* is set to false, data will not be
* requested that falls completely outside of these bounds.
*/
maxExtent: null,
/**
* APIProperty: minExtent
* {}
*/
minExtent: null,
/**
* APIProperty: maxResolution
* {Float} Default max is 360 deg / 256 px, which corresponds to
* zoom level 0 on gmaps. Specify a different value in the layer
* options if you are not using a geographic projection and
* displaying the whole world.
*/
maxResolution: null,
/**
* APIProperty: minResolution
* {Float}
*/
minResolution: null,
/**
* APIProperty: numZoomLevels
* {Integer}
*/
numZoomLevels: null,
/**
* APIProperty: minScale
* {Float}
*/
minScale: null,
/**
* APIProperty: maxScale
* {Float}
*/
maxScale: null,
/**
* APIProperty: displayOutsideMaxExtent
* {Boolean} Request map tiles that are completely outside of the max
* extent for this layer. Defaults to false.
*/
displayOutsideMaxExtent: false,
/**
* APIProperty: wrapDateLine
* {Boolean} #487 for more info.
*/
wrapDateLine: false,
/**
* APIProperty: transitionEffect
* {String} The transition effect to use when the map is panned or
* zoomed.
*
* There are currently two supported values:
* - *null* No transition effect (the default).
* - *resize* Existing tiles are resized on zoom to provide a visual
* effect of the zoom having taken place immediately. As the
* new tiles become available, they are drawn over top of the
* resized tiles.
*/
transitionEffect: null,
/**
* Property: SUPPORTED_TRANSITIONS
* {Array} An immutable (that means don't change it!) list of supported
* transitionEffect values.
*/
SUPPORTED_TRANSITIONS: ['resize'],
/**
* Property: metadata
* {Object} This object can be used to store additional information on a
* layer object.
*/
metadata: {},
/**
* Constructor: OpenLayers.Layer
*
* Parameters:
* name - {String} The layer name
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, options) {
this.addOptions(options);
this.name = name;
if (this.id == null) {
this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
this.div = OpenLayers.Util.createDiv(this.id);
this.div.style.width = "100%";
this.div.style.height = "100%";
this.div.dir = "ltr";
this.events = new OpenLayers.Events(this, this.div,
this.EVENT_TYPES);
if(this.eventListeners instanceof Object) {
this.events.on(this.eventListeners);
}
}
if (this.wrapDateLine) {
this.displayOutsideMaxExtent = true;
}
},
/**
* Method: destroy
* Destroy is a destructor: this is to alleviate cyclic references which
* the Javascript garbage cleaner can not take care of on its own.
*
* Parameters:
* setNewBaseLayer - {Boolean} Set a new base layer when this layer has
* been destroyed. Default is true.
*/
destroy: function(setNewBaseLayer) {
if (setNewBaseLayer == null) {
setNewBaseLayer = true;
}
if (this.map != null) {
this.map.removeLayer(this, setNewBaseLayer);
}
this.projection = null;
this.map = null;
this.name = null;
this.div = null;
this.options = null;
if (this.events) {
if(this.eventListeners) {
this.events.un(this.eventListeners);
}
this.events.destroy();
}
this.eventListeners = null;
this.events = null;
},
/**
* Method: clone
*
* Parameters:
* obj - {} The layer to be cloned
*
* Returns:
* {} An exact clone of this
*/
clone: function (obj) {
if (obj == null) {
obj = new OpenLayers.Layer(this.name, this.getOptions());
}
// catch any randomly tagged-on properties
OpenLayers.Util.applyDefaults(obj, this);
// a cloned layer should never have its map property set
// because it has not been added to a map yet.
obj.map = null;
return obj;
},
/**
* Method: getOptions
* Extracts an object from the layer with the properties that were set as
* options, but updates them with the values currently set on the
* instance.
*
* Returns:
* {Object} the of the layer, representing the current state.
*/
getOptions: function() {
var options = {};
for(var o in this.options) {
options[o] = this[o];
}
return options;
},
/**
* APIMethod: setName
* Sets the new layer name for this layer. Can trigger a changelayer event
* on the map.
*
* Parameters:
* newName - {String} The new name.
*/
setName: function(newName) {
if (newName != this.name) {
this.name = newName;
if (this.map != null) {
this.map.events.triggerEvent("changelayer", {
layer: this,
property: "name"
});
}
}
},
/**
* APIMethod: addOptions
*
* Parameters:
* newOptions - {Object}
* reinitialize - {Boolean} If set to true, and if resolution options of the
* current baseLayer were changed, the map will be recentered to make
* sure that it is displayed with a valid resolution, and a
* changebaselayer event will be triggered.
*/
addOptions: function (newOptions, reinitialize) {
if (this.options == null) {
this.options = {};
}
// update our copy for clone
OpenLayers.Util.extend(this.options, newOptions);
// add new options to this
OpenLayers.Util.extend(this, newOptions);
// make sure this.projection references a projection object
if(typeof this.projection == "string") {
this.projection = new OpenLayers.Projection(this.projection);
}
// get the units from the projection, if we have a projection
// and it it has units
if(this.projection && this.projection.getUnits()) {
this.units = this.projection.getUnits();
}
// re-initialize resolutions if necessary, i.e. if any of the
// properties of the "properties" array defined below is set
// in the new options
if(this.map) {
// store current resolution so we can try to restore it later
var resolution = this.map.getResolution();
var properties = this.RESOLUTION_PROPERTIES.concat(
["projection", "units", "minExtent", "maxExtent"]
);
for(var o in newOptions) {
if(newOptions.hasOwnProperty(o) &&
OpenLayers.Util.indexOf(properties, o) >= 0) {
this.initResolutions();
if (reinitialize && this.map.baseLayer === this) {
// update map position, and restore previous resolution
this.map.setCenter(this.map.getCenter(),
this.map.getZoomForResolution(resolution),
false, true
);
// trigger a changebaselayer event to make sure that
// all controls (especially
// OpenLayers.Control.PanZoomBar) get notified of the
// new options
this.map.events.triggerEvent("changebaselayer", {
layer: this
});
}
break;
}
}
}
},
/**
* APIMethod: onMapResize
* This function can be implemented by subclasses
*/
onMapResize: function() {
//this function can be implemented by subclasses
},
/**
* APIMethod: redraw
* Redraws the layer. Returns true if the layer was redrawn, false if not.
*
* Returns:
* {Boolean} The layer was redrawn.
*/
redraw: function() {
var redrawn = false;
if (this.map) {
// min/max Range may have changed
this.inRange = this.calculateInRange();
// map's center might not yet be set
var extent = this.getExtent();
if (extent && this.inRange && this.visibility) {
var zoomChanged = true;
this.moveTo(extent, zoomChanged, false);
this.events.triggerEvent("moveend",
{"zoomChanged": zoomChanged});
redrawn = true;
}
}
return redrawn;
},
/**
* Method: moveTo
*
* Parameters:
* bounds - {}
* zoomChanged - {Boolean} Tells when zoom has changed, as layers have to
* do some init work in that case.
* dragging - {Boolean}
*/
moveTo:function(bounds, zoomChanged, dragging) {
var display = this.visibility;
if (!this.isBaseLayer) {
display = display && this.inRange;
}
this.display(display);
},
/**
* Method: moveByPx
* Move the layer based on pixel vector. To be implemented by subclasses.
*
* Parameters:
* dx - {Number} The x coord of the displacement vector.
* dy - {Number} The y coord of the displacement vector.
*/
moveByPx: function(dx, dy) {
},
/**
* Method: setMap
* Set the map property for the layer. This is done through an accessor
* so that subclasses can override this and take special action once
* they have their map variable set.
*
* Here we take care to bring over any of the necessary default
* properties from the map.
*
* Parameters:
* map - {}
*/
setMap: function(map) {
if (this.map == null) {
this.map = map;
// grab some essential layer data from the map if it hasn't already
// been set
this.maxExtent = this.maxExtent || this.map.maxExtent;
this.minExtent = this.minExtent || this.map.minExtent;
this.projection = this.projection || this.map.projection;
if (typeof this.projection == "string") {
this.projection = new OpenLayers.Projection(this.projection);
}
// Check the projection to see if we can get units -- if not, refer
// to properties.
this.units = this.projection.getUnits() ||
this.units || this.map.units;
this.initResolutions();
if (!this.isBaseLayer) {
this.inRange = this.calculateInRange();
var show = ((this.visibility) && (this.inRange));
this.div.style.display = show ? "" : "none";
}
// deal with gutters
this.setTileSize();
}
},
/**
* Method: afterAdd
* Called at the end of the map.addLayer sequence. At this point, the map
* will have a base layer. To be overridden by subclasses.
*/
afterAdd: function() {
},
/**
* APIMethod: removeMap
* Just as setMap() allows each layer the possibility to take a
* personalized action on being added to the map, removeMap() allows
* each layer to take a personalized action on being removed from it.
* For now, this will be mostly unused, except for the EventPane layer,
* which needs this hook so that it can remove the special invisible
* pane.
*
* Parameters:
* map - {}
*/
removeMap: function(map) {
//to be overridden by subclasses
},
/**
* APIMethod: getImageSize
*
* Parameters:
* bounds - {} optional tile bounds, can be used
* by subclasses that have to deal with different tile sizes at the
* layer extent edges (e.g. Zoomify)
*
* Returns:
* {} The size that the image should be, taking into
* account gutters.
*/
getImageSize: function(bounds) {
return (this.imageSize || this.tileSize);
},
/**
* APIMethod: setTileSize
* Set the tile size based on the map size. This also sets layer.imageSize
* and layer.imageOffset for use by Tile.Image.
*
* Parameters:
* size - {}
*/
setTileSize: function(size) {
var tileSize = (size) ? size :
((this.tileSize) ? this.tileSize :
this.map.getTileSize());
this.tileSize = tileSize;
if(this.gutter) {
// layers with gutters need non-null tile sizes
//if(tileSize == null) {
// OpenLayers.console.error("Error in layer.setMap() for " +
// this.name + ": layers with " +
// "gutters need non-null tile sizes");
//}
this.imageOffset = new OpenLayers.Pixel(-this.gutter,
-this.gutter);
this.imageSize = new OpenLayers.Size(tileSize.w + (2*this.gutter),
tileSize.h + (2*this.gutter));
}
},
/**
* APIMethod: getVisibility
*
* Returns:
* {Boolean} The layer should be displayed (if in range).
*/
getVisibility: function() {
return this.visibility;
},
/**
* APIMethod: setVisibility
* Set the visibility flag for the layer and hide/show & redraw
* accordingly. Fire event unless otherwise specified
*
* Note that visibility is no longer simply whether or not the layer's
* style.display is set to "block". Now we store a 'visibility' state
* property on the layer class, this allows us to remember whether or
* not we *desire* for a layer to be visible. In the case where the
* map's resolution is out of the layer's range, this desire may be
* subverted.
*
* Parameters:
* visibility - {Boolean} Whether or not to display the layer (if in range)
*/
setVisibility: function(visibility) {
if (visibility != this.visibility) {
this.visibility = visibility;
this.display(visibility);
this.redraw();
if (this.map != null) {
this.map.events.triggerEvent("changelayer", {
layer: this,
property: "visibility"
});
}
this.events.triggerEvent("visibilitychanged");
}
},
/**
* APIMethod: display
* Hide or show the Layer. This is designed to be used internally, and
* is not generally the way to enable or disable the layer. For that,
* use the setVisibility function instead..
*
* Parameters:
* display - {Boolean}
*/
display: function(display) {
if (display != (this.div.style.display != "none")) {
this.div.style.display = (display && this.calculateInRange()) ? "block" : "none";
}
},
/**
* APIMethod: calculateInRange
*
* Returns:
* {Boolean} The layer is displayable at the current map's current
* resolution. Note that if 'alwaysInRange' is true for the layer,
* this function will always return true.
*/
calculateInRange: function() {
var inRange = false;
if (this.alwaysInRange) {
inRange = true;
} else {
if (this.map) {
var resolution = this.map.getResolution();
inRange = ( (resolution >= this.minResolution) &&
(resolution <= this.maxResolution) );
}
}
return inRange;
},
/**
* APIMethod: setIsBaseLayer
*
* Parameters:
* isBaseLayer - {Boolean}
*/
setIsBaseLayer: function(isBaseLayer) {
if (isBaseLayer != this.isBaseLayer) {
this.isBaseLayer = isBaseLayer;
if (this.map != null) {
this.map.events.triggerEvent("changebaselayer", {
layer: this
});
}
}
},
/********************************************************/
/* */
/* Baselayer Functions */
/* */
/********************************************************/
/**
* Method: initResolutions
* This method's responsibility is to set up the 'resolutions' array
* for the layer -- this array is what the layer will use to interface
* between the zoom levels of the map and the resolution display
* of the layer.
*
* The user has several options that determine how the array is set up.
*
* For a detailed explanation, see the following wiki from the
* openlayers.org homepage:
* http://trac.openlayers.org/wiki/SettingZoomLevels
*/
initResolutions: function() {
// ok we want resolutions, here's our strategy:
//
// 1. if resolutions are defined in the layer config, use them
// 2. else, if scales are defined in the layer config then derive
// resolutions from these scales
// 3. else, attempt to calculate resolutions from maxResolution,
// minResolution, numZoomLevels, maxZoomLevel set in the
// layer config
// 4. if we still don't have resolutions, and if resolutions
// are defined in the same, use them
// 5. else, if scales are defined in the map then derive
// resolutions from these scales
// 6. else, attempt to calculate resolutions from maxResolution,
// minResolution, numZoomLevels, maxZoomLevel set in the
// map
// 7. hope for the best!
var i, len, p;
var props = {}, alwaysInRange = true;
// get resolution data from layer config
// (we also set alwaysInRange in the layer as appropriate)
for(i=0, len=this.RESOLUTION_PROPERTIES.length; i} A Bounds object which represents the lon/lat
* bounds of the current viewPort.
*/
getExtent: function() {
// just use stock map calculateBounds function -- passing no arguments
// means it will user map's current center & resolution
//
return this.map.calculateBounds();
},
/**
* APIMethod: getZoomForExtent
*
* Parameters:
* extent - {}
* closest - {Boolean} Find the zoom level that most closely fits the
* specified bounds. Note that this may result in a zoom that does
* not exactly contain the entire extent.
* Default is false.
*
* Returns:
* {Integer} The index of the zoomLevel (entry in the resolutions array)
* for the passed-in extent. We do this by calculating the ideal
* resolution for the given extent (based on the map size) and then
* calling getZoomForResolution(), passing along the 'closest'
* parameter.
*/
getZoomForExtent: function(extent, closest) {
var viewSize = this.map.getSize();
var idealResolution = Math.max( extent.getWidth() / viewSize.w,
extent.getHeight() / viewSize.h );
return this.getZoomForResolution(idealResolution, closest);
},
/**
* Method: getDataExtent
* Calculates the max extent which includes all of the data for the layer.
* This function is to be implemented by subclasses.
*
* Returns:
* {}
*/
getDataExtent: function () {
//to be implemented by subclasses
},
/**
* APIMethod: getResolutionForZoom
*
* Parameter:
* zoom - {Float}
*
* Returns:
* {Float} A suitable resolution for the specified zoom.
*/
getResolutionForZoom: function(zoom) {
zoom = Math.max(0, Math.min(zoom, this.resolutions.length - 1));
var resolution;
if(this.map.fractionalZoom) {
var low = Math.floor(zoom);
var high = Math.ceil(zoom);
resolution = this.resolutions[low] -
((zoom-low) * (this.resolutions[low]-this.resolutions[high]));
} else {
resolution = this.resolutions[Math.round(zoom)];
}
return resolution;
},
/**
* APIMethod: getZoomForResolution
*
* Parameters:
* resolution - {Float}
* closest - {Boolean} Find the zoom level that corresponds to the absolute
* closest resolution, which may result in a zoom whose corresponding
* resolution is actually smaller than we would have desired (if this
* is being called from a getZoomForExtent() call, then this means that
* the returned zoom index might not actually contain the entire
* extent specified... but it'll be close).
* Default is false.
*
* Returns:
* {Integer} The index of the zoomLevel (entry in the resolutions array)
* that corresponds to the best fit resolution given the passed in
* value and the 'closest' specification.
*/
getZoomForResolution: function(resolution, closest) {
var zoom, i, len;
if(this.map.fractionalZoom) {
var lowZoom = 0;
var highZoom = this.resolutions.length - 1;
var highRes = this.resolutions[lowZoom];
var lowRes = this.resolutions[highZoom];
var res;
for(i=0, len=this.resolutions.length; i= resolution) {
highRes = res;
lowZoom = i;
}
if(res <= resolution) {
lowRes = res;
highZoom = i;
break;
}
}
var dRes = highRes - lowRes;
if(dRes > 0) {
zoom = lowZoom + ((highRes - resolution) / dRes);
} else {
zoom = lowZoom;
}
} else {
var diff;
var minDiff = Number.POSITIVE_INFINITY;
for(i=0, len=this.resolutions.length; i minDiff) {
break;
}
minDiff = diff;
} else {
if (this.resolutions[i] < resolution) {
break;
}
}
}
zoom = Math.max(0, i-1);
}
return zoom;
},
/**
* APIMethod: getLonLatFromViewPortPx
*
* Parameters:
* viewPortPx - {}
*
* Returns:
* {} An OpenLayers.LonLat which is the passed-in
* view port , translated into lon/lat by the layer.
*/
getLonLatFromViewPortPx: function (viewPortPx) {
var lonlat = null;
var map = this.map;
if (viewPortPx != null && map.minPx) {
var res = map.getResolution();
var maxExtent = map.getMaxExtent({restricted: true});
var lon = (viewPortPx.x - map.minPx.x) * res + maxExtent.left;
var lat = (map.minPx.y - viewPortPx.y) * res + maxExtent.top;
lonlat = new OpenLayers.LonLat(lon, lat);
if (this.wrapDateLine) {
lonlat = lonlat.wrapDateLine(this.maxExtent);
}
}
return lonlat;
},
/**
* APIMethod: getViewPortPxFromLonLat
* Returns a pixel location given a map location. This method will return
* fractional pixel values.
*
* Parameters:
* lonlat - {}
*
* Returns:
* {} An which is the passed-in
* ,translated into view port pixels.
*/
getViewPortPxFromLonLat: function (lonlat) {
var px = null;
if (lonlat != null) {
var resolution = this.map.getResolution();
var extent = this.map.getExtent();
px = new OpenLayers.Pixel(
(1/resolution * (lonlat.lon - extent.left)),
(1/resolution * (extent.top - lonlat.lat))
);
}
return px;
},
/**
* APIMethod: setOpacity
* Sets the opacity for the entire layer (all images)
*
* Parameter:
* opacity - {Float}
*/
setOpacity: function(opacity) {
if (opacity != this.opacity) {
this.opacity = opacity;
for(var i=0, len=this.div.childNodes.length; i}
*/
adjustBounds: function (bounds) {
if (this.gutter) {
// Adjust the extent of a bounds in map units by the
// layer's gutter in pixels.
var mapGutter = this.gutter * this.map.getResolution();
bounds = new OpenLayers.Bounds(bounds.left - mapGutter,
bounds.bottom - mapGutter,
bounds.right + mapGutter,
bounds.top + mapGutter);
}
if (this.wrapDateLine) {
// wrap around the date line, within the limits of rounding error
var wrappingOptions = {
'rightTolerance':this.getResolution(),
'leftTolerance':this.getResolution()
};
bounds = bounds.wrapDateLine(this.maxExtent, wrappingOptions);
}
return bounds;
},
CLASS_NAME: "OpenLayers.Layer"
});
/* ======================================================================
OpenLayers/Layer/HTTPRequest.js
====================================================================== */
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Layer.js
*/
/**
* Class: OpenLayers.Layer.HTTPRequest
*
* Inherits from:
* -
*/
OpenLayers.Layer.HTTPRequest = OpenLayers.Class(OpenLayers.Layer, {
/**
* Constant: URL_HASH_FACTOR
* {Float} Used to hash URL param strings for multi-WMS server selection.
* Set to the Golden Ratio per Knuth's recommendation.
*/
URL_HASH_FACTOR: (Math.sqrt(5) - 1) / 2,
/**
* Property: url
* {Array(String) or String} This is either an array of url strings or
* a single url string.
*/
url: null,
/**
* Property: params
* {Object} Hashtable of key/value parameters
*/
params: null,
/**
* APIProperty: reproject
* *Deprecated*. See http://docs.openlayers.org/library/spherical_mercator.html
* for information on the replacement for this functionality.
* {Boolean} Whether layer should reproject itself based on base layer
* locations. This allows reprojection onto commercial layers.
* Default is false: Most layers can't reproject, but layers
* which can create non-square geographic pixels can, like WMS.
*
*/
reproject: false,
/**
* Constructor: OpenLayers.Layer.HTTPRequest
*
* Parameters:
* name - {String}
* url - {Array(String) or String}
* params - {Object}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, url, params, options) {
OpenLayers.Layer.prototype.initialize.apply(this, [name, options]);
this.url = url;
this.params = OpenLayers.Util.extend( {}, params);
},
/**
* APIMethod: destroy
*/
destroy: function() {
this.url = null;
this.params = null;
OpenLayers.Layer.prototype.destroy.apply(this, arguments);
},
/**
* APIMethod: clone
*
* Parameters:
* obj - {Object}
*
* Returns:
* {} An exact clone of this
*
*/
clone: function (obj) {
if (obj == null) {
obj = new OpenLayers.Layer.HTTPRequest(this.name,
this.url,
this.params,
this.getOptions());
}
//get all additions from superclasses
obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]);
// copy/set any non-init, non-simple values here
return obj;
},
/**
* APIMethod: setUrl
*
* Parameters:
* newUrl - {String}
*/
setUrl: function(newUrl) {
this.url = newUrl;
},
/**
* APIMethod: mergeNewParams
*
* Parameters:
* newParams - {Object}
*
* Returns:
* redrawn: {Boolean} whether the layer was actually redrawn.
*/
mergeNewParams:function(newParams) {
this.params = OpenLayers.Util.extend(this.params, newParams);
var ret = this.redraw();
if(this.map != null) {
this.map.events.triggerEvent("changelayer", {
layer: this,
property: "params"
});
}
return ret;
},
/**
* APIMethod: redraw
* Redraws the layer. Returns true if the layer was redrawn, false if not.
*
* Parameters:
* force - {Boolean} Force redraw by adding random parameter.
*
* Returns:
* {Boolean} The layer was redrawn.
*/
redraw: function(force) {
if (force) {
return this.mergeNewParams({"_olSalt": Math.random()});
} else {
return OpenLayers.Layer.prototype.redraw.apply(this, []);
}
},
/**
* Method: selectUrl
* selectUrl() implements the standard floating-point multiplicative
* hash function described by Knuth, and hashes the contents of the
* given param string into a float between 0 and 1. This float is then
* scaled to the size of the provided urls array, and used to select
* a URL.
*
* Parameters:
* paramString - {String}
* urls - {Array(String)}
*
* Returns:
* {String} An entry from the urls array, deterministically selected based
* on the paramString.
*/
selectUrl: function(paramString, urls) {
var product = 1;
for (var i=0, len=paramString.length; i constructor.
*
* Inherits from:
* -
*/
OpenLayers.Layer.Grid = OpenLayers.Class(OpenLayers.Layer.HTTPRequest, {
/**
* APIProperty: tileSize
* {}
*/
tileSize: null,
/**
* Property: tileOriginCorner
* {String} If the property is not provided, the tile origin
* will be derived from the layer's . The corner of the
* used is determined by this property. Acceptable values
* are "tl" (top left), "tr" (top right), "bl" (bottom left), and "br"
* (bottom right). Default is "bl".
*/
tileOriginCorner: "bl",
/**
* APIProperty: tileOrigin
* {} Optional origin for aligning the grid of tiles.
* If provided, requests for tiles at all resolutions will be aligned
* with this location (no tiles shall overlap this location). If
* not provided, the grid of tiles will be aligned with the layer's
* . Default is ``null``.
*/
tileOrigin: null,
/** APIProperty: tileOptions
* {Object} optional configuration options for instances
* created by this Layer, if supported by the tile class.
*/
tileOptions: null,
/**
* Property: grid
* {Array(Array())} This is an array of rows, each row is
* an array of tiles.
*/
grid: null,
/**
* APIProperty: singleTile
* {Boolean} Moves the layer into single-tile mode, meaning that one tile
* will be loaded. The tile's size will be determined by the 'ratio'
* property. When the tile is dragged such that it does not cover the
* entire viewport, it is reloaded.
*/
singleTile: false,
/** APIProperty: ratio
* {Float} Used only when in single-tile mode, this specifies the
* ratio of the size of the single tile to the size of the map.
*/
ratio: 1.5,
/**
* APIProperty: buffer
* {Integer} Used only when in gridded mode, this specifies the number of
* extra rows and colums of tiles on each side which will
* surround the minimum grid tiles to cover the map.
* For very slow loading layers, a larger value may increase
* performance somewhat when dragging, but will increase bandwidth
* use significantly.
*/
buffer: 0,
/**
* APIProperty: numLoadingTiles
* {Integer} How many tiles are still loading?
*/
numLoadingTiles: 0,
/**
* APIProperty: tileLoadingDelay
* {Integer} - Number of milliseconds before we shift and load
* tiles. Default is 100.
*/
tileLoadingDelay: 100,
/**
* Property: timerId
* {Number} - The id of the tileLoadingDelay timer.
*/
timerId: null,
/**
* Constructor: OpenLayers.Layer.Grid
* Create a new grid layer
*
* Parameters:
* name - {String}
* url - {String}
* params - {Object}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, url, params, options) {
OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,
arguments);
//grid layers will trigger 'tileloaded' when each new tile is
// loaded, as a means of progress update to listeners.
// listeners can access 'numLoadingTiles' if they wish to keep track
// of the loading progress
//
this.events.addEventType("tileloaded");
this.grid = [];
this._moveGriddedTiles = OpenLayers.Function.bind(
this.moveGriddedTiles, this
);
},
/**
* Method: removeMap
* Called when the layer is removed from the map.
*
* Parameters:
* map - {