2010-03-02 Miguel de Dios <miguel.dedios@artica.es>

* include/javascript/OpenLayers/lib/*, 
	include/javascript/OpenLayers/news.txt, 
	include/javascript/OpenLayers/readme.txt,
	include/javascript/OpenLayers/repository-license.txt,
	include/javascript/OpenLayers/release-license.txt: delete unused files of
	OpenLayers lib.



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@2449 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
This commit is contained in:
mdtrooper 2010-03-02 15:51:33 +00:00
parent f869f56312
commit 1dcec08556
230 changed files with 9 additions and 65059 deletions

View File

@ -1,3 +1,12 @@
2010-03-02 Miguel de Dios <miguel.dedios@artica.es>
* include/javascript/OpenLayers/lib/*,
include/javascript/OpenLayers/news.txt,
include/javascript/OpenLayers/readme.txt,
include/javascript/OpenLayers/repository-license.txt,
include/javascript/OpenLayers/release-license.txt: delete unused files of
OpenLayers lib.
2010-03-02 Miguel de Dios <miguel.dedios@artica.es>
* operation/gis_maps/render_view.php: clean source code.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 457 B

View File

@ -1,209 +0,0 @@
html, body {
margin: 0;
background: #FFFFFF;
font-family: Lucida Grande, Tahoma, sans-serif;
font-size: 11px;
overflow: hidden;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.toolbar {
height: 14px;
border-top: 1px solid ThreeDHighlight;
border-bottom: 1px solid ThreeDShadow;
padding: 2px 6px;
background: ThreeDFace;
}
.toolbarRight {
position: absolute;
top: 4px;
right: 6px;
}
#log {
overflow: auto;
position: absolute;
left: 0;
width: 100%;
}
#commandLine {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 18px;
border: none;
border-top: 1px solid ThreeDShadow;
}
/************************************************************************************************/
.logRow {
position: relative;
border-bottom: 1px solid #D7D7D7;
padding: 2px 4px 1px 6px;
background-color: #FFFFFF;
}
.logRow-command {
font-family: Monaco, monospace;
color: blue;
}
.objectBox-null {
padding: 0 2px;
border: 1px solid #666666;
background-color: #888888;
color: #FFFFFF;
}
.objectBox-string {
font-family: Monaco, monospace;
color: red;
white-space: pre;
}
.objectBox-number {
color: #000088;
}
.objectBox-function {
font-family: Monaco, monospace;
color: DarkGreen;
}
.objectBox-object {
color: DarkGreen;
font-weight: bold;
}
/************************************************************************************************/
.logRow-info,
.logRow-error,
.logRow-warning {
background: #FFFFFF no-repeat 2px 2px;
padding-left: 20px;
padding-bottom: 3px;
}
.logRow-info {
background-image: url(infoIcon.png);
}
.logRow-warning {
background-color: cyan;
background-image: url(warningIcon.png);
}
.logRow-error {
background-color: LightYellow;
background-image: url(errorIcon.png);
}
.errorMessage {
vertical-align: top;
color: #FF0000;
}
.objectBox-sourceLink {
position: absolute;
right: 4px;
top: 2px;
padding-left: 8px;
font-family: Lucida Grande, sans-serif;
font-weight: bold;
color: #0000FF;
}
/************************************************************************************************/
.logRow-group {
background: #EEEEEE;
border-bottom: none;
}
.logGroup {
background: #EEEEEE;
}
.logGroupBox {
margin-left: 24px;
border-top: 1px solid #D7D7D7;
border-left: 1px solid #D7D7D7;
}
/************************************************************************************************/
.selectorTag,
.selectorId,
.selectorClass {
font-family: Monaco, monospace;
font-weight: normal;
}
.selectorTag {
color: #0000FF;
}
.selectorId {
color: DarkBlue;
}
.selectorClass {
color: red;
}
/************************************************************************************************/
.objectBox-element {
font-family: Monaco, monospace;
color: #000088;
}
.nodeChildren {
margin-left: 16px;
}
.nodeTag {
color: blue;
}
.nodeValue {
color: #FF0000;
font-weight: normal;
}
.nodeText,
.nodeComment {
margin: 0 2px;
vertical-align: top;
}
.nodeText {
color: #333333;
}
.nodeComment {
color: DarkGreen;
}
/************************************************************************************************/
.propertyNameCell {
vertical-align: top;
}
.propertyName {
font-weight: bold;
}

View File

@ -1,23 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Firebug</title>
<link rel="stylesheet" type="text/css" href="firebug.css">
</head>
<body>
<div id="toolbar" class="toolbar">
<a href="#" onclick="parent.console.clear()">Clear</a>
<span class="toolbarRight">
<a href="#" onclick="parent.console.close()">Close</a>
</span>
</div>
<div id="log"></div>
<input type="text" id="commandLine">
<script>parent.onFirebugReady(document);</script>
</body>
</html>

View File

@ -1,674 +0,0 @@
if (!window.console || !console.firebug) { (function()
{
window.console =
{
log: function()
{
logFormatted(arguments, "");
},
debug: function()
{
logFormatted(arguments, "debug");
},
info: function()
{
logFormatted(arguments, "info");
},
warn: function()
{
logFormatted(arguments, "warning");
},
error: function()
{
logFormatted(arguments, "error");
},
assert: function(truth, message)
{
if (!truth)
{
var args = [];
for (var i = 1; i < arguments.length; ++i)
args.push(arguments[i]);
logFormatted(args.length ? args : ["Assertion Failure"], "error");
throw message ? message : "Assertion Failure";
}
},
dir: function(object)
{
var html = [];
var pairs = [];
for (var name in object)
{
try
{
pairs.push([name, object[name]]);
}
catch (exc)
{
}
}
pairs.sort(function(a, b) { return a[0] < b[0] ? -1 : 1; });
html.push('<table>');
for (var i = 0; i < pairs.length; ++i)
{
var name = pairs[i][0], value = pairs[i][1];
html.push('<tr>',
'<td class="propertyNameCell"><span class="propertyName">',
escapeHTML(name), '</span></td>', '<td><span class="propertyValue">');
appendObject(value, html);
html.push('</span></td></tr>');
}
html.push('</table>');
logRow(html, "dir");
},
dirxml: function(node)
{
var html = [];
appendNode(node, html);
logRow(html, "dirxml");
},
group: function()
{
logRow(arguments, "group", pushGroup);
},
groupEnd: function()
{
logRow(arguments, "", popGroup);
},
time: function(name)
{
timeMap[name] = (new Date()).getTime();
},
timeEnd: function(name)
{
if (name in timeMap)
{
var delta = (new Date()).getTime() - timeMap[name];
logFormatted([name+ ":", delta+"ms"]);
delete timeMap[name];
}
},
count: function()
{
this.warn(["count() not supported."]);
},
trace: function()
{
this.warn(["trace() not supported."]);
},
profile: function()
{
this.warn(["profile() not supported."]);
},
profileEnd: function()
{
},
clear: function()
{
consoleBody.innerHTML = "";
},
open: function()
{
toggleConsole(true);
},
close: function()
{
if (frameVisible)
toggleConsole();
}
};
// ********************************************************************************************
var consoleFrame = null;
var consoleBody = null;
var commandLine = null;
var frameVisible = false;
var messageQueue = [];
var groupStack = [];
var timeMap = {};
var clPrefix = ">>> ";
var isFirefox = navigator.userAgent.indexOf("Firefox") != -1;
var isIE = navigator.userAgent.indexOf("MSIE") != -1;
var isOpera = navigator.userAgent.indexOf("Opera") != -1;
var isSafari = navigator.userAgent.indexOf("AppleWebKit") != -1;
// ********************************************************************************************
function toggleConsole(forceOpen)
{
frameVisible = forceOpen || !frameVisible;
if (consoleFrame)
consoleFrame.style.visibility = frameVisible ? "visible" : "hidden";
else
waitForBody();
}
function focusCommandLine()
{
toggleConsole(true);
if (commandLine)
commandLine.focus();
}
function waitForBody()
{
if (document.body)
createFrame();
else
setTimeout(waitForBody, 200);
}
function createFrame()
{
if (consoleFrame)
return;
window.onFirebugReady = function(doc)
{
window.onFirebugReady = null;
var toolbar = doc.getElementById("toolbar");
toolbar.onmousedown = onSplitterMouseDown;
commandLine = doc.getElementById("commandLine");
addEvent(commandLine, "keydown", onCommandLineKeyDown);
addEvent(doc, isIE || isSafari ? "keydown" : "keypress", onKeyDown);
consoleBody = doc.getElementById("log");
layout();
flush();
}
var baseURL = getFirebugURL();
consoleFrame = document.createElement("iframe");
consoleFrame.setAttribute("src", baseURL+"/firebug.html");
consoleFrame.setAttribute("frameBorder", "0");
consoleFrame.style.visibility = (frameVisible ? "visible" : "hidden");
consoleFrame.style.zIndex = "2147483583";
consoleFrame.style.position = document.all ? "absolute" : "fixed";
consoleFrame.style.width = "100%";
consoleFrame.style.left = "0";
consoleFrame.style.bottom = "0";
consoleFrame.style.height = "200px";
document.body.appendChild(consoleFrame);
}
function getFirebugURL()
{
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i)
{
if (scripts[i].src.indexOf("firebug.js") != -1)
{
var lastSlash = scripts[i].src.lastIndexOf("/");
return scripts[i].src.substr(0, lastSlash);
}
}
}
function evalCommandLine()
{
var text = commandLine.value;
commandLine.value = "";
logRow([clPrefix, text], "command");
var value;
try
{
value = eval(text);
}
catch (exc)
{
}
console.log(value);
}
function layout()
{
var toolbar = consoleBody.ownerDocument.getElementById("toolbar");
var height = consoleFrame.offsetHeight - (toolbar.offsetHeight + commandLine.offsetHeight);
height = Math.max(height, 0);
consoleBody.style.top = toolbar.offsetHeight + "px";
consoleBody.style.height = height + "px";
commandLine.style.top = (consoleFrame.offsetHeight - commandLine.offsetHeight) + "px";
}
function logRow(message, className, handler)
{
if (consoleBody)
writeMessage(message, className, handler);
else
{
messageQueue.push([message, className, handler]);
waitForBody();
}
}
function flush()
{
var queue = messageQueue;
messageQueue = [];
for (var i = 0; i < queue.length; ++i)
writeMessage(queue[i][0], queue[i][1], queue[i][2]);
}
function writeMessage(message, className, handler)
{
var isScrolledToBottom =
consoleBody.scrollTop + consoleBody.offsetHeight >= consoleBody.scrollHeight;
if (!handler)
handler = writeRow;
handler(message, className);
if (isScrolledToBottom)
consoleBody.scrollTop = consoleBody.scrollHeight - consoleBody.offsetHeight;
}
function appendRow(row)
{
var container = groupStack.length ? groupStack[groupStack.length-1] : consoleBody;
container.appendChild(row);
}
function writeRow(message, className)
{
var row = consoleBody.ownerDocument.createElement("div");
row.className = "logRow" + (className ? " logRow-"+className : "");
row.innerHTML = message.join("");
appendRow(row);
}
function pushGroup(message, className)
{
logFormatted(message, className);
var groupRow = consoleBody.ownerDocument.createElement("div");
groupRow.className = "logGroup";
var groupRowBox = consoleBody.ownerDocument.createElement("div");
groupRowBox.className = "logGroupBox";
groupRow.appendChild(groupRowBox);
appendRow(groupRowBox);
groupStack.push(groupRowBox);
}
function popGroup()
{
groupStack.pop();
}
// ********************************************************************************************
function logFormatted(objects, className)
{
var html = [];
var format = objects[0];
var objIndex = 0;
if (typeof(format) != "string")
{
format = "";
objIndex = -1;
}
var parts = parseFormat(format);
for (var i = 0; i < parts.length; ++i)
{
var part = parts[i];
if (part && typeof(part) == "object")
{
var object = objects[++objIndex];
part.appender(object, html);
}
else
appendText(part, html);
}
for (var i = objIndex+1; i < objects.length; ++i)
{
appendText(" ", html);
var object = objects[i];
if (typeof(object) == "string")
appendText(object, html);
else
appendObject(object, html);
}
logRow(html, className);
}
function parseFormat(format)
{
var parts = [];
var reg = /((^%|[^\\]%)(\d+)?(\.)([a-zA-Z]))|((^%|[^\\]%)([a-zA-Z]))/;
var appenderMap = {s: appendText, d: appendInteger, i: appendInteger, f: appendFloat};
for (var m = reg.exec(format); m; m = reg.exec(format))
{
var type = m[8] ? m[8] : m[5];
var appender = type in appenderMap ? appenderMap[type] : appendObject;
var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0);
parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1));
parts.push({appender: appender, precision: precision});
format = format.substr(m.index+m[0].length);
}
parts.push(format);
return parts;
}
function escapeHTML(value)
{
function replaceChars(ch)
{
switch (ch)
{
case "<":
return "&lt;";
case ">":
return "&gt;";
case "&":
return "&amp;";
case "'":
return "&#39;";
case '"':
return "&quot;";
}
return "?";
};
return String(value).replace(/[<>&"']/g, replaceChars);
}
function objectToString(object)
{
try
{
return object+"";
}
catch (exc)
{
return null;
}
}
// ********************************************************************************************
function appendText(object, html)
{
html.push(escapeHTML(objectToString(object)));
}
function appendNull(object, html)
{
html.push('<span class="objectBox-null">', escapeHTML(objectToString(object)), '</span>');
}
function appendString(object, html)
{
html.push('<span class="objectBox-string">&quot;', escapeHTML(objectToString(object)),
'&quot;</span>');
}
function appendInteger(object, html)
{
html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>');
}
function appendFloat(object, html)
{
html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>');
}
function appendFunction(object, html)
{
var reName = /function ?(.*?)\(/;
var m = reName.exec(objectToString(object));
var name = m ? m[1] : "function";
html.push('<span class="objectBox-function">', escapeHTML(name), '()</span>');
}
function appendObject(object, html)
{
try
{
if (object == undefined)
appendNull("undefined", html);
else if (object == null)
appendNull("null", html);
else if (typeof object == "string")
appendString(object, html);
else if (typeof object == "number")
appendInteger(object, html);
else if (typeof object == "function")
appendFunction(object, html);
else if (object.nodeType == 1)
appendSelector(object, html);
else if (typeof object == "object")
appendObjectFormatted(object, html);
else
appendText(object, html);
}
catch (exc)
{
}
}
function appendObjectFormatted(object, html)
{
var text = objectToString(object);
var reObject = /\[object (.*?)\]/;
var m = reObject.exec(text);
html.push('<span class="objectBox-object">', m ? m[1] : text, '</span>')
}
function appendSelector(object, html)
{
html.push('<span class="objectBox-selector">');
html.push('<span class="selectorTag">', escapeHTML(object.nodeName.toLowerCase()), '</span>');
if (object.id)
html.push('<span class="selectorId">#', escapeHTML(object.id), '</span>');
if (object.className)
html.push('<span class="selectorClass">.', escapeHTML(object.className), '</span>');
html.push('</span>');
}
function appendNode(node, html)
{
if (node.nodeType == 1)
{
html.push(
'<div class="objectBox-element">',
'&lt;<span class="nodeTag">', node.nodeName.toLowerCase(), '</span>');
for (var i = 0; i < node.attributes.length; ++i)
{
var attr = node.attributes[i];
if (!attr.specified)
continue;
html.push('&nbsp;<span class="nodeName">', attr.nodeName.toLowerCase(),
'</span>=&quot;<span class="nodeValue">', escapeHTML(attr.nodeValue),
'</span>&quot;')
}
if (node.firstChild)
{
html.push('&gt;</div><div class="nodeChildren">');
for (var child = node.firstChild; child; child = child.nextSibling)
appendNode(child, html);
html.push('</div><div class="objectBox-element">&lt;/<span class="nodeTag">',
node.nodeName.toLowerCase(), '&gt;</span></div>');
}
else
html.push('/&gt;</div>');
}
else if (node.nodeType == 3)
{
html.push('<div class="nodeText">', escapeHTML(node.nodeValue),
'</div>');
}
}
// ********************************************************************************************
function addEvent(object, name, handler)
{
if (document.all)
object.attachEvent("on"+name, handler);
else
object.addEventListener(name, handler, false);
}
function removeEvent(object, name, handler)
{
if (document.all)
object.detachEvent("on"+name, handler);
else
object.removeEventListener(name, handler, false);
}
function cancelEvent(event)
{
if (document.all)
event.cancelBubble = true;
else
event.stopPropagation();
}
function onError(msg, href, lineNo)
{
var html = [];
var lastSlash = href.lastIndexOf("/");
var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1);
html.push(
'<span class="errorMessage">', msg, '</span>',
'<div class="objectBox-sourceLink">', fileName, ' (line ', lineNo, ')</div>'
);
logRow(html, "error");
};
function onKeyDown(event)
{
if (event.keyCode == 123)
toggleConsole();
else if ((event.keyCode == 108 || event.keyCode == 76) && event.shiftKey
&& (event.metaKey || event.ctrlKey))
focusCommandLine();
else
return;
cancelEvent(event);
}
function onSplitterMouseDown(event)
{
if (isSafari || isOpera)
return;
addEvent(document, "mousemove", onSplitterMouseMove);
addEvent(document, "mouseup", onSplitterMouseUp);
for (var i = 0; i < frames.length; ++i)
{
addEvent(frames[i].document, "mousemove", onSplitterMouseMove);
addEvent(frames[i].document, "mouseup", onSplitterMouseUp);
}
}
function onSplitterMouseMove(event)
{
var win = document.all
? event.srcElement.ownerDocument.parentWindow
: event.target.ownerDocument.defaultView;
var clientY = event.clientY;
if (win != win.parent)
clientY += win.frameElement ? win.frameElement.offsetTop : 0;
var height = consoleFrame.offsetTop + consoleFrame.clientHeight;
var toolbar = consoleBody.ownerDocument.getElementById("toolbar");
var y = Math.max(height - clientY,
toolbar.offsetHeight + commandLine.offsetHeight);
consoleFrame.style.height = y + "px";
layout();
}
function onSplitterMouseUp(event)
{
removeEvent(document, "mousemove", onSplitterMouseMove);
removeEvent(document, "mouseup", onSplitterMouseUp);
for (var i = 0; i < frames.length; ++i)
{
removeEvent(frames[i].document, "mousemove", onSplitterMouseMove);
removeEvent(frames[i].document, "mouseup", onSplitterMouseUp);
}
}
function onCommandLineKeyDown(event)
{
if (event.keyCode == 13)
evalCommandLine();
else if (event.keyCode == 27)
commandLine.value = "";
}
window.onerror = onError;
addEvent(document, isIE || isSafari ? "keydown" : "keypress", onKeyDown);
if (document.documentElement.getAttribute("debug") == "true")
toggleConsole(true);
})();
}

View File

@ -1,9 +0,0 @@
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 524 B

View File

@ -1,30 +0,0 @@
Software License Agreement (BSD License)
Copyright (c) 2007, Parakey Inc.
All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of Parakey Inc. nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of Parakey Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,13 +0,0 @@
This directory contains the source for Firebug Lite
(http://www.getfirebug.com/lite.html). This code is distributed with a
BSD License, Copyright (c) 2007, Parakey Inc. See the included license.txt
for the full text of the license.
This is a patched version of the trunk from
http://fbug.googlecode.com/svn/trunk.
Revision 36 was patched to resolve the issue described here
http://code.google.com/p/fbug/issues/detail?id=85
When this issue is resolved, Firebug Lite can be used directly - no further
modifications are needed for OpenLayers.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 516 B

View File

@ -1,88 +0,0 @@
/*
* Copyright 2007, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Google Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Sets up google.gears.*, which is *the only* supported way to access Gears.
*
* Circumvent this file at your own risk!
*
* In the future, Gears may automatically define google.gears.* without this
* file. Gears may use these objects to transparently fix bugs and compatibility
* issues. Applications that use the code below will continue to work seamlessly
* when that happens.
*/
(function() {
// We are already defined. Hooray!
if (window.google && google.gears) {
return;
}
var factory = null;
// Firefox
if (typeof GearsFactory != 'undefined') {
factory = new GearsFactory();
} else {
// IE
try {
factory = new ActiveXObject('Gears.Factory');
// privateSetGlobalObject is only required and supported on WinCE.
if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
factory.privateSetGlobalObject(this);
}
} catch (e) {
// Safari
if ((typeof navigator.mimeTypes != 'undefined')
&& navigator.mimeTypes["application/x-googlegears"]) {
factory = document.createElement("object");
factory.style.display = "none";
factory.width = 0;
factory.height = 0;
factory.type = "application/x-googlegears";
document.documentElement.appendChild(factory);
}
}
}
// *Do not* define any objects if Gears is not installed. This mimics the
// behavior of Gears defining the objects in the future.
if (!factory) {
return;
}
// Now set up the objects, being careful not to overwrite anything.
//
// Note: In Internet Explorer for Windows Mobile, you can't add properties to
// the window object. However, global objects are automatically added as
// properties of the window object in all browsers.
if (!window.google) {
google = {};
}
if (!google.gears) {
google.gears = {factory: factory};
}
})();

View File

@ -1,299 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., 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.js
* @requires OpenLayers/Lang/en.js
* @requires OpenLayers/Console.js
*/
(function() {
/**
* Before creating the OpenLayers namespace, check to see if
* OpenLayers.singleFile is true. This occurs if the
* OpenLayers/SingleFile.js script is included before this one - as is the
* case with single file builds.
*/
var singleFile = (typeof OpenLayers == "object" && OpenLayers.singleFile);
/**
* Namespace: OpenLayers
* The OpenLayers object provides a namespace for all things OpenLayers
*/
window.OpenLayers = {
/**
* Property: _scriptName
* {String} Relative path of this script.
*/
_scriptName: (!singleFile) ? "lib/OpenLayers.js" : "OpenLayers.js",
/**
* Function: _getScriptLocation
* Return the path to this script.
*
* Returns:
* {String} Path to this script
*/
_getScriptLocation: function () {
var scriptLocation = "";
var isOL = new RegExp("(^|(.*?\\/))(" + OpenLayers._scriptName + ")(\\?|$)");
var scripts = document.getElementsByTagName('script');
for (var i=0, len=scripts.length; i<len; i++) {
var src = scripts[i].getAttribute('src');
if (src) {
var match = src.match(isOL);
if(match) {
scriptLocation = match[1];
break;
}
}
}
return scriptLocation;
}
};
/**
* OpenLayers.singleFile is a flag indicating this file is being included
* in a Single File Library build of the OpenLayers Library.
*
* When we are *not* part of a SFL build we dynamically include the
* OpenLayers library code.
*
* When we *are* part of a SFL build we do not dynamically include the
* OpenLayers library code as it will be appended at the end of this file.
*/
if(!singleFile) {
var jsfiles = new Array(
"OpenLayers/Util.js",
"OpenLayers/BaseTypes.js",
"OpenLayers/BaseTypes/Class.js",
"OpenLayers/BaseTypes/Bounds.js",
"OpenLayers/BaseTypes/Element.js",
"OpenLayers/BaseTypes/LonLat.js",
"OpenLayers/BaseTypes/Pixel.js",
"OpenLayers/BaseTypes/Size.js",
"OpenLayers/Console.js",
"OpenLayers/Tween.js",
"Rico/Corner.js",
"Rico/Color.js",
"OpenLayers/Ajax.js",
"OpenLayers/Events.js",
"OpenLayers/Request.js",
"OpenLayers/Request/XMLHttpRequest.js",
"OpenLayers/Projection.js",
"OpenLayers/Map.js",
"OpenLayers/Layer.js",
"OpenLayers/Icon.js",
"OpenLayers/Marker.js",
"OpenLayers/Marker/Box.js",
"OpenLayers/Popup.js",
"OpenLayers/Tile.js",
"OpenLayers/Tile/Image.js",
"OpenLayers/Tile/WFS.js",
"OpenLayers/Layer/Image.js",
"OpenLayers/Layer/SphericalMercator.js",
"OpenLayers/Layer/EventPane.js",
"OpenLayers/Layer/FixedZoomLevels.js",
"OpenLayers/Layer/Google.js",
"OpenLayers/Layer/VirtualEarth.js",
"OpenLayers/Layer/Yahoo.js",
"OpenLayers/Layer/HTTPRequest.js",
"OpenLayers/Layer/Grid.js",
"OpenLayers/Layer/MapGuide.js",
"OpenLayers/Layer/MapServer.js",
"OpenLayers/Layer/MapServer/Untiled.js",
"OpenLayers/Layer/KaMap.js",
"OpenLayers/Layer/KaMapCache.js",
"OpenLayers/Layer/MultiMap.js",
"OpenLayers/Layer/Markers.js",
"OpenLayers/Layer/Text.js",
"OpenLayers/Layer/WorldWind.js",
"OpenLayers/Layer/ArcGIS93Rest.js",
"OpenLayers/Layer/WMS.js",
"OpenLayers/Layer/WMS/Untiled.js",
"OpenLayers/Layer/ArcIMS.js",
"OpenLayers/Layer/GeoRSS.js",
"OpenLayers/Layer/Boxes.js",
"OpenLayers/Layer/XYZ.js",
"OpenLayers/Layer/TMS.js",
"OpenLayers/Layer/TileCache.js",
"OpenLayers/Popup/Anchored.js",
"OpenLayers/Popup/AnchoredBubble.js",
"OpenLayers/Popup/Framed.js",
"OpenLayers/Popup/FramedCloud.js",
"OpenLayers/Feature.js",
"OpenLayers/Feature/Vector.js",
"OpenLayers/Feature/WFS.js",
"OpenLayers/Handler.js",
"OpenLayers/Handler/Click.js",
"OpenLayers/Handler/Hover.js",
"OpenLayers/Handler/Point.js",
"OpenLayers/Handler/Path.js",
"OpenLayers/Handler/Polygon.js",
"OpenLayers/Handler/Feature.js",
"OpenLayers/Handler/Drag.js",
"OpenLayers/Handler/RegularPolygon.js",
"OpenLayers/Handler/Box.js",
"OpenLayers/Handler/MouseWheel.js",
"OpenLayers/Handler/Keyboard.js",
"OpenLayers/Control.js",
"OpenLayers/Control/Attribution.js",
"OpenLayers/Control/Button.js",
"OpenLayers/Control/ZoomBox.js",
"OpenLayers/Control/ZoomToMaxExtent.js",
"OpenLayers/Control/DragPan.js",
"OpenLayers/Control/Navigation.js",
"OpenLayers/Control/MouseDefaults.js",
"OpenLayers/Control/MousePosition.js",
"OpenLayers/Control/OverviewMap.js",
"OpenLayers/Control/KeyboardDefaults.js",
"OpenLayers/Control/PanZoom.js",
"OpenLayers/Control/PanZoomBar.js",
"OpenLayers/Control/ArgParser.js",
"OpenLayers/Control/Permalink.js",
"OpenLayers/Control/Scale.js",
"OpenLayers/Control/ScaleLine.js",
"OpenLayers/Control/Snapping.js",
"OpenLayers/Control/Split.js",
"OpenLayers/Control/LayerSwitcher.js",
"OpenLayers/Control/DrawFeature.js",
"OpenLayers/Control/DragFeature.js",
"OpenLayers/Control/ModifyFeature.js",
"OpenLayers/Control/Panel.js",
"OpenLayers/Control/SelectFeature.js",
"OpenLayers/Control/NavigationHistory.js",
"OpenLayers/Control/Measure.js",
"OpenLayers/Control/WMSGetFeatureInfo.js",
"OpenLayers/Geometry.js",
"OpenLayers/Geometry/Rectangle.js",
"OpenLayers/Geometry/Collection.js",
"OpenLayers/Geometry/Point.js",
"OpenLayers/Geometry/MultiPoint.js",
"OpenLayers/Geometry/Curve.js",
"OpenLayers/Geometry/LineString.js",
"OpenLayers/Geometry/LinearRing.js",
"OpenLayers/Geometry/Polygon.js",
"OpenLayers/Geometry/MultiLineString.js",
"OpenLayers/Geometry/MultiPolygon.js",
"OpenLayers/Geometry/Surface.js",
"OpenLayers/Renderer.js",
"OpenLayers/Renderer/Elements.js",
"OpenLayers/Renderer/SVG.js",
"OpenLayers/Renderer/Canvas.js",
"OpenLayers/Renderer/VML.js",
"OpenLayers/Layer/Vector.js",
"OpenLayers/Layer/Vector/RootContainer.js",
"OpenLayers/Strategy.js",
"OpenLayers/Strategy/Fixed.js",
"OpenLayers/Strategy/Cluster.js",
"OpenLayers/Strategy/Paging.js",
"OpenLayers/Strategy/BBOX.js",
"OpenLayers/Strategy/Save.js",
"OpenLayers/Protocol.js",
"OpenLayers/Protocol/HTTP.js",
"OpenLayers/Protocol/SQL.js",
"OpenLayers/Protocol/SQL/Gears.js",
"OpenLayers/Protocol/WFS.js",
"OpenLayers/Protocol/WFS/v1.js",
"OpenLayers/Protocol/WFS/v1_0_0.js",
"OpenLayers/Protocol/WFS/v1_1_0.js",
"OpenLayers/Layer/PointTrack.js",
"OpenLayers/Layer/GML.js",
"OpenLayers/Style.js",
"OpenLayers/StyleMap.js",
"OpenLayers/Rule.js",
"OpenLayers/Filter.js",
"OpenLayers/Filter/FeatureId.js",
"OpenLayers/Filter/Logical.js",
"OpenLayers/Filter/Comparison.js",
"OpenLayers/Filter/Spatial.js",
"OpenLayers/Format.js",
"OpenLayers/Format/XML.js",
"OpenLayers/Format/ArcXML.js",
"OpenLayers/Format/ArcXML/Features.js",
"OpenLayers/Format/GML.js",
"OpenLayers/Format/GML/Base.js",
"OpenLayers/Format/GML/v2.js",
"OpenLayers/Format/GML/v3.js",
"OpenLayers/Format/KML.js",
"OpenLayers/Format/GeoRSS.js",
"OpenLayers/Format/WFS.js",
"OpenLayers/Format/WFSCapabilities.js",
"OpenLayers/Format/WFSCapabilities/v1.js",
"OpenLayers/Format/WFSCapabilities/v1_0_0.js",
"OpenLayers/Format/WFSCapabilities/v1_1_0.js",
"OpenLayers/Format/WFSDescribeFeatureType.js",
"OpenLayers/Format/WMSDescribeLayer.js",
"OpenLayers/Format/WMSDescribeLayer/v1_1.js",
"OpenLayers/Format/WKT.js",
"OpenLayers/Format/OSM.js",
"OpenLayers/Format/GPX.js",
"OpenLayers/Format/Filter.js",
"OpenLayers/Format/Filter/v1.js",
"OpenLayers/Format/Filter/v1_0_0.js",
"OpenLayers/Format/Filter/v1_1_0.js",
"OpenLayers/Format/SLD.js",
"OpenLayers/Format/SLD/v1.js",
"OpenLayers/Format/SLD/v1_0_0.js",
"OpenLayers/Format/SLD/v1.js",
"OpenLayers/Format/WFST.js",
"OpenLayers/Format/WFST/v1.js",
"OpenLayers/Format/WFST/v1_0_0.js",
"OpenLayers/Format/WFST/v1_1_0.js",
"OpenLayers/Format/Text.js",
"OpenLayers/Format/JSON.js",
"OpenLayers/Format/GeoJSON.js",
"OpenLayers/Format/WMC.js",
"OpenLayers/Format/WMC/v1.js",
"OpenLayers/Format/WMC/v1_0_0.js",
"OpenLayers/Format/WMC/v1_1_0.js",
"OpenLayers/Format/WMSCapabilities.js",
"OpenLayers/Format/WMSCapabilities/v1_1.js",
"OpenLayers/Format/WMSCapabilities/v1_1_0.js",
"OpenLayers/Format/WMSCapabilities/v1_1_1.js",
"OpenLayers/Format/WMSGetFeatureInfo.js",
"OpenLayers/Layer/WFS.js",
"OpenLayers/Control/GetFeature.js",
"OpenLayers/Control/MouseToolbar.js",
"OpenLayers/Control/NavToolbar.js",
"OpenLayers/Control/PanPanel.js",
"OpenLayers/Control/Pan.js",
"OpenLayers/Control/ZoomIn.js",
"OpenLayers/Control/ZoomOut.js",
"OpenLayers/Control/ZoomPanel.js",
"OpenLayers/Control/EditingToolbar.js",
"OpenLayers/Lang.js",
"OpenLayers/Lang/en.js"
); // etc.
var agent = navigator.userAgent;
var docWrite = (agent.match("MSIE") || agent.match("Safari"));
if(docWrite) {
var allScriptTags = new Array(jsfiles.length);
}
var host = OpenLayers._getScriptLocation() + "lib/";
for (var i=0, len=jsfiles.length; i<len; i++) {
if (docWrite) {
allScriptTags[i] = "<script src='" + host + jsfiles[i] +
"'></script>";
} else {
var s = document.createElement("script");
s.src = host + jsfiles[i];
var h = document.getElementsByTagName("head").length ?
document.getElementsByTagName("head")[0] :
document.body;
h.appendChild(s);
}
}
if (docWrite) {
document.write(allScriptTags.join(""));
}
}
})();
/**
* Constant: VERSION_NUMBER
*/
OpenLayers.VERSION_NUMBER="OpenLayers 2.8 -- $Revision: 9492 $";

View File

@ -1,677 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Request/XMLHttpRequest.js
* @requires OpenLayers/Console.js
*/
OpenLayers.ProxyHost = "";
//OpenLayers.ProxyHost = "examples/proxy.cgi?url=";
/**
* Ajax reader for OpenLayers
*
* @uri url to do remote XML http get
* @param {String} 'get' format params (x=y&a=b...)
* @who object to handle callbacks for this request
* @complete the function to be called on success
* @failure the function to be called on failure
*
* example usage from a caller:
*
* caps: function(request) {
* -blah-
* },
*
* OpenLayers.loadURL(url,params,this,caps);
*
* Notice the above example does not provide an error handler; a default empty
* handler is provided which merely logs the error if a failure handler is not
* supplied
*
*/
/**
* Function: OpenLayers.nullHandler
* @param {} request
*/
OpenLayers.nullHandler = function(request) {
OpenLayers.Console.userError(OpenLayers.i18n("unhandledRequest", {'statusText':request.statusText}));
};
/**
* APIFunction: loadURL
* Background load a document. For more flexibility in using XMLHttpRequest,
* see the <OpenLayers.Request> methods.
*
* Parameters:
* uri - {String} URI of source doc
* params - {String} or {Object} GET params. Either a string in the form
* "?hello=world&foo=bar" (do not forget the leading question mark)
* or an object in the form {'hello': 'world', 'foo': 'bar}
* caller - {Object} object which gets callbacks
* onComplete - {Function} Optional callback for success. The callback
* will be called with this set to caller and will receive the request
* object as an argument. Note that if you do not specify an onComplete
* function, <OpenLayers.nullHandler> will be called (which pops up a
* user friendly error message dialog).
* onFailure - {Function} Optional callback for failure. In the event of
* a failure, the callback will be called with this set to caller and will
* receive the request object as an argument. Note that if you do not
* specify an onComplete function, <OpenLayers.nullHandler> will be called
* (which pops up a user friendly error message dialog).
*
* Returns:
* {<OpenLayers.Request.XMLHttpRequest>} The request object. To abort loading,
* call request.abort().
*/
OpenLayers.loadURL = function(uri, params, caller,
onComplete, onFailure) {
if(typeof params == 'string') {
params = OpenLayers.Util.getParameters(params);
}
var success = (onComplete) ? onComplete : OpenLayers.nullHandler;
var failure = (onFailure) ? onFailure : OpenLayers.nullHandler;
return OpenLayers.Request.GET({
url: uri, params: params,
success: success, failure: failure, scope: caller
});
};
/**
* Function: parseXMLString
* Parse XML into a doc structure
*
* Parameters:
* text - {String}
*
* Returns:
* {?} Parsed AJAX Responsev
*/
OpenLayers.parseXMLString = function(text) {
//MS sucks, if the server is bad it dies
var index = text.indexOf('<');
if (index > 0) {
text = text.substring(index);
}
var ajaxResponse = OpenLayers.Util.Try(
function() {
var xmldom = new ActiveXObject('Microsoft.XMLDOM');
xmldom.loadXML(text);
return xmldom;
},
function() {
return new DOMParser().parseFromString(text, 'text/xml');
},
function() {
var req = new XMLHttpRequest();
req.open("GET", "data:" + "text/xml" +
";charset=utf-8," + encodeURIComponent(text), false);
if (req.overrideMimeType) {
req.overrideMimeType("text/xml");
}
req.send(null);
return req.responseXML;
}
);
return ajaxResponse;
};
/**
* Namespace: OpenLayers.Ajax
*/
OpenLayers.Ajax = {
/**
* Method: emptyFunction
*/
emptyFunction: function () {},
/**
* Method: getTransport
*
* Returns:
* {Object} Transport mechanism for whichever browser we're in, or false if
* none available.
*/
getTransport: function() {
return OpenLayers.Util.Try(
function() {return new XMLHttpRequest();},
function() {return new ActiveXObject('Msxml2.XMLHTTP');},
function() {return new ActiveXObject('Microsoft.XMLHTTP');}
) || false;
},
/**
* Property: activeRequestCount
* {Integer}
*/
activeRequestCount: 0
};
/**
* Namespace: OpenLayers.Ajax.Responders
* {Object}
*/
OpenLayers.Ajax.Responders = {
/**
* Property: responders
* {Array}
*/
responders: [],
/**
* Method: register
*
* Parameters:
* responderToAdd - {?}
*/
register: function(responderToAdd) {
for (var i = 0; i < this.responders.length; i++){
if (responderToAdd == this.responders[i]){
return;
}
}
this.responders.push(responderToAdd);
},
/**
* Method: unregister
*
* Parameters:
* responderToRemove - {?}
*/
unregister: function(responderToRemove) {
OpenLayers.Util.removeItem(this.reponders, responderToRemove);
},
/**
* Method: dispatch
*
* Parameters:
* callback - {?}
* request - {?}
* transport - {?}
*/
dispatch: function(callback, request, transport) {
var responder;
for (var i = 0; i < this.responders.length; i++) {
responder = this.responders[i];
if (responder[callback] &&
typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder,
[request, transport]);
} catch (e) {}
}
}
}
};
OpenLayers.Ajax.Responders.register({
/**
* Function: onCreate
*/
onCreate: function() {
OpenLayers.Ajax.activeRequestCount++;
},
/**
* Function: onComplete
*/
onComplete: function() {
OpenLayers.Ajax.activeRequestCount--;
}
});
/**
* Class: OpenLayers.Ajax.Base
*/
OpenLayers.Ajax.Base = OpenLayers.Class({
/**
* Constructor: OpenLayers.Ajax.Base
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/xml',
parameters: ''
};
OpenLayers.Util.extend(this.options, options || {});
this.options.method = this.options.method.toLowerCase();
if (typeof this.options.parameters == 'string') {
this.options.parameters =
OpenLayers.Util.getParameters(this.options.parameters);
}
}
});
/**
* Class: OpenLayers.Ajax.Request
* *Deprecated*. Use <OpenLayers.Request> method instead.
*
* Inherit:
* - <OpenLayers.Ajax.Base>
*/
OpenLayers.Ajax.Request = OpenLayers.Class(OpenLayers.Ajax.Base, {
/**
* Property: _complete
*
* {Boolean}
*/
_complete: false,
/**
* Constructor: OpenLayers.Ajax.Request
*
* Parameters:
* url - {String}
* options - {Object}
*/
initialize: function(url, options) {
OpenLayers.Ajax.Base.prototype.initialize.apply(this, [options]);
if (OpenLayers.ProxyHost && OpenLayers.String.startsWith(url, "http")) {
url = OpenLayers.ProxyHost + encodeURIComponent(url);
}
this.transport = OpenLayers.Ajax.getTransport();
this.request(url);
},
/**
* Method: request
*
* Parameters:
* url - {String}
*/
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = OpenLayers.Util.extend({}, this.options.parameters);
if (this.method != 'get' && this.method != 'post') {
// simulate other verbs over post
params['_method'] = this.method;
this.method = 'post';
}
this.parameters = params;
if (params = OpenLayers.Util.getParameterString(params)) {
// when GET, append parameters to URL
if (this.method == 'get') {
this.url += ((this.url.indexOf('?') > -1) ? '&' : '?') + params;
} else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
params += '&_=';
}
}
try {
var response = new OpenLayers.Ajax.Response(this);
if (this.options.onCreate) {
this.options.onCreate(response);
}
OpenLayers.Ajax.Responders.dispatch('onCreate',
this,
response);
this.transport.open(this.method.toUpperCase(),
this.url,
this.options.asynchronous);
if (this.options.asynchronous) {
window.setTimeout(
OpenLayers.Function.bind(this.respondToReadyState, this, 1),
10);
}
this.transport.onreadystatechange =
OpenLayers.Function.bind(this.onStateChange, this);
this.setRequestHeaders();
this.body = this.method == 'post' ?
(this.options.postBody || params) : null;
this.transport.send(this.body);
// Force Firefox to handle ready state 4 for synchronous requests
if (!this.options.asynchronous &&
this.transport.overrideMimeType) {
this.onStateChange();
}
} catch (e) {
this.dispatchException(e);
}
},
/**
* Method: onStateChange
*/
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete)) {
this.respondToReadyState(this.transport.readyState);
}
},
/**
* Method: setRequestHeaders
*/
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*',
'OpenLayers': true
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) {
headers['Connection'] = 'close';
}
}
// user-defined headers
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (typeof extras.push == 'function') {
for (var i = 0, length = extras.length; i < length; i += 2) {
headers[extras[i]] = extras[i+1];
}
} else {
for (var i in extras) {
headers[i] = extras[i];
}
}
}
for (var name in headers) {
this.transport.setRequestHeader(name, headers[name]);
}
},
/**
* Method: success
*
* Returns:
* {Boolean} -
*/
success: function() {
var status = this.getStatus();
return !status || (status >=200 && status < 300);
},
/**
* Method: getStatus
*
* Returns:
* {Integer} - Status
*/
getStatus: function() {
try {
return this.transport.status || 0;
} catch (e) {
return 0;
}
},
/**
* Method: respondToReadyState
*
* Parameters:
* readyState - {?}
*/
respondToReadyState: function(readyState) {
var state = OpenLayers.Ajax.Request.Events[readyState];
var response = new OpenLayers.Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + response.status] ||
this.options['on' + (this.success() ? 'Success' : 'Failure')] ||
OpenLayers.Ajax.emptyFunction)(response);
} catch (e) {
this.dispatchException(e);
}
var contentType = response.getHeader('Content-type');
}
try {
(this.options['on' + state] ||
OpenLayers.Ajax.emptyFunction)(response);
OpenLayers.Ajax.Responders.dispatch('on' + state,
this,
response);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
// avoid memory leak in MSIE: clean up
this.transport.onreadystatechange = OpenLayers.Ajax.emptyFunction;
}
},
/**
* Method: getHeader
*
* Parameters:
* name - {String} Header name
*
* Returns:
* {?} - response header for the given name
*/
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name);
} catch (e) {
return null;
}
},
/**
* Method: dispatchException
* If the optional onException function is set, execute it
* and then dispatch the call to any other listener registered
* for onException.
*
* If no optional onException function is set, we suspect that
* the user may have also not used
* OpenLayers.Ajax.Responders.register to register a listener
* for the onException call. To make sure that something
* gets done with this exception, only dispatch the call if there
* are listeners.
*
* If you explicitly want to swallow exceptions, set
* request.options.onException to an empty function (function(){})
* or register an empty function with <OpenLayers.Ajax.Responders>
* for onException.
*
* Parameters:
* exception - {?}
*/
dispatchException: function(exception) {
var handler = this.options.onException;
if(handler) {
// call options.onException and alert any other listeners
handler(this, exception);
OpenLayers.Ajax.Responders.dispatch('onException', this, exception);
} else {
// check if there are any other listeners
var listener = false;
var responders = OpenLayers.Ajax.Responders.responders;
for (var i = 0; i < responders.length; i++) {
if(responders[i].onException) {
listener = true;
break;
}
}
if(listener) {
// call all listeners
OpenLayers.Ajax.Responders.dispatch('onException', this, exception);
} else {
// let the exception through
throw exception;
}
}
}
});
/**
* Property: Events
* {Array(String)}
*/
OpenLayers.Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
/**
* Class: OpenLayers.Ajax.Response
*/
OpenLayers.Ajax.Response = OpenLayers.Class({
/**
* Property: status
*
* {Integer}
*/
status: 0,
/**
* Property: statusText
*
* {String}
*/
statusText: '',
/**
* Constructor: OpenLayers.Ajax.Response
*
* Parameters:
* request - {Object}
*/
initialize: function(request) {
this.request = request;
var transport = this.transport = request.transport,
readyState = this.readyState = transport.readyState;
if ((readyState > 2 &&
!(!!(window.attachEvent && !window.opera))) ||
readyState == 4) {
this.status = this.getStatus();
this.statusText = this.getStatusText();
this.responseText = transport.responseText == null ?
'' : String(transport.responseText);
}
if(readyState == 4) {
var xml = transport.responseXML;
this.responseXML = xml === undefined ? null : xml;
}
},
/**
* Method: getStatus
*/
getStatus: OpenLayers.Ajax.Request.prototype.getStatus,
/**
* Method: getStatustext
*
* Returns:
* {String} - statusText
*/
getStatusText: function() {
try {
return this.transport.statusText || '';
} catch (e) {
return '';
}
},
/**
* Method: getHeader
*/
getHeader: OpenLayers.Ajax.Request.prototype.getHeader,
/**
* Method: getResponseHeader
*
* Returns:
* {?} - response header for given name
*/
getResponseHeader: function(name) {
return this.transport.getResponseHeader(name);
}
});
/**
* Function: getElementsByTagNameNS
*
* Parameters:
* parentnode - {?}
* nsuri - {?}
* nsprefix - {?}
* tagname - {?}
*
* Returns:
* {?}
*/
OpenLayers.Ajax.getElementsByTagNameNS = function(parentnode, nsuri,
nsprefix, tagname) {
var elem = null;
if (parentnode.getElementsByTagNameNS) {
elem = parentnode.getElementsByTagNameNS(nsuri, tagname);
} else {
elem = parentnode.getElementsByTagName(nsprefix + ':' + tagname);
}
return elem;
};
/**
* Function: serializeXMLToString
* Wrapper function around XMLSerializer, which doesn't exist/work in
* IE/Safari. We need to come up with a way to serialize in those browser:
* for now, these browsers will just fail. #535, #536
*
* Parameters:
* xmldom {XMLNode} xml dom to serialize
*
* Returns:
* {?}
*/
OpenLayers.Ajax.serializeXMLToString = function(xmldom) {
var serializer = new XMLSerializer();
var data = serializer.serializeToString(xmldom);
return data;
};

View File

@ -1,529 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., 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/BaseTypes/LonLat.js
* @requires OpenLayers/BaseTypes/Size.js
* @requires OpenLayers/BaseTypes/Pixel.js
* @requires OpenLayers/BaseTypes/Bounds.js
* @requires OpenLayers/BaseTypes/Element.js
* @requires OpenLayers/Lang/en.js
* @requires OpenLayers/Console.js
*/
/**
* Header: OpenLayers Base Types
* OpenLayers custom string, number and function functions are described here.
*/
/**
* Namespace: OpenLayers.String
* Contains convenience functions for string manipulation.
*/
OpenLayers.String = {
/**
* APIFunction: startsWith
* Test whether a string starts with another string.
*
* Parameters:
* str - {String} The string to test.
* sub - {Sring} The substring to look for.
*
* Returns:
* {Boolean} The first string starts with the second.
*/
startsWith: function(str, sub) {
return (str.indexOf(sub) == 0);
},
/**
* APIFunction: contains
* Test whether a string contains another string.
*
* Parameters:
* str - {String} The string to test.
* sub - {String} The substring to look for.
*
* Returns:
* {Boolean} The first string contains the second.
*/
contains: function(str, sub) {
return (str.indexOf(sub) != -1);
},
/**
* APIFunction: trim
* Removes leading and trailing whitespace characters from a string.
*
* Parameters:
* str - {String} The (potentially) space padded string. This string is not
* modified.
*
* Returns:
* {String} A trimmed version of the string with all leading and
* trailing spaces removed.
*/
trim: function(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
},
/**
* APIFunction: camelize
* Camel-case a hyphenated string.
* Ex. "chicken-head" becomes "chickenHead", and
* "-chicken-head" becomes "ChickenHead".
*
* Parameters:
* str - {String} The string to be camelized. The original is not modified.
*
* Returns:
* {String} The string, camelized
*/
camelize: function(str) {
var oStringList = str.split('-');
var camelizedString = oStringList[0];
for (var i=1, len=oStringList.length; i<len; i++) {
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}
return camelizedString;
},
/**
* APIFunction: format
* Given a string with tokens in the form ${token}, return a string
* with tokens replaced with properties from the given context
* object. Represent a literal "${" by doubling it, e.g. "${${".
*
* Parameters:
* template - {String} A string with tokens to be replaced. A template
* has the form "literal ${token}" where the token will be replaced
* by the value of context["token"].
* context - {Object} An optional object with properties corresponding
* to the tokens in the format string. If no context is sent, the
* window object will be used.
* args - {Array} Optional arguments to pass to any functions found in
* the context. If a context property is a function, the token
* will be replaced by the return from the function called with
* these arguments.
*
* Returns:
* {String} A string with tokens replaced from the context object.
*/
format: function(template, context, args) {
if(!context) {
context = window;
}
// Example matching:
// str = ${foo.bar}
// match = foo.bar
var replacer = function(str, match) {
var replacement;
// Loop through all subs. Example: ${a.b.c}
// 0 -> replacement = context[a];
// 1 -> replacement = context[a][b];
// 2 -> replacement = context[a][b][c];
var subs = match.split(/\.+/);
for (var i=0; i< subs.length; i++) {
if (i == 0) {
replacement = context;
}
replacement = replacement[subs[i]];
}
if(typeof replacement == "function") {
replacement = args ?
replacement.apply(null, args) :
replacement();
}
// If replacement is undefined, return the string 'undefined'.
// This is a workaround for a bugs in browsers not properly
// dealing with non-participating groups in regular expressions:
// http://blog.stevenlevithan.com/archives/npcg-javascript
if (typeof replacement == 'undefined') {
return 'undefined';
} else {
return replacement;
}
};
return template.replace(OpenLayers.String.tokenRegEx, replacer);
},
/**
* Property: OpenLayers.String.tokenRegEx
* Used to find tokens in a string.
* Examples: ${a}, ${a.b.c}, ${a-b}, ${5}
*/
tokenRegEx: /\$\{([\w.]+?)\}/g,
/**
* Property: OpenLayers.String.numberRegEx
* Used to test strings as numbers.
*/
numberRegEx: /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,
/**
* APIFunction: OpenLayers.String.isNumeric
* Determine whether a string contains only a numeric value.
*
* Examples:
* (code)
* OpenLayers.String.isNumeric("6.02e23") // true
* OpenLayers.String.isNumeric("12 dozen") // false
* OpenLayers.String.isNumeric("4") // true
* OpenLayers.String.isNumeric(" 4 ") // false
* (end)
*
* Returns:
* {Boolean} String contains only a number.
*/
isNumeric: function(value) {
return OpenLayers.String.numberRegEx.test(value);
},
/**
* APIFunction: numericIf
* Converts a string that appears to be a numeric value into a number.
*
* Returns
* {Number|String} a Number if the passed value is a number, a String
* otherwise.
*/
numericIf: function(value) {
return OpenLayers.String.isNumeric(value) ? parseFloat(value) : value;
}
};
if (!String.prototype.startsWith) {
/**
* APIMethod: String.startsWith
* *Deprecated*. Whether or not a string starts with another string.
*
* Parameters:
* sStart - {Sring} The string we're testing for.
*
* Returns:
* {Boolean} Whether or not this string starts with the string passed in.
*/
String.prototype.startsWith = function(sStart) {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.String.startsWith'}));
return OpenLayers.String.startsWith(this, sStart);
};
}
if (!String.prototype.contains) {
/**
* APIMethod: String.contains
* *Deprecated*. Whether or not a string contains another string.
*
* Parameters:
* str - {String} The string that we're testing for.
*
* Returns:
* {Boolean} Whether or not this string contains with the string passed in.
*/
String.prototype.contains = function(str) {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.String.contains'}));
return OpenLayers.String.contains(this, str);
};
}
if (!String.prototype.trim) {
/**
* APIMethod: String.trim
* *Deprecated*. Removes leading and trailing whitespace characters from a string.
*
* Returns:
* {String} A trimmed version of the string - all leading and
* trailing spaces removed
*/
String.prototype.trim = function() {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.String.trim'}));
return OpenLayers.String.trim(this);
};
}
if (!String.prototype.camelize) {
/**
* APIMethod: String.camelize
* *Deprecated*. Camel-case a hyphenated string.
* Ex. "chicken-head" becomes "chickenHead", and
* "-chicken-head" becomes "ChickenHead".
*
* Returns:
* {String} The string, camelized
*/
String.prototype.camelize = function() {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.String.camelize'}));
return OpenLayers.String.camelize(this);
};
}
/**
* Namespace: OpenLayers.Number
* Contains convenience functions for manipulating numbers.
*/
OpenLayers.Number = {
/**
* Property: decimalSeparator
* Decimal separator to use when formatting numbers.
*/
decimalSeparator: ".",
/**
* Property: thousandsSeparator
* Thousands separator to use when formatting numbers.
*/
thousandsSeparator: ",",
/**
* APIFunction: limitSigDigs
* Limit the number of significant digits on a float.
*
* Parameters:
* num - {Float}
* sig - {Integer}
*
* Returns:
* {Float} The number, rounded to the specified number of significant
* digits.
*/
limitSigDigs: function(num, sig) {
var fig = 0;
if (sig > 0) {
fig = parseFloat(num.toPrecision(sig));
}
return fig;
},
/**
* APIFunction: format
* Formats a number for output.
*
* Parameters:
* num - {Float}
* dec - {Integer} Number of decimal places to round to.
* Defaults to 0. Set to null to leave decimal places unchanged.
* tsep - {String} Thousands separator.
* Default is ",".
* dsep - {String} Decimal separator.
* Default is ".".
*
* Returns:
* {String} A string representing the formatted number.
*/
format: function(num, dec, tsep, dsep) {
dec = (typeof dec != "undefined") ? dec : 0;
tsep = (typeof tsep != "undefined") ? tsep :
OpenLayers.Number.thousandsSeparator;
dsep = (typeof dsep != "undefined") ? dsep :
OpenLayers.Number.decimalSeparator;
if (dec != null) {
num = parseFloat(num.toFixed(dec));
}
var parts = num.toString().split(".");
if (parts.length == 1 && dec == null) {
// integer where we do not want to touch the decimals
dec = 0;
}
var integer = parts[0];
if (tsep) {
var thousands = /(-?[0-9]+)([0-9]{3})/;
while(thousands.test(integer)) {
integer = integer.replace(thousands, "$1" + tsep + "$2");
}
}
var str;
if (dec == 0) {
str = integer;
} else {
var rem = parts.length > 1 ? parts[1] : "0";
if (dec != null) {
rem = rem + new Array(dec - rem.length + 1).join("0");
}
str = integer + dsep + rem;
}
return str;
}
};
if (!Number.prototype.limitSigDigs) {
/**
* APIMethod: Number.limitSigDigs
* *Deprecated*. Limit the number of significant digits on an integer. Does *not*
* work with floats!
*
* Parameters:
* sig - {Integer}
*
* Returns:
* {Integer} The number, rounded to the specified number of significant digits.
* If null, 0, or negative value passed in, returns 0
*/
Number.prototype.limitSigDigs = function(sig) {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.Number.limitSigDigs'}));
return OpenLayers.Number.limitSigDigs(this, sig);
};
}
/**
* Namespace: OpenLayers.Function
* Contains convenience functions for function manipulation.
*/
OpenLayers.Function = {
/**
* APIFunction: bind
* Bind a function to an object. Method to easily create closures with
* 'this' altered.
*
* Parameters:
* func - {Function} Input function.
* object - {Object} The object to bind to the input function (as this).
*
* Returns:
* {Function} A closure with 'this' set to the passed in object.
*/
bind: function(func, object) {
// create a reference to all arguments past the second one
var args = Array.prototype.slice.apply(arguments, [2]);
return function() {
// Push on any additional arguments from the actual function call.
// These will come after those sent to the bind call.
var newArgs = args.concat(
Array.prototype.slice.apply(arguments, [0])
);
return func.apply(object, newArgs);
};
},
/**
* APIFunction: bindAsEventListener
* Bind a function to an object, and configure it to receive the event
* object as first parameter when called.
*
* Parameters:
* func - {Function} Input function to serve as an event listener.
* object - {Object} A reference to this.
*
* Returns:
* {Function}
*/
bindAsEventListener: function(func, object) {
return function(event) {
return func.call(object, event || window.event);
};
}
};
if (!Function.prototype.bind) {
/**
* APIMethod: Function.bind
* *Deprecated*. Bind a function to an object.
* Method to easily create closures with 'this' altered.
*
* Parameters:
* object - {Object} the this parameter
*
* Returns:
* {Function} A closure with 'this' altered to the first
* argument.
*/
Function.prototype.bind = function() {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.Function.bind'}));
// new function takes the same arguments with this function up front
Array.prototype.unshift.apply(arguments, [this]);
return OpenLayers.Function.bind.apply(null, arguments);
};
}
if (!Function.prototype.bindAsEventListener) {
/**
* APIMethod: Function.bindAsEventListener
* *Deprecated*. Bind a function to an object, and configure it to receive the
* event object as first parameter when called.
*
* Parameters:
* object - {Object} A reference to this.
*
* Returns:
* {Function}
*/
Function.prototype.bindAsEventListener = function(object) {
OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",
{'newMethod':'OpenLayers.Function.bindAsEventListener'}));
return OpenLayers.Function.bindAsEventListener(this, object);
};
}
/**
* Namespace: OpenLayers.Array
* Contains convenience functions for array manipulation.
*/
OpenLayers.Array = {
/**
* APIMethod: filter
* Filter an array. Provides the functionality of the
* Array.prototype.filter extension to the ECMA-262 standard. Where
* available, Array.prototype.filter will be used.
*
* Based on well known example from http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:filter
*
* Parameters:
* array - {Array} The array to be filtered. This array is not mutated.
* Elements added to this array by the callback will not be visited.
* callback - {Function} A function that is called for each element in
* the array. If this function returns true, the element will be
* included in the return. The function will be called with three
* arguments: the element in the array, the index of that element, and
* the array itself. If the optional caller parameter is specified
* the callback will be called with this set to caller.
* caller - {Object} Optional object to be set as this when the callback
* is called.
*
* Returns:
* {Array} An array of elements from the passed in array for which the
* callback returns true.
*/
filter: function(array, callback, caller) {
var selected = [];
if (Array.prototype.filter) {
selected = array.filter(callback, caller);
} else {
var len = array.length;
if (typeof callback != "function") {
throw new TypeError();
}
for(var i=0; i<len; i++) {
if (i in array) {
var val = array[i];
if (callback.call(caller, val, i, array)) {
selected.push(val);
}
}
}
}
return selected;
}
};

View File

@ -1,671 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Bounds
* Instances of this class represent bounding boxes. Data stored as left,
* bottom, right, top floats. All values are initialized to null, however,
* you should make sure you set them before using the bounds for anything.
*
* Possible use case:
* > bounds = new OpenLayers.Bounds();
* > bounds.extend(new OpenLayers.LonLat(4,5));
* > bounds.extend(new OpenLayers.LonLat(5,6));
* > bounds.toBBOX(); // returns 4,5,5,6
*/
OpenLayers.Bounds = OpenLayers.Class({
/**
* Property: left
* {Number} Minimum horizontal coordinate.
*/
left: null,
/**
* Property: bottom
* {Number} Minimum vertical coordinate.
*/
bottom: null,
/**
* Property: right
* {Number} Maximum horizontal coordinate.
*/
right: null,
/**
* Property: top
* {Number} Maximum vertical coordinate.
*/
top: null,
/**
* Property: centerLonLat
* {<OpenLayers.LonLat>} A cached center location. This should not be
* accessed directly. Use <getCenterLonLat> instead.
*/
centerLonLat: null,
/**
* Constructor: OpenLayers.Bounds
* Construct a new bounds object.
*
* Parameters:
* left - {Number} The left bounds of the box. Note that for width
* calculations, this is assumed to be less than the right value.
* bottom - {Number} The bottom bounds of the box. Note that for height
* calculations, this is assumed to be more than the top value.
* right - {Number} The right bounds.
* top - {Number} The top bounds.
*/
initialize: function(left, bottom, right, top) {
if (left != null) {
this.left = OpenLayers.Util.toFloat(left);
}
if (bottom != null) {
this.bottom = OpenLayers.Util.toFloat(bottom);
}
if (right != null) {
this.right = OpenLayers.Util.toFloat(right);
}
if (top != null) {
this.top = OpenLayers.Util.toFloat(top);
}
},
/**
* Method: clone
* Create a cloned instance of this bounds.
*
* Returns:
* {<OpenLayers.Bounds>} A fresh copy of the bounds
*/
clone:function() {
return new OpenLayers.Bounds(this.left, this.bottom,
this.right, this.top);
},
/**
* Method: equals
* Test a two bounds for equivalence.
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
*
* Returns:
* {Boolean} The passed-in bounds object has the same left,
* right, top, bottom components as this. Note that if bounds
* passed in is null, returns false.
*/
equals:function(bounds) {
var equals = false;
if (bounds != null) {
equals = ((this.left == bounds.left) &&
(this.right == bounds.right) &&
(this.top == bounds.top) &&
(this.bottom == bounds.bottom));
}
return equals;
},
/**
* APIMethod: toString
*
* Returns:
* {String} String representation of bounds object.
* (ex.<i>"left-bottom=(5,42) right-top=(10,45)"</i>)
*/
toString:function() {
return ( "left-bottom=(" + this.left + "," + this.bottom + ")"
+ " right-top=(" + this.right + "," + this.top + ")" );
},
/**
* APIMethod: toArray
*
* Returns:
* {Array} array of left, bottom, right, top
*/
toArray: function() {
return [this.left, this.bottom, this.right, this.top];
},
/**
* APIMethod: toBBOX
*
* Parameters:
* decimal - {Integer} How many significant digits in the bbox coords?
* Default is 6
*
* Returns:
* {String} Simple String representation of bounds object.
* (ex. <i>"5,42,10,45"</i>)
*/
toBBOX:function(decimal) {
if (decimal== null) {
decimal = 6;
}
var mult = Math.pow(10, decimal);
var bbox = Math.round(this.left * mult) / mult + "," +
Math.round(this.bottom * mult) / mult + "," +
Math.round(this.right * mult) / mult + "," +
Math.round(this.top * mult) / mult;
return bbox;
},
/**
* APIMethod: toGeometry
* Create a new polygon geometry based on this bounds.
*
* Returns:
* {<OpenLayers.Geometry.Polygon>} A new polygon with the coordinates
* of this bounds.
*/
toGeometry: function() {
return new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(this.left, this.bottom),
new OpenLayers.Geometry.Point(this.right, this.bottom),
new OpenLayers.Geometry.Point(this.right, this.top),
new OpenLayers.Geometry.Point(this.left, this.top)
])
]);
},
/**
* APIMethod: getWidth
*
* Returns:
* {Float} The width of the bounds
*/
getWidth:function() {
return (this.right - this.left);
},
/**
* APIMethod: getHeight
*
* Returns:
* {Float} The height of the bounds (top minus bottom).
*/
getHeight:function() {
return (this.top - this.bottom);
},
/**
* APIMethod: getSize
*
* Returns:
* {<OpenLayers.Size>} The size of the box.
*/
getSize:function() {
return new OpenLayers.Size(this.getWidth(), this.getHeight());
},
/**
* APIMethod: getCenterPixel
*
* Returns:
* {<OpenLayers.Pixel>} The center of the bounds in pixel space.
*/
getCenterPixel:function() {
return new OpenLayers.Pixel( (this.left + this.right) / 2,
(this.bottom + this.top) / 2);
},
/**
* APIMethod: getCenterLonLat
*
* Returns:
* {<OpenLayers.LonLat>} The center of the bounds in map space.
*/
getCenterLonLat:function() {
if(!this.centerLonLat) {
this.centerLonLat = new OpenLayers.LonLat(
(this.left + this.right) / 2, (this.bottom + this.top) / 2
);
}
return this.centerLonLat;
},
/**
* Method: scale
* Scales the bounds around a pixel or lonlat. Note that the new
* bounds may return non-integer properties, even if a pixel
* is passed.
*
* Parameters:
* ratio - {Float}
* origin - {<OpenLayers.Pixel> or <OpenLayers.LonLat>}
* Default is center.
*
* Returns:
* {<OpenLayers.Bound>} A new bounds that is scaled by ratio
* from origin.
*/
scale: function(ratio, origin){
if(origin == null){
origin = this.getCenterLonLat();
}
var bounds = [];
var origx,origy;
// get origin coordinates
if(origin.CLASS_NAME == "OpenLayers.LonLat"){
origx = origin.lon;
origy = origin.lat;
} else {
origx = origin.x;
origy = origin.y;
}
var left = (this.left - origx) * ratio + origx;
var bottom = (this.bottom - origy) * ratio + origy;
var right = (this.right - origx) * ratio + origx;
var top = (this.top - origy) * ratio + origy;
return new OpenLayers.Bounds(left, bottom, right, top);
},
/**
* APIMethod: add
*
* Parameters:
* x - {Float}
* y - {Float}
*
* Returns:
* {<OpenLayers.Bounds>} A new bounds whose coordinates are the same as
* this, but shifted by the passed-in x and y values.
*/
add:function(x, y) {
if ( (x == null) || (y == null) ) {
var msg = OpenLayers.i18n("boundsAddError");
OpenLayers.Console.error(msg);
return null;
}
return new OpenLayers.Bounds(this.left + x, this.bottom + y,
this.right + x, this.top + y);
},
/**
* APIMethod: extend
* Extend the bounds to include the point, lonlat, or bounds specified.
* Note, this function assumes that left < right and bottom < top.
*
* Parameters:
* object - {Object} Can be LonLat, Point, or Bounds
*/
extend:function(object) {
var bounds = null;
if (object) {
// clear cached center location
switch(object.CLASS_NAME) {
case "OpenLayers.LonLat":
bounds = new OpenLayers.Bounds(object.lon, object.lat,
object.lon, object.lat);
break;
case "OpenLayers.Geometry.Point":
bounds = new OpenLayers.Bounds(object.x, object.y,
object.x, object.y);
break;
case "OpenLayers.Bounds":
bounds = object;
break;
}
if (bounds) {
this.centerLonLat = null;
if ( (this.left == null) || (bounds.left < this.left)) {
this.left = bounds.left;
}
if ( (this.bottom == null) || (bounds.bottom < this.bottom) ) {
this.bottom = bounds.bottom;
}
if ( (this.right == null) || (bounds.right > this.right) ) {
this.right = bounds.right;
}
if ( (this.top == null) || (bounds.top > this.top) ) {
this.top = bounds.top;
}
}
}
},
/**
* APIMethod: containsLonLat
*
* Parameters:
* ll - {<OpenLayers.LonLat>}
* inclusive - {Boolean} Whether or not to include the border.
* Default is true.
*
* Returns:
* {Boolean} The passed-in lonlat is within this bounds.
*/
containsLonLat:function(ll, inclusive) {
return this.contains(ll.lon, ll.lat, inclusive);
},
/**
* APIMethod: containsPixel
*
* Parameters:
* px - {<OpenLayers.Pixel>}
* inclusive - {Boolean} Whether or not to include the border. Default is
* true.
*
* Returns:
* {Boolean} The passed-in pixel is within this bounds.
*/
containsPixel:function(px, inclusive) {
return this.contains(px.x, px.y, inclusive);
},
/**
* APIMethod: contains
*
* Parameters:
* x - {Float}
* y - {Float}
* inclusive - {Boolean} Whether or not to include the border. Default is
* true.
*
* Returns:
* {Boolean} Whether or not the passed-in coordinates are within this
* bounds.
*/
contains:function(x, y, inclusive) {
//set default
if (inclusive == null) {
inclusive = true;
}
if (x == null || y == null) {
return false;
}
x = OpenLayers.Util.toFloat(x);
y = OpenLayers.Util.toFloat(y);
var contains = false;
if (inclusive) {
contains = ((x >= this.left) && (x <= this.right) &&
(y >= this.bottom) && (y <= this.top));
} else {
contains = ((x > this.left) && (x < this.right) &&
(y > this.bottom) && (y < this.top));
}
return contains;
},
/**
* APIMethod: intersectsBounds
* Determine whether the target bounds intersects this bounds. Bounds are
* considered intersecting if any of their edges intersect or if one
* bounds contains the other.
*
* Parameters:
* bounds - {<OpenLayers.Bounds>} The target bounds.
* inclusive - {Boolean} Treat coincident borders as intersecting. Default
* is true. If false, bounds that do not overlap but only touch at the
* border will not be considered as intersecting.
*
* Returns:
* {Boolean} The passed-in bounds object intersects this bounds.
*/
intersectsBounds:function(bounds, inclusive) {
if (inclusive == null) {
inclusive = true;
}
var intersects = false;
var mightTouch = (
this.left == bounds.right ||
this.right == bounds.left ||
this.top == bounds.bottom ||
this.bottom == bounds.top
);
// if the two bounds only touch at an edge, and inclusive is false,
// then the bounds don't *really* intersect.
if (inclusive || !mightTouch) {
// otherwise, if one of the boundaries even partially contains another,
// inclusive of the edges, then they do intersect.
var inBottom = (
((bounds.bottom >= this.bottom) && (bounds.bottom <= this.top)) ||
((this.bottom >= bounds.bottom) && (this.bottom <= bounds.top))
);
var inTop = (
((bounds.top >= this.bottom) && (bounds.top <= this.top)) ||
((this.top > bounds.bottom) && (this.top < bounds.top))
);
var inLeft = (
((bounds.left >= this.left) && (bounds.left <= this.right)) ||
((this.left >= bounds.left) && (this.left <= bounds.right))
);
var inRight = (
((bounds.right >= this.left) && (bounds.right <= this.right)) ||
((this.right >= bounds.left) && (this.right <= bounds.right))
);
intersects = ((inBottom || inTop) && (inLeft || inRight));
}
return intersects;
},
/**
* APIMethod: containsBounds
* Determine whether the target bounds is contained within this bounds.
*
* bounds - {<OpenLayers.Bounds>} The target bounds.
* partial - {Boolean} If any of the target corners is within this bounds
* consider the bounds contained. Default is false. If true, the
* entire target bounds must be contained within this bounds.
* inclusive - {Boolean} Treat shared edges as contained. Default is
* true.
*
* Returns:
* {Boolean} The passed-in bounds object is contained within this bounds.
*/
containsBounds:function(bounds, partial, inclusive) {
if (partial == null) {
partial = false;
}
if (inclusive == null) {
inclusive = true;
}
var bottomLeft = this.contains(bounds.left, bounds.bottom, inclusive);
var bottomRight = this.contains(bounds.right, bounds.bottom, inclusive);
var topLeft = this.contains(bounds.left, bounds.top, inclusive);
var topRight = this.contains(bounds.right, bounds.top, inclusive);
return (partial) ? (bottomLeft || bottomRight || topLeft || topRight)
: (bottomLeft && bottomRight && topLeft && topRight);
},
/**
* APIMethod: determineQuadrant
*
* Parameters:
* lonlat - {<OpenLayers.LonLat>}
*
* Returns:
* {String} The quadrant ("br" "tr" "tl" "bl") of the bounds in which the
* coordinate lies.
*/
determineQuadrant: function(lonlat) {
var quadrant = "";
var center = this.getCenterLonLat();
quadrant += (lonlat.lat < center.lat) ? "b" : "t";
quadrant += (lonlat.lon < center.lon) ? "l" : "r";
return quadrant;
},
/**
* APIMethod: transform
* Transform the Bounds object from source to dest.
*
* Parameters:
* source - {<OpenLayers.Projection>} Source projection.
* dest - {<OpenLayers.Projection>} Destination projection.
*
* Returns:
* {<OpenLayers.Bounds>} Itself, for use in chaining operations.
*/
transform: function(source, dest) {
// clear cached center location
this.centerLonLat = null;
var ll = OpenLayers.Projection.transform(
{'x': this.left, 'y': this.bottom}, source, dest);
var lr = OpenLayers.Projection.transform(
{'x': this.right, 'y': this.bottom}, source, dest);
var ul = OpenLayers.Projection.transform(
{'x': this.left, 'y': this.top}, source, dest);
var ur = OpenLayers.Projection.transform(
{'x': this.right, 'y': this.top}, source, dest);
this.left = Math.min(ll.x, ul.x);
this.bottom = Math.min(ll.y, lr.y);
this.right = Math.max(lr.x, ur.x);
this.top = Math.max(ul.y, ur.y);
return this;
},
/**
* APIMethod: wrapDateLine
*
* Parameters:
* maxExtent - {<OpenLayers.Bounds>}
* options - {Object} Some possible options are:
* leftTolerance - {float} Allow for a margin of error
* with the 'left' value of this
* bound.
* Default is 0.
* rightTolerance - {float} Allow for a margin of error
* with the 'right' value of
* this bound.
* Default is 0.
*
* Returns:
* {<OpenLayers.Bounds>} A copy of this bounds, but wrapped around the
* "dateline" (as specified by the borders of
* maxExtent). Note that this function only returns
* a different bounds value if this bounds is
* *entirely* outside of the maxExtent. If this
* bounds straddles the dateline (is part in/part
* out of maxExtent), the returned bounds will be
* merely a copy of this one.
*/
wrapDateLine: function(maxExtent, options) {
options = options || {};
var leftTolerance = options.leftTolerance || 0;
var rightTolerance = options.rightTolerance || 0;
var newBounds = this.clone();
if (maxExtent) {
//shift right?
while ( newBounds.left < maxExtent.left &&
(newBounds.right - rightTolerance) <= maxExtent.left ) {
newBounds = newBounds.add(maxExtent.getWidth(), 0);
}
//shift left?
while ( (newBounds.left + leftTolerance) >= maxExtent.right &&
newBounds.right > maxExtent.right ) {
newBounds = newBounds.add(-maxExtent.getWidth(), 0);
}
}
return newBounds;
},
CLASS_NAME: "OpenLayers.Bounds"
});
/**
* APIFunction: fromString
* Alternative constructor that builds a new OpenLayers.Bounds from a
* parameter string
*
* Parameters:
* str - {String}Comma-separated bounds string. (ex. <i>"5,42,10,45"</i>)
*
* Returns:
* {<OpenLayers.Bounds>} New bounds object built from the
* passed-in String.
*/
OpenLayers.Bounds.fromString = function(str) {
var bounds = str.split(",");
return OpenLayers.Bounds.fromArray(bounds);
};
/**
* APIFunction: fromArray
* Alternative constructor that builds a new OpenLayers.Bounds
* from an array
*
* Parameters:
* bbox - {Array(Float)} Array of bounds values (ex. <i>[5,42,10,45]</i>)
*
* Returns:
* {<OpenLayers.Bounds>} New bounds object built from the passed-in Array.
*/
OpenLayers.Bounds.fromArray = function(bbox) {
return new OpenLayers.Bounds(parseFloat(bbox[0]),
parseFloat(bbox[1]),
parseFloat(bbox[2]),
parseFloat(bbox[3]));
};
/**
* APIFunction: fromSize
* Alternative constructor that builds a new OpenLayers.Bounds
* from a size
*
* Parameters:
* size - {<OpenLayers.Size>}
*
* Returns:
* {<OpenLayers.Bounds>} New bounds object built from the passed-in size.
*/
OpenLayers.Bounds.fromSize = function(size) {
return new OpenLayers.Bounds(0,
size.h,
size.w,
0);
};
/**
* Function: oppositeQuadrant
* Get the opposite quadrant for a given quadrant string.
*
* Parameters:
* quadrant - {String} two character quadrant shortstring
*
* Returns:
* {String} The opposing quadrant ("br" "tr" "tl" "bl"). For Example, if
* you pass in "bl" it returns "tr", if you pass in "br" it
* returns "tl", etc.
*/
OpenLayers.Bounds.oppositeQuadrant = function(quadrant) {
var opp = "";
opp += (quadrant.charAt(0) == 't') ? 'b' : 't';
opp += (quadrant.charAt(1) == 'l') ? 'r' : 'l';
return opp;
};

View File

@ -1,114 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Constructor: OpenLayers.Class
* Base class used to construct all other classes. Includes support for
* multiple inheritance.
*
* This constructor is new in OpenLayers 2.5. At OpenLayers 3.0, the old
* syntax for creating classes and dealing with inheritance
* will be removed.
*
* To create a new OpenLayers-style class, use the following syntax:
* > var MyClass = OpenLayers.Class(prototype);
*
* To create a new OpenLayers-style class with multiple inheritance, use the
* following syntax:
* > var MyClass = OpenLayers.Class(Class1, Class2, prototype);
* Note that instanceof reflection will only reveil Class1 as superclass.
* Class2 ff are mixins.
*
*/
OpenLayers.Class = function() {
var Class = function() {
/**
* This following condition can be removed at 3.0 - this is only for
* backwards compatibility while the Class.inherit method is still
* in use. So at 3.0, the following three lines would be replaced with
* simply:
* this.initialize.apply(this, arguments);
*/
if (arguments && arguments[0] != OpenLayers.Class.isPrototype) {
this.initialize.apply(this, arguments);
}
};
var extended = {};
var parent, initialize;
for(var i=0, len=arguments.length; i<len; ++i) {
if(typeof arguments[i] == "function") {
// make the class passed as the first argument the superclass
if(i == 0 && len > 1) {
initialize = arguments[i].prototype.initialize;
// replace the initialize method with an empty function,
// because we do not want to create a real instance here
arguments[i].prototype.initialize = function() {};
// the line below makes sure that the new class has a
// superclass
extended = new arguments[i];
// restore the original initialize method
if(initialize === undefined) {
delete arguments[i].prototype.initialize;
} else {
arguments[i].prototype.initialize = initialize;
}
}
// get the prototype of the superclass
parent = arguments[i].prototype;
} else {
// in this case we're extending with the prototype
parent = arguments[i];
}
OpenLayers.Util.extend(extended, parent);
}
Class.prototype = extended;
return Class;
};
/**
* Property: isPrototype
* *Deprecated*. This is no longer needed and will be removed at 3.0.
*/
OpenLayers.Class.isPrototype = function () {};
/**
* APIFunction: OpenLayers.create
* *Deprecated*. Old method to create an OpenLayers style class. Use the
* <OpenLayers.Class> constructor instead.
*
* Returns:
* An OpenLayers class
*/
OpenLayers.Class.create = function() {
return function() {
if (arguments && arguments[0] != OpenLayers.Class.isPrototype) {
this.initialize.apply(this, arguments);
}
};
};
/**
* APIFunction: inherit
* *Deprecated*. Old method to inherit from one or more OpenLayers style
* classes. Use the <OpenLayers.Class> constructor instead.
*
* Parameters:
* class - One or more classes can be provided as arguments
*
* Returns:
* An object prototype
*/
OpenLayers.Class.inherit = function () {
var superClass = arguments[0];
var proto = new superClass(OpenLayers.Class.isPrototype);
for (var i=1, len=arguments.length; i<len; i++) {
if (typeof arguments[i] == "function") {
var mixin = arguments[i];
arguments[i] = new mixin(OpenLayers.Class.isPrototype);
}
OpenLayers.Util.extend(proto, arguments[i]);
}
return proto;
};

View File

@ -1,244 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Namespace: OpenLayers.Element
*/
OpenLayers.Element = {
/**
* APIFunction: visible
*
* Parameters:
* element - {DOMElement}
*
* Returns:
* {Boolean} Is the element visible?
*/
visible: function(element) {
return OpenLayers.Util.getElement(element).style.display != 'none';
},
/**
* APIFunction: toggle
* Toggle the visibility of element(s) passed in
*
* Parameters:
* element - {DOMElement} Actually user can pass any number of elements
*/
toggle: function() {
for (var i=0, len=arguments.length; i<len; i++) {
var element = OpenLayers.Util.getElement(arguments[i]);
var display = OpenLayers.Element.visible(element) ? 'hide'
: 'show';
OpenLayers.Element[display](element);
}
},
/**
* APIFunction: hide
* Hide element(s) passed in
*
* Parameters:
* element - {DOMElement} Actually user can pass any number of elements
*/
hide: function() {
for (var i=0, len=arguments.length; i<len; i++) {
var element = OpenLayers.Util.getElement(arguments[i]);
element.style.display = 'none';
}
},
/**
* APIFunction: show
* Show element(s) passed in
*
* Parameters:
* element - {DOMElement} Actually user can pass any number of elements
*/
show: function() {
for (var i=0, len=arguments.length; i<len; i++) {
var element = OpenLayers.Util.getElement(arguments[i]);
element.style.display = '';
}
},
/**
* APIFunction: remove
* Remove the specified element from the DOM.
*
* Parameters:
* element - {DOMElement}
*/
remove: function(element) {
element = OpenLayers.Util.getElement(element);
element.parentNode.removeChild(element);
},
/**
* APIFunction: getHeight
*
* Parameters:
* element - {DOMElement}
*
* Returns:
* {Integer} The offset height of the element passed in
*/
getHeight: function(element) {
element = OpenLayers.Util.getElement(element);
return element.offsetHeight;
},
/**
* APIFunction: getDimensions
*
* Parameters:
* element - {DOMElement}
*
* Returns:
* {Object} Object with 'width' and 'height' properties which are the
* dimensions of the element passed in.
*/
getDimensions: function(element) {
element = OpenLayers.Util.getElement(element);
if (OpenLayers.Element.getStyle(element, 'display') != 'none') {
return {width: element.offsetWidth, height: element.offsetHeight};
}
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = '';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = 'none';
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
/**
* Function: hasClass
* Tests if an element has the given CSS class name.
*
* Parameters:
* element - {DOMElement} A DOM element node.
* name - {String} The CSS class name to search for.
*
* Returns:
* {Boolean} The element has the given class name.
*/
hasClass: function(element, name) {
var names = element.className;
return (!!names && new RegExp("(^|\\s)" + name + "(\\s|$)").test(names));
},
/**
* Function: addClass
* Add a CSS class name to an element. Safe where element already has
* the class name.
*
* Parameters:
* element - {DOMElement} A DOM element node.
* name - {String} The CSS class name to add.
*
* Returns:
* {DOMElement} The element.
*/
addClass: function(element, name) {
if(!OpenLayers.Element.hasClass(element, name)) {
element.className += (element.className ? " " : "") + name;
}
return element;
},
/**
* Function: removeClass
* Remove a CSS class name from an element. Safe where element does not
* have the class name.
*
* Parameters:
* element - {DOMElement} A DOM element node.
* name - {String} The CSS class name to remove.
*
* Returns:
* {DOMElement} The element.
*/
removeClass: function(element, name) {
var names = element.className;
if(names) {
element.className = OpenLayers.String.trim(
names.replace(
new RegExp("(^|\\s+)" + name + "(\\s+|$)"), " "
)
);
}
return element;
},
/**
* Function: toggleClass
* Remove a CSS class name from an element if it exists. Add the class name
* if it doesn't exist.
*
* Parameters:
* element - {DOMElement} A DOM element node.
* name - {String} The CSS class name to toggle.
*
* Returns:
* {DOMElement} The element.
*/
toggleClass: function(element, name) {
if(OpenLayers.Element.hasClass(element, name)) {
OpenLayers.Element.removeClass(element, name);
} else {
OpenLayers.Element.addClass(element, name);
}
return element;
},
/**
* APIFunction: getStyle
*
* Parameters:
* element - {DOMElement}
* style - {?}
*
* Returns:
* {?}
*/
getStyle: function(element, style) {
element = OpenLayers.Util.getElement(element);
var value = null;
if (element && element.style) {
value = element.style[OpenLayers.String.camelize(style)];
if (!value) {
if (document.defaultView &&
document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[OpenLayers.String.camelize(style)];
}
}
var positions = ['left', 'top', 'right', 'bottom'];
if (window.opera &&
(OpenLayers.Util.indexOf(positions,style) != -1) &&
(OpenLayers.Element.getStyle(element, 'position') == 'static')) {
value = 'auto';
}
}
return value == 'auto' ? null : value;
}
};

View File

@ -1,189 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.LonLat
* This class represents a longitude and latitude pair
*/
OpenLayers.LonLat = OpenLayers.Class({
/**
* APIProperty: lon
* {Float} The x-axis coodinate in map units
*/
lon: 0.0,
/**
* APIProperty: lat
* {Float} The y-axis coordinate in map units
*/
lat: 0.0,
/**
* Constructor: OpenLayers.LonLat
* Create a new map location.
*
* Parameters:
* lon - {Number} The x-axis coordinate in map units. If your map is in
* a geographic projection, this will be the Longitude. Otherwise,
* it will be the x coordinate of the map location in your map units.
* lat - {Number} The y-axis coordinate in map units. If your map is in
* a geographic projection, this will be the Latitude. Otherwise,
* it will be the y coordinate of the map location in your map units.
*/
initialize: function(lon, lat) {
this.lon = OpenLayers.Util.toFloat(lon);
this.lat = OpenLayers.Util.toFloat(lat);
},
/**
* Method: toString
* Return a readable string version of the lonlat
*
* Returns:
* {String} String representation of OpenLayers.LonLat object.
* (ex. <i>"lon=5,lat=42"</i>)
*/
toString:function() {
return ("lon=" + this.lon + ",lat=" + this.lat);
},
/**
* APIMethod: toShortString
*
* Returns:
* {String} Shortened String representation of OpenLayers.LonLat object.
* (ex. <i>"5, 42"</i>)
*/
toShortString:function() {
return (this.lon + ", " + this.lat);
},
/**
* APIMethod: clone
*
* Returns:
* {<OpenLayers.LonLat>} New OpenLayers.LonLat object with the same lon
* and lat values
*/
clone:function() {
return new OpenLayers.LonLat(this.lon, this.lat);
},
/**
* APIMethod: add
*
* Parameters:
* lon - {Float}
* lat - {Float}
*
* Returns:
* {<OpenLayers.LonLat>} A new OpenLayers.LonLat object with the lon and
* lat passed-in added to this's.
*/
add:function(lon, lat) {
if ( (lon == null) || (lat == null) ) {
var msg = OpenLayers.i18n("lonlatAddError");
OpenLayers.Console.error(msg);
return null;
}
return new OpenLayers.LonLat(this.lon + lon, this.lat + lat);
},
/**
* APIMethod: equals
*
* Parameters:
* ll - {<OpenLayers.LonLat>}
*
* Returns:
* {Boolean} Boolean value indicating whether the passed-in
* <OpenLayers.LonLat> object has the same lon and lat
* components as this.
* Note: if ll passed in is null, returns false
*/
equals:function(ll) {
var equals = false;
if (ll != null) {
equals = ((this.lon == ll.lon && this.lat == ll.lat) ||
(isNaN(this.lon) && isNaN(this.lat) && isNaN(ll.lon) && isNaN(ll.lat)));
}
return equals;
},
/**
* APIMethod: transform
* Transform the LonLat object from source to dest. This transformation is
* *in place*: if you want a *new* lonlat, use .clone() first.
*
* Parameters:
* source - {<OpenLayers.Projection>} Source projection.
* dest - {<OpenLayers.Projection>} Destination projection.
*
* Returns:
* {<OpenLayers.LonLat>} Itself, for use in chaining operations.
*/
transform: function(source, dest) {
var point = OpenLayers.Projection.transform(
{'x': this.lon, 'y': this.lat}, source, dest);
this.lon = point.x;
this.lat = point.y;
return this;
},
/**
* APIMethod: wrapDateLine
*
* Parameters:
* maxExtent - {<OpenLayers.Bounds>}
*
* Returns:
* {<OpenLayers.LonLat>} A copy of this lonlat, but wrapped around the
* "dateline" (as specified by the borders of
* maxExtent)
*/
wrapDateLine: function(maxExtent) {
var newLonLat = this.clone();
if (maxExtent) {
//shift right?
while (newLonLat.lon < maxExtent.left) {
newLonLat.lon += maxExtent.getWidth();
}
//shift left?
while (newLonLat.lon > maxExtent.right) {
newLonLat.lon -= maxExtent.getWidth();
}
}
return newLonLat;
},
CLASS_NAME: "OpenLayers.LonLat"
});
/**
* Function: fromString
* Alternative constructor that builds a new <OpenLayers.LonLat> from a
* parameter string
*
* Parameters:
* str - {String} Comma-separated Lon,Lat coordinate string.
* (ex. <i>"5,40"</i>)
*
* Returns:
* {<OpenLayers.LonLat>} New <OpenLayers.LonLat> object built from the
* passed-in String.
*/
OpenLayers.LonLat.fromString = function(str) {
var pair = str.split(",");
return new OpenLayers.LonLat(parseFloat(pair[0]),
parseFloat(pair[1]));
};

View File

@ -1,124 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Pixel
* This class represents a screen coordinate, in x and y coordinates
*/
OpenLayers.Pixel = OpenLayers.Class({
/**
* APIProperty: x
* {Number} The x coordinate
*/
x: 0.0,
/**
* APIProperty: y
* {Number} The y coordinate
*/
y: 0.0,
/**
* Constructor: OpenLayers.Pixel
* Create a new OpenLayers.Pixel instance
*
* Parameters:
* x - {Number} The x coordinate
* y - {Number} The y coordinate
*
* Returns:
* An instance of OpenLayers.Pixel
*/
initialize: function(x, y) {
this.x = parseFloat(x);
this.y = parseFloat(y);
},
/**
* Method: toString
* Cast this object into a string
*
* Returns:
* {String} The string representation of Pixel. ex: "x=200.4,y=242.2"
*/
toString:function() {
return ("x=" + this.x + ",y=" + this.y);
},
/**
* APIMethod: clone
* Return a clone of this pixel object
*
* Returns:
* {<OpenLayers.Pixel>} A clone pixel
*/
clone:function() {
return new OpenLayers.Pixel(this.x, this.y);
},
/**
* APIMethod: equals
* Determine whether one pixel is equivalent to another
*
* Parameters:
* px - {<OpenLayers.Pixel>}
*
* Returns:
* {Boolean} The point passed in as parameter is equal to this. Note that
* if px passed in is null, returns false.
*/
equals:function(px) {
var equals = false;
if (px != null) {
equals = ((this.x == px.x && this.y == px.y) ||
(isNaN(this.x) && isNaN(this.y) && isNaN(px.x) && isNaN(px.y)));
}
return equals;
},
/**
* APIMethod: add
*
* Parameters:
* x - {Integer}
* y - {Integer}
*
* Returns:
* {<OpenLayers.Pixel>} A new Pixel with this pixel's x&y augmented by the
* values passed in.
*/
add:function(x, y) {
if ( (x == null) || (y == null) ) {
var msg = OpenLayers.i18n("pixelAddError");
OpenLayers.Console.error(msg);
return null;
}
return new OpenLayers.Pixel(this.x + x, this.y + y);
},
/**
* APIMethod: offset
*
* Parameters
* px - {<OpenLayers.Pixel>}
*
* Returns:
* {<OpenLayers.Pixel>} A new Pixel with this pixel's x&y augmented by the
* x&y values of the pixel passed in.
*/
offset:function(px) {
var newPx = this.clone();
if (px) {
newPx = this.add(px.x, px.y);
}
return newPx;
},
CLASS_NAME: "OpenLayers.Pixel"
});

View File

@ -1,84 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Class: OpenLayers.Size
* Instances of this class represent a width/height pair
*/
OpenLayers.Size = OpenLayers.Class({
/**
* APIProperty: w
* {Number} width
*/
w: 0.0,
/**
* APIProperty: h
* {Number} height
*/
h: 0.0,
/**
* Constructor: OpenLayers.Size
* Create an instance of OpenLayers.Size
*
* Parameters:
* w - {Number} width
* h - {Number} height
*/
initialize: function(w, h) {
this.w = parseFloat(w);
this.h = parseFloat(h);
},
/**
* Method: toString
* Return the string representation of a size object
*
* Returns:
* {String} The string representation of OpenLayers.Size object.
* (ex. <i>"w=55,h=66"</i>)
*/
toString:function() {
return ("w=" + this.w + ",h=" + this.h);
},
/**
* APIMethod: clone
* Create a clone of this size object
*
* Returns:
* {<OpenLayers.Size>} A new OpenLayers.Size object with the same w and h
* values
*/
clone:function() {
return new OpenLayers.Size(this.w, this.h);
},
/**
*
* APIMethod: equals
* Determine where this size is equal to another
*
* Parameters:
* sz - {<OpenLayers.Size>}
*
* Returns:
* {Boolean} The passed in size has the same h and w properties as this one.
* Note that if sz passed in is null, returns false.
*
*/
equals:function(sz) {
var equals = false;
if (sz != null) {
equals = ((this.w == sz.w && this.h == sz.h) ||
(isNaN(this.w) && isNaN(this.h) && isNaN(sz.w) && isNaN(sz.h)));
}
return equals;
},
CLASS_NAME: "OpenLayers.Size"
});

View File

@ -1,245 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Namespace: OpenLayers.Console
* The OpenLayers.Console namespace is used for debugging and error logging.
* If the Firebug Lite (../Firebug/firebug.js) is included before this script,
* calls to OpenLayers.Console methods will get redirected to window.console.
* This makes use of the Firebug extension where available and allows for
* cross-browser debugging Firebug style.
*
* Note:
* Note that behavior will differ with the Firebug extention and Firebug Lite.
* Most notably, the Firebug Lite console does not currently allow for
* hyperlinks to code or for clicking on object to explore their properties.
*
*/
OpenLayers.Console = {
/**
* Create empty functions for all console methods. The real value of these
* properties will be set if Firebug Lite (../Firebug/firebug.js script) is
* included. We explicitly require the Firebug Lite script to trigger
* functionality of the OpenLayers.Console methods.
*/
/**
* APIFunction: log
* Log an object in the console. The Firebug Lite console logs string
* representation of objects. Given multiple arguments, they will
* be cast to strings and logged with a space delimiter. If the first
* argument is a string with printf-like formatting, subsequent arguments
* will be used in string substitution. Any additional arguments (beyond
* the number substituted in a format string) will be appended in a space-
* delimited line.
*
* Parameters:
* object - {Object}
*/
log: function() {},
/**
* APIFunction: debug
* Writes a message to the console, including a hyperlink to the line
* where it was called.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
debug: function() {},
/**
* APIFunction: info
* Writes a message to the console with the visual "info" icon and color
* coding and a hyperlink to the line where it was called.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
info: function() {},
/**
* APIFunction: warn
* Writes a message to the console with the visual "warning" icon and
* color coding and a hyperlink to the line where it was called.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
warn: function() {},
/**
* APIFunction: error
* Writes a message to the console with the visual "error" icon and color
* coding and a hyperlink to the line where it was called.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
error: function() {},
/**
* APIFunction: userError
* A single interface for showing error messages to the user. The default
* behavior is a Javascript alert, though this can be overridden by
* reassigning OpenLayers.Console.userError to a different function.
*
* Expects a single error message
*
* Parameters:
* object - {Object}
*/
userError: function(error) {
alert(error);
},
/**
* APIFunction: assert
* Tests that an expression is true. If not, it will write a message to
* the console and throw an exception.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
assert: function() {},
/**
* APIFunction: dir
* Prints an interactive listing of all properties of the object. This
* looks identical to the view that you would see in the DOM tab.
*
* Parameters:
* object - {Object}
*/
dir: function() {},
/**
* APIFunction: dirxml
* Prints the XML source tree of an HTML or XML element. This looks
* identical to the view that you would see in the HTML tab. You can click
* on any node to inspect it in the HTML tab.
*
* Parameters:
* object - {Object}
*/
dirxml: function() {},
/**
* APIFunction: trace
* Prints an interactive stack trace of JavaScript execution at the point
* where it is called. The stack trace details the functions on the stack,
* as well as the values that were passed as arguments to each function.
* You can click each function to take you to its source in the Script tab,
* and click each argument value to inspect it in the DOM or HTML tabs.
*
*/
trace: function() {},
/**
* APIFunction: group
* Writes a message to the console and opens a nested block to indent all
* future messages sent to the console. Call OpenLayers.Console.groupEnd()
* to close the block.
*
* May be called with multiple arguments as with OpenLayers.Console.log().
*
* Parameters:
* object - {Object}
*/
group: function() {},
/**
* APIFunction: groupEnd
* Closes the most recently opened block created by a call to
* OpenLayers.Console.group
*/
groupEnd: function() {},
/**
* APIFunction: time
* Creates a new timer under the given name. Call
* OpenLayers.Console.timeEnd(name)
* with the same name to stop the timer and print the time elapsed.
*
* Parameters:
* name - {String}
*/
time: function() {},
/**
* APIFunction: timeEnd
* Stops a timer created by a call to OpenLayers.Console.time(name) and
* writes the time elapsed.
*
* Parameters:
* name - {String}
*/
timeEnd: function() {},
/**
* APIFunction: profile
* Turns on the JavaScript profiler. The optional argument title would
* contain the text to be printed in the header of the profile report.
*
* This function is not currently implemented in Firebug Lite.
*
* Parameters:
* title - {String} Optional title for the profiler
*/
profile: function() {},
/**
* APIFunction: profileEnd
* Turns off the JavaScript profiler and prints its report.
*
* This function is not currently implemented in Firebug Lite.
*/
profileEnd: function() {},
/**
* APIFunction: count
* Writes the number of times that the line of code where count was called
* was executed. The optional argument title will print a message in
* addition to the number of the count.
*
* This function is not currently implemented in Firebug Lite.
*
* Parameters:
* title - {String} Optional title to be printed with count
*/
count: function() {},
CLASS_NAME: "OpenLayers.Console"
};
/**
* Execute an anonymous function to extend the OpenLayers.Console namespace
* if the firebug.js script is included. This closure is used so that the
* "scripts" and "i" variables don't pollute the global namespace.
*/
(function() {
/**
* If Firebug Lite is included (before this script), re-route all
* OpenLayers.Console calls to the console object.
*/
var scripts = document.getElementsByTagName("script");
for(var i=0, len=scripts.length; i<len; ++i) {
if(scripts[i].src.indexOf("firebug.js") != -1) {
if(console) {
OpenLayers.Util.extend(OpenLayers.Console, console);
break;
}
}
}
})();

View File

@ -1,349 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Control
* Controls affect the display or behavior of the map. They allow everything
* from panning and zooming to displaying a scale indicator. Controls by
* default are added to the map they are contained within however it is
* possible to add a control to an external div by passing the div in the
* options parameter.
*
* Example:
* The following example shows how to add many of the common controls
* to a map.
*
* > var map = new OpenLayers.Map('map', { controls: [] });
* >
* > map.addControl(new OpenLayers.Control.PanZoomBar());
* > map.addControl(new OpenLayers.Control.MouseToolbar());
* > map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false}));
* > map.addControl(new OpenLayers.Control.Permalink());
* > map.addControl(new OpenLayers.Control.Permalink('permalink'));
* > map.addControl(new OpenLayers.Control.MousePosition());
* > map.addControl(new OpenLayers.Control.OverviewMap());
* > map.addControl(new OpenLayers.Control.KeyboardDefaults());
*
* The next code fragment is a quick example of how to intercept
* shift-mouse click to display the extent of the bounding box
* dragged out by the user. Usually controls are not created
* in exactly this manner. See the source for a more complete
* example:
*
* > var control = new OpenLayers.Control();
* > OpenLayers.Util.extend(control, {
* > draw: function () {
* > // this Handler.Box will intercept the shift-mousedown
* > // before Control.MouseDefault gets to see it
* > this.box = new OpenLayers.Handler.Box( control,
* > {"done": this.notice},
* > {keyMask: OpenLayers.Handler.MOD_SHIFT});
* > this.box.activate();
* > },
* >
* > notice: function (bounds) {
* > OpenLayers.Console.userError(bounds);
* > }
* > });
* > map.addControl(control);
*
*/
OpenLayers.Control = OpenLayers.Class({
/**
* Property: id
* {String}
*/
id: null,
/**
* Property: map
* {<OpenLayers.Map>} this gets set in the addControl() function in
* OpenLayers.Map
*/
map: null,
/**
* Property: div
* {DOMElement}
*/
div: null,
/**
* Property: type
* {OpenLayers.Control.TYPES} Controls can have a 'type'. The type
* determines the type of interactions which are possible with them when
* they are placed into a toolbar.
*/
type: null,
/**
* Property: allowSelection
* {Boolean} By deafault, controls do not allow selection, because
* it may interfere with map dragging. If this is true, OpenLayers
* will not prevent selection of the control.
* Default is false.
*/
allowSelection: false,
/**
* Property: displayClass
* {string} This property is used for CSS related to the drawing of the
* Control.
*/
displayClass: "",
/**
* Property: title
* {string} This property is used for showing a tooltip over the
* Control.
*/
title: "",
/**
* Property: active
* {Boolean} The control is active.
*/
active: null,
/**
* Property: handler
* {<OpenLayers.Handler>} null
*/
handler: null,
/**
* APIProperty: eventListeners
* {Object} If set as an option at construction, the eventListeners
* object will be registered with <OpenLayers.Events.on>. Object
* structure must be a listeners object as shown in the example for
* the events.on method.
*/
eventListeners: null,
/**
* Property: events
* {<OpenLayers.Events>} Events instance for triggering control specific
* events.
*/
events: null,
/**
* Constant: EVENT_TYPES
* {Array(String)} Supported application event types. Register a listener
* for a particular event with the following syntax:
* (code)
* control.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 control.events.object (a reference
* to the control).
* element - {DOMElement} A reference to control.events.element (which
* will be null unless documented otherwise).
*
* Supported map event types:
* activate - Triggered when activated.
* deactivate - Triggered when deactivated.
*/
EVENT_TYPES: ["activate", "deactivate"],
/**
* Constructor: OpenLayers.Control
* Create an OpenLayers Control. The options passed as a parameter
* directly extend the control. For example passing the following:
*
* > var control = new OpenLayers.Control({div: myDiv});
*
* Overrides the default div attribute value of null.
*
* Parameters:
* options - {Object}
*/
initialize: function (options) {
// We do this before the extend so that instances can override
// className in options.
this.displayClass =
this.CLASS_NAME.replace("OpenLayers.", "ol").replace(/\./g, "");
OpenLayers.Util.extend(this, options);
this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES);
if(this.eventListeners instanceof Object) {
this.events.on(this.eventListeners);
}
if (this.id == null) {
this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
}
},
/**
* Method: destroy
* The destroy method is used to perform any clean up before the control
* is dereferenced. Typically this is where event listeners are removed
* to prevent memory leaks.
*/
destroy: function () {
if(this.events) {
if(this.eventListeners) {
this.events.un(this.eventListeners);
}
this.events.destroy();
this.events = null;
}
this.eventListeners = null;
// eliminate circular references
if (this.handler) {
this.handler.destroy();
this.handler = null;
}
if(this.handlers) {
for(var key in this.handlers) {
if(this.handlers.hasOwnProperty(key) &&
typeof this.handlers[key].destroy == "function") {
this.handlers[key].destroy();
}
}
this.handlers = null;
}
if (this.map) {
this.map.removeControl(this);
this.map = null;
}
},
/**
* Method: setMap
* Set the map property for the control. This is done through an accessor
* so that subclasses can override this and take special action once
* they have their map variable set.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
this.map = map;
if (this.handler) {
this.handler.setMap(map);
}
},
/**
* Method: draw
* The draw method is called when the control is ready to be displayed
* on the page. If a div has not been created one is created. Controls
* with a visual component will almost always want to override this method
* to customize the look of control.
*
* Parameters:
* px - {<OpenLayers.Pixel>} The top-left pixel position of the control
* or null.
*
* Returns:
* {DOMElement} A reference to the DIV DOMElement containing the control
*/
draw: function (px) {
if (this.div == null) {
this.div = OpenLayers.Util.createDiv(this.id);
this.div.className = this.displayClass;
if (!this.allowSelection) {
this.div.className += " olControlNoSelect";
this.div.setAttribute("unselectable", "on", 0);
this.div.onselectstart = function() { return(false); };
}
if (this.title != "") {
this.div.title = this.title;
}
}
if (px != null) {
this.position = px.clone();
}
this.moveTo(this.position);
return this.div;
},
/**
* Method: moveTo
* Sets the left and top style attributes to the passed in pixel
* coordinates.
*
* Parameters:
* px - {<OpenLayers.Pixel>}
*/
moveTo: function (px) {
if ((px != null) && (this.div != null)) {
this.div.style.left = px.x + "px";
this.div.style.top = px.y + "px";
}
},
/**
* Method: activate
* Explicitly activates a control and it's associated
* handler if one has been set. Controls can be
* deactivated by calling the deactivate() method.
*
* Returns:
* {Boolean} True if the control was successfully activated or
* false if the control was already active.
*/
activate: function () {
if (this.active) {
return false;
}
if (this.handler) {
this.handler.activate();
}
this.active = true;
if(this.map) {
OpenLayers.Element.addClass(
this.map.viewPortDiv,
this.displayClass.replace(/ /g, "") + "Active"
);
}
this.events.triggerEvent("activate");
return true;
},
/**
* Method: deactivate
* Deactivates a control and it's associated handler if any. The exact
* effect of this depends on the control itself.
*
* Returns:
* {Boolean} True if the control was effectively deactivated or false
* if the control was already inactive.
*/
deactivate: function () {
if (this.active) {
if (this.handler) {
this.handler.deactivate();
}
this.active = false;
if(this.map) {
OpenLayers.Element.removeClass(
this.map.viewPortDiv,
this.displayClass.replace(/ /g, "") + "Active"
);
}
this.events.triggerEvent("deactivate");
return true;
}
return false;
},
CLASS_NAME: "OpenLayers.Control"
});
OpenLayers.Control.TYPE_BUTTON = 1;
OpenLayers.Control.TYPE_TOGGLE = 2;
OpenLayers.Control.TYPE_TOOL = 3;

View File

@ -1,165 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.ArgParser
* The ArgParser control adds location bar querystring parsing functionality
* to an OpenLayers Map.
* When added to a Map control, on a page load/refresh, the Map will
* automatically take the href string and parse it for lon, lat, zoom, and
* layers information.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ArgParser = OpenLayers.Class(OpenLayers.Control, {
/**
* Parameter: center
* {<OpenLayers.LonLat>}
*/
center: null,
/**
* Parameter: zoom
* {int}
*/
zoom: null,
/**
* Parameter: layers
* {Array(<OpenLayers.Layer>)}
*/
layers: null,
/**
* APIProperty: displayProjection
* {<OpenLayers.Projection>} Requires proj4js support.
* Projection used when reading the coordinates from the URL. This will
*
* reproject the map coordinates from the URL into the map's
* projection.
*
* If you are using this functionality, be aware that any permalink
* which is added to the map will determine the coordinate type which
* is read from the URL, which means you should not add permalinks with
* different displayProjections to the same map.
*/
displayProjection: null,
/**
* Constructor: OpenLayers.Control.ArgParser
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
OpenLayers.Control.prototype.setMap.apply(this, arguments);
//make sure we dont already have an arg parser attached
for(var i=0, len=this.map.controls.length; i<len; i++) {
var control = this.map.controls[i];
if ( (control != this) &&
(control.CLASS_NAME == "OpenLayers.Control.ArgParser") ) {
// If a second argparser is added to the map, then we
// override the displayProjection to be the one added to the
// map.
if (control.displayProjection != this.displayProjection) {
this.displayProjection = control.displayProjection;
}
break;
}
}
if (i == this.map.controls.length) {
var args = OpenLayers.Util.getParameters();
// Be careful to set layer first, to not trigger unnecessary layer loads
if (args.layers) {
this.layers = args.layers;
// when we add a new layer, set its visibility
this.map.events.register('addlayer', this,
this.configureLayers);
this.configureLayers();
}
if (args.lat && args.lon) {
this.center = new OpenLayers.LonLat(parseFloat(args.lon),
parseFloat(args.lat));
if (args.zoom) {
this.zoom = parseInt(args.zoom);
}
// when we add a new baselayer to see when we can set the center
this.map.events.register('changebaselayer', this,
this.setCenter);
this.setCenter();
}
}
},
/**
* Method: setCenter
* As soon as a baseLayer has been loaded, we center and zoom
* ...and remove the handler.
*/
setCenter: function() {
if (this.map.baseLayer) {
//dont need to listen for this one anymore
this.map.events.unregister('changebaselayer', this,
this.setCenter);
if (this.displayProjection) {
this.center.transform(this.displayProjection,
this.map.getProjectionObject());
}
this.map.setCenter(this.center, this.zoom);
}
},
/**
* Method: configureLayers
* As soon as all the layers are loaded, cycle through them and
* hide or show them.
*/
configureLayers: function() {
if (this.layers.length == this.map.layers.length) {
this.map.events.unregister('addlayer', this, this.configureLayers);
for(var i=0, len=this.layers.length; i<len; i++) {
var layer = this.map.layers[i];
var c = this.layers.charAt(i);
if (c == "B") {
this.map.setBaseLayer(layer);
} else if ( (c == "T") || (c == "F") ) {
layer.setVisibility(c == "T");
}
}
}
},
CLASS_NAME: "OpenLayers.Control.ArgParser"
});

View File

@ -1,92 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Attribution
* The attribution control adds attribution from layers to the map display.
* It uses 'attribution' property of each layer.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Attribution =
OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: seperator
* {String} String used to seperate layers.
*/
separator: ", ",
/**
* Constructor: OpenLayers.Control.Attribution
*
* Parameters:
* options - {Object} Options for control.
*/
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* Method: destroy
* Destroy control.
*/
destroy: function() {
this.map.events.un({
"removelayer": this.updateAttribution,
"addlayer": this.updateAttribution,
"changelayer": this.updateAttribution,
"changebaselayer": this.updateAttribution,
scope: this
});
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Initialize control.
*
* Returns:
* {DOMElement} A reference to the DIV DOMElement containing the control
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
this.map.events.on({
'changebaselayer': this.updateAttribution,
'changelayer': this.updateAttribution,
'addlayer': this.updateAttribution,
'removelayer': this.updateAttribution,
scope: this
});
this.updateAttribution();
return this.div;
},
/**
* Method: updateAttribution
* Update attribution string.
*/
updateAttribution: function() {
var attributions = [];
if (this.map && this.map.layers) {
for(var i=0, len=this.map.layers.length; i<len; i++) {
var layer = this.map.layers[i];
if (layer.attribution && layer.getVisibility()) {
attributions.push( layer.attribution );
}
}
this.div.innerHTML = attributions.join(this.separator);
}
},
CLASS_NAME: "OpenLayers.Control.Attribution"
});

View File

@ -1,43 +0,0 @@
/* Copyright (c) 2006-2007 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.Button
* The Button control is a very simple push-button, for use with
* <OpenLayers.Control.Panel>.
* When clicked, the function trigger() is executed.
*
* Inherits from:
* - <OpenLayers.Control>
*
* Use:
* (code)
* var button = new OpenLayers.Control.Button({
* displayClass: "MyButton", trigger: myFunction
* });
* panel.addControls([button]);
* (end)
*
* Will create a button with CSS class MyButtonItemInactive, that
* will call the function MyFunction() when clicked.
*/
OpenLayers.Control.Button = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {Integer} OpenLayers.Control.TYPE_BUTTON.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/**
* Method: trigger
* Called by a control panel when the button is clicked.
*/
trigger: function() {},
CLASS_NAME: "OpenLayers.Control.Button"
});

View File

@ -1,293 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Drag.js
* @requires OpenLayers/Handler/Feature.js
*/
/**
* Class: OpenLayers.Control.DragFeature
* The DragFeature control moves a feature with a drag of the mouse. Create a
* new control with the <OpenLayers.Control.DragFeature> constructor.
*
* Inherits From:
* - <OpenLayers.Control>
*/
OpenLayers.Control.DragFeature = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: geometryTypes
* {Array(String)} To restrict dragging to a limited set of geometry types,
* send a list of strings corresponding to the geometry class names.
*/
geometryTypes: null,
/**
* APIProperty: onStart
* {Function} Define this function if you want to know when a drag starts.
* The function should expect to receive two arguments: the feature
* that is about to be dragged and the pixel location of the mouse.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature that is about to be
* dragged.
* pixel - {<OpenLayers.Pixel>} The pixel location of the mouse.
*/
onStart: function(feature, pixel) {},
/**
* APIProperty: onDrag
* {Function} Define this function if you want to know about each move of a
* feature. The function should expect to receive two arguments: the
* feature that is being dragged and the pixel location of the mouse.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature that was dragged.
* pixel - {<OpenLayers.Pixel>} The pixel location of the mouse.
*/
onDrag: function(feature, pixel) {},
/**
* APIProperty: onComplete
* {Function} Define this function if you want to know when a feature is
* done dragging. The function should expect to receive two arguments:
* the feature that is being dragged and the pixel location of the
* mouse.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature that was dragged.
* pixel - {<OpenLayers.Pixel>} The pixel location of the mouse.
*/
onComplete: function(feature, pixel) {},
/**
* Property: layer
* {<OpenLayers.Layer.Vector>}
*/
layer: null,
/**
* Property: feature
* {<OpenLayers.Feature.Vector>}
*/
feature: null,
/**
* Property: dragCallbacks
* {Object} The functions that are sent to the drag handler for callback.
*/
dragCallbacks: {},
/**
* Property: featureCallbacks
* {Object} The functions that are sent to the feature handler for callback.
*/
featureCallbacks: {},
/**
* Property: lastPixel
* {<OpenLayers.Pixel>}
*/
lastPixel: null,
/**
* Constructor: OpenLayers.Control.DragFeature
* Create a new control to drag features.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>} The layer containing features to be
* dragged.
* options - {Object} Optional object whose properties will be set on the
* control.
*/
initialize: function(layer, options) {
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.layer = layer;
this.handlers = {
drag: new OpenLayers.Handler.Drag(
this, OpenLayers.Util.extend({
down: this.downFeature,
move: this.moveFeature,
up: this.upFeature,
out: this.cancel,
done: this.doneDragging
}, this.dragCallbacks)
),
feature: new OpenLayers.Handler.Feature(
this, this.layer, OpenLayers.Util.extend({
over: this.overFeature,
out: this.outFeature
}, this.featureCallbacks),
{geometryTypes: this.geometryTypes}
)
};
},
/**
* APIMethod: destroy
* Take care of things that are not handled in superclass
*/
destroy: function() {
this.layer = null;
OpenLayers.Control.prototype.destroy.apply(this, []);
},
/**
* APIMethod: activate
* Activate the control and the feature handler.
*
* Returns:
* {Boolean} Successfully activated the control and feature handler.
*/
activate: function() {
return (this.handlers.feature.activate() &&
OpenLayers.Control.prototype.activate.apply(this, arguments));
},
/**
* APIMethod: deactivate
* Deactivate the control and all handlers.
*
* Returns:
* {Boolean} Successfully deactivated the control.
*/
deactivate: function() {
// the return from the handlers is unimportant in this case
this.handlers.drag.deactivate();
this.handlers.feature.deactivate();
this.feature = null;
this.dragging = false;
this.lastPixel = null;
OpenLayers.Element.removeClass(
this.map.viewPortDiv, this.displayClass + "Over"
);
return OpenLayers.Control.prototype.deactivate.apply(this, arguments);
},
/**
* Method: overFeature
* Called when the feature handler detects a mouse-over on a feature.
* This activates the drag handler.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The selected feature.
*/
overFeature: function(feature) {
if(!this.handlers.drag.dragging) {
this.feature = feature;
this.handlers.drag.activate();
this.over = true;
OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass + "Over");
} else {
if(this.feature.id == feature.id) {
this.over = true;
} else {
this.over = false;
}
}
},
/**
* Method: downFeature
* Called when the drag handler detects a mouse-down.
*
* Parameters:
* pixel - {<OpenLayers.Pixel>} Location of the mouse event.
*/
downFeature: function(pixel) {
this.lastPixel = pixel;
this.onStart(this.feature, pixel);
},
/**
* Method: moveFeature
* Called when the drag handler detects a mouse-move. Also calls the
* optional onDrag method.
*
* Parameters:
* pixel - {<OpenLayers.Pixel>} Location of the mouse event.
*/
moveFeature: function(pixel) {
var res = this.map.getResolution();
this.feature.geometry.move(res * (pixel.x - this.lastPixel.x),
res * (this.lastPixel.y - pixel.y));
this.layer.drawFeature(this.feature);
this.lastPixel = pixel;
this.onDrag(this.feature, pixel);
},
/**
* Method: upFeature
* Called when the drag handler detects a mouse-up.
*
* Parameters:
* pixel - {<OpenLayers.Pixel>} Location of the mouse event.
*/
upFeature: function(pixel) {
if(!this.over) {
this.handlers.drag.deactivate();
}
},
/**
* Method: doneDragging
* Called when the drag handler is done dragging.
*
* Parameters:
* pixel - {<OpenLayers.Pixel>} The last event pixel location. If this event
* came from a mouseout, this may not be in the map viewport.
*/
doneDragging: function(pixel) {
this.onComplete(this.feature, pixel);
},
/**
* Method: outFeature
* Called when the feature handler detects a mouse-out on a feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature that the mouse left.
*/
outFeature: function(feature) {
if(!this.handlers.drag.dragging) {
this.over = false;
this.handlers.drag.deactivate();
OpenLayers.Element.removeClass(
this.map.viewPortDiv, this.displayClass + "Over"
);
this.feature = null;
} else {
if(this.feature.id == feature.id) {
this.over = false;
}
}
},
/**
* Method: cancel
* Called when the drag handler detects a mouse-out (from the map viewport).
*/
cancel: function() {
this.handlers.drag.deactivate();
this.over = false;
},
/**
* Method: setMap
* Set the map property for the control and all handlers.
*
* Parameters:
* map - {<OpenLayers.Map>} The control's map.
*/
setMap: function(map) {
this.handlers.drag.setMap(map);
this.handlers.feature.setMap(map);
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
CLASS_NAME: "OpenLayers.Control.DragFeature"
});

View File

@ -1,85 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Drag.js
*/
/**
* Class: OpenLayers.Control.DragPan
* The DragPan control pans the map with a drag of the mouse.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.DragPan = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {OpenLayers.Control.TYPES}
*/
type: OpenLayers.Control.TYPE_TOOL,
/**
* Property: panned
* {Boolean} The map moved.
*/
panned: false,
/**
* Property: interval
* {Integer} The number of milliseconds that should ellapse before
* panning the map again. Set this to increase dragging performance.
* Defaults to 25 milliseconds.
*/
interval: 25,
/**
* Method: draw
* Creates a Drag handler, using <panMap> and
* <panMapDone> as callbacks.
*/
draw: function() {
this.handler = new OpenLayers.Handler.Drag(this, {
"move": this.panMap,
"done": this.panMapDone
}, {
interval: this.interval
}
);
},
/**
* Method: panMap
*
* Parameters:
* xy - {<OpenLayers.Pixel>} Pixel of the mouse position
*/
panMap: function(xy) {
this.panned = true;
this.map.pan(
this.handler.last.x - xy.x,
this.handler.last.y - xy.y,
{dragging: this.handler.dragging, animate: false}
);
},
/**
* Method: panMapDone
* Finish the panning operation. Only call setCenter (through <panMap>)
* if the map has actually been moved.
*
* Parameters:
* xy - {<OpenLayers.Pixel>} Pixel of the mouse position
*/
panMapDone: function(xy) {
if(this.panned) {
this.panMap(xy);
this.panned = false;
}
},
CLASS_NAME: "OpenLayers.Control.DragPan"
});

View File

@ -1,115 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Feature/Vector.js
*/
/**
* Class: OpenLayers.Control.DrawFeature
* The DrawFeature control draws point, line or polygon features on a vector
* layer when active.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.DrawFeature = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: layer
* {<OpenLayers.Layer.Vector>}
*/
layer: null,
/**
* Property: callbacks
* {Object} The functions that are sent to the handler for callback
*/
callbacks: null,
/**
* Constant: EVENT_TYPES
*
* Supported event types:
* featureadded - Triggered when a feature is added
*/
EVENT_TYPES: ["featureadded"],
/**
* APIProperty: featureAdded
* {Function} Called after each feature is added
*/
featureAdded: function() {},
/**
* APIProperty: handlerOptions
* {Object} Used to set non-default properties on the control's handler
*/
handlerOptions: null,
/**
* Constructor: OpenLayers.Control.DrawFeature
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* handler - {<OpenLayers.Handler>}
* options - {Object}
*/
initialize: function(layer, handler, options) {
// concatenate events specific to vector with those from the base
this.EVENT_TYPES =
OpenLayers.Control.DrawFeature.prototype.EVENT_TYPES.concat(
OpenLayers.Control.prototype.EVENT_TYPES
);
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.callbacks = OpenLayers.Util.extend(
{
done: this.drawFeature,
modify: function(vertex, feature) {
this.layer.events.triggerEvent(
"sketchmodified", {vertex: vertex, feature: feature}
);
},
create: function(vertex, feature) {
this.layer.events.triggerEvent(
"sketchstarted", {vertex: vertex, feature: feature}
);
}
},
this.callbacks
);
this.layer = layer;
var sketchStyle = this.layer.styleMap && this.layer.styleMap.styles.temporary;
if(sketchStyle) {
this.handlerOptions = this.handlerOptions || {};
this.handlerOptions.layerOptions = OpenLayers.Util.applyDefaults(
this.handlerOptions.layerOptions,
{styleMap: new OpenLayers.StyleMap({"default": sketchStyle})}
);
}
this.handler = new handler(this, this.callbacks, this.handlerOptions);
},
/**
* Method: drawFeature
*/
drawFeature: function(geometry) {
var feature = new OpenLayers.Feature.Vector(geometry);
var proceed = this.layer.events.triggerEvent(
"sketchcomplete", {feature: feature}
);
if(proceed !== false) {
feature.state = OpenLayers.State.INSERT;
this.layer.addFeatures([feature]);
this.featureAdded(feature);
this.events.triggerEvent("featureadded",{feature : feature});
}
},
CLASS_NAME: "OpenLayers.Control.DrawFeature"
});

View File

@ -1,62 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control/Panel.js
* @requires OpenLayers/Control/Navigation.js
* @requires OpenLayers/Control/DrawFeature.js
* @requires OpenLayers/Handler/Point.js
* @requires OpenLayers/Handler/Path.js
* @requires OpenLayers/Handler/Polygon.js
*/
/**
* Class: OpenLayers.Control.EditingToolbar
* The EditingToolbar is a panel of 4 controls to draw polygons, lines,
* points, or to navigate the map by panning. By default it appears in the
* upper right corner of the map.
*
* Inherits from:
* - <OpenLayers.Control.Panel>
*/
OpenLayers.Control.EditingToolbar = OpenLayers.Class(
OpenLayers.Control.Panel, {
/**
* Constructor: OpenLayers.Control.EditingToolbar
* Create an editing toolbar for a given layer.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>}
* options - {Object}
*/
initialize: function(layer, options) {
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls(
[ new OpenLayers.Control.Navigation() ]
);
var controls = [
new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Point, {'displayClass': 'olControlDrawFeaturePoint'}),
new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Path, {'displayClass': 'olControlDrawFeaturePath'}),
new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon, {'displayClass': 'olControlDrawFeaturePolygon'})
];
this.addControls(controls);
},
/**
* Method: draw
* calls the default draw, and then activates mouse defaults.
*
* Returns:
* {DOMElement}
*/
draw: function() {
var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
this.activateControl(this.controls[0]);
return div;
},
CLASS_NAME: "OpenLayers.Control.EditingToolbar"
});

View File

@ -1,558 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Click.js
* @requires OpenLayers/Handler/Box.js
* @requires OpenLayers/Handler/Hover.js
* @requires OpenLayers/Filter/Spatial.js
*/
/**
* Class: OpenLayers.Control.GetFeature
* Gets vector features for locations underneath the mouse cursor. Can be
* configured to act on click, hover or dragged boxes. Uses an
* <OpenLayers.Protocol> that supports spatial filters (BBOX) to retrieve
* features from a server and fires events that notify applications of the
* selected features.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.GetFeature = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: protocol
* {<OpenLayers.Protocol>} Required. The protocol used for fetching
* features.
*/
protocol: null,
/**
* APIProperty: multipleKey
* {String} An event modifier ('altKey' or 'shiftKey') that temporarily sets
* the <multiple> property to true. Default is null.
*/
multipleKey: null,
/**
* APIProperty: toggleKey
* {String} An event modifier ('altKey' or 'shiftKey') that temporarily sets
* the <toggle> property to true. Default is null.
*/
toggleKey: null,
/**
* Property: modifiers
* {Object} The event modifiers to use, according to the current event
* being handled by this control's handlers
*/
modifiers: null,
/**
* APIProperty: multiple
* {Boolean} Allow selection of multiple geometries. Default is false.
*/
multiple: false,
/**
* APIProperty: click
* {Boolean} Use a click handler for selecting/unselecting features.
* Default is true.
*/
click: true,
/**
* APIProperty: clickout
* {Boolean} Unselect features when clicking outside any feature.
* Applies only if <click> is true. Default is true.
*/
clickout: true,
/**
* APIProperty: toggle
* {Boolean} Unselect a selected feature on click. Applies only if
* <click> is true. Default is false.
*/
toggle: false,
/**
* APIProperty: clickTolerance
* {Integer} Tolerance for the BBOX query in pixels. This has the
* same effect as the tolerance parameter on WMS GetFeatureInfo
* requests. Will be ignored for box selections. Applies only if
* <click> is true. Default is 5.
*/
clickTolerance: 5,
/**
* APIProperty: hover
* {Boolean} Send feature requests on mouse moves. Default is false.
*/
hover: false,
/**
* APIProperty: box
* {Boolean} Allow feature selection by drawing a box.
*/
box: false,
/**
* APIProperty: maxFeatures
* {Integer} Maximum number of features to return from a query, if
* supported by the <protocol>. Default is 10.
*/
maxFeatures: 10,
/**
* Property: features
* {Object} Hash of {<OpenLayers.Feature.Vector>}, keyed by fid, holding
* the currently selected features
*/
features: null,
/**
* Proeprty: hoverFeature
* {<OpenLayers.Feature.Vector>} The feature currently selected by the
* hover handler
*/
hoverFeature: null,
/**
* APIProperty: handlerOptions
* {Object} Additional options for the handlers used by this control. This
* is a hash with the keys "click", "box" and "hover".
*/
handlerOptions: null,
/**
* Property: handlers
* {Object} Object with references to multiple <OpenLayers.Handler>
* instances.
*/
handlers: null,
/**
* Property: hoverResponse
* {<OpenLayers.Protocol.Response>} The response object associated with
* the currently running hover request (if any).
*/
hoverResponse: null,
/**
* Constant: EVENT_TYPES
*
* Supported event types:
* beforefeatureselected - Triggered when <click> is true before a
* feature is selected. The event object has a feature property with
* the feature about to select
* featureselected - Triggered when <click> is true and a feature is
* selected. The event object has a feature property with the
* selected feature
* featureunselected - Triggered when <click> is true and a feature is
* unselected. The event object has a feature property with the
* unselected feature
* clickout - Triggered when when <click> is true and no feature was
* selected.
* hoverfeature - Triggered when <hover> is true and the mouse has
* stopped over a feature
* outfeature - Triggered when <hover> is true and the mouse moves
* moved away from a hover-selected feature
*/
EVENT_TYPES: ["featureselected", "featureunselected", "clickout",
"beforefeatureselected", "hoverfeature", "outfeature"],
/**
* Constructor: OpenLayers.Control.GetFeature
* Create a new control for fetching remote features.
*
* Parameters:
* options - {Object} A configuration object which at least has to contain
* a <protocol> property
*/
initialize: function(options) {
// concatenate events specific to vector with those from the base
this.EVENT_TYPES =
OpenLayers.Control.GetFeature.prototype.EVENT_TYPES.concat(
OpenLayers.Control.prototype.EVENT_TYPES
);
options.handlerOptions = options.handlerOptions || {};
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.features = {};
this.handlers = {};
if(this.click) {
this.handlers.click = new OpenLayers.Handler.Click(this,
{click: this.selectSingle}, this.handlerOptions.click || {})
};
if(this.box) {
this.handlers.box = new OpenLayers.Handler.Box(
this, {done: this.selectBox},
OpenLayers.Util.extend(this.handlerOptions.box, {
boxDivClassName: "olHandlerBoxSelectFeature"
})
);
}
if(this.hover) {
this.handlers.hover = new OpenLayers.Handler.Hover(
this, {'move': this.cancelHover, 'pause': this.selectHover},
OpenLayers.Util.extend(this.handlerOptions.hover, {
'delay': 250
})
);
}
},
/**
* Method: activate
* Activates the control.
*
* Returns:
* {Boolean} The control was effectively activated.
*/
activate: function () {
if (!this.active) {
for(var i in this.handlers) {
this.handlers[i].activate();
}
}
return OpenLayers.Control.prototype.activate.apply(
this, arguments
);
},
/**
* Method: deactivate
* Deactivates the control.
*
* Returns:
* {Boolean} The control was effectively deactivated.
*/
deactivate: function () {
if (this.active) {
for(var i in this.handlers) {
this.handlers[i].deactivate();
}
}
return OpenLayers.Control.prototype.deactivate.apply(
this, arguments
);
},
/**
* Method: unselectAll
* Unselect all selected features. To unselect all except for a single
* feature, set the options.except property to the feature.
*
* Parameters:
* options - {Object} Optional configuration object.
*/
unselectAll: function(options) {
// we'll want an option to supress notification here
var feature;
for(var i=this.features.length-1; i>=0; --i) {
feature = this.features[i];
if(!options || options.except != feature) {
this.unselect(feature);
}
}
},
/**
* Method: selectSingle
* Called on click
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
selectSingle: function(evt) {
// Set the cursor to "wait" to tell the user we're working on their click.
OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait");
var bounds = this.pixelToBounds(evt.xy);
this.setModifiers(evt);
this.request(bounds, {single: true});
},
/**
* Method: selectBox
* Callback from the handlers.box set up when <box> selection is on
*
* Parameters:
* position - {<OpenLayers.Bounds>}
*/
selectBox: function(position) {
if (position instanceof OpenLayers.Bounds) {
var minXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.left, position.bottom)
);
var maxXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.right, position.top)
);
var bounds = new OpenLayers.Bounds(
minXY.lon, minXY.lat, maxXY.lon, maxXY.lat
);
this.setModifiers(this.handlers.box.dragHandler.evt);
this.request(bounds);
}
},
/**
* Method selectHover
* Callback from the handlers.hover set up when <hover> selection is on
*
* Parameters:
* evt {Object} - event object with an xy property
*/
selectHover: function(evt) {
var bounds = this.pixelToBounds(evt.xy);
this.request(bounds, {single: true, hover: true});
},
/**
* Method: cancelHover
* Callback from the handlers.hover set up when <hover> selection is on
*/
cancelHover: function() {
if (this.hoverResponse) {
this.protocol.abort(this.hoverResponse);
this.hoverResponse = null;
}
},
/**
* Method: request
* Sends a GetFeature request to the WFS
*
* Parameters:
* bounds - {<OpenLayers.Bounds>} bounds for the request's BBOX filter
* options - {Object} additional options for this method.
*
* Supported options include:
* single - {Boolean} A single feature should be returned.
* Note that this will be ignored if the protocol does not
* return the geometries of the features.
* hover - {Boolean} Do the request for the hover handler.
*/
request: function(bounds, options) {
options = options || {};
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.BBOX,
value: bounds
});
var response = this.protocol.read({
maxFeatures: options.single == true ? this.maxFeatures : undefined,
filter: filter,
callback: function(result) {
if(result.code == 1) {
if(result.features.length) {
if(options.single == true) {
this.selectBestFeature(result.features,
bounds.getCenterLonLat(), options);
} else {
this.select(result.features);
}
} else if(options.hover) {
this.hoverSelect();
} else {
this.events.triggerEvent("clickout");
if(this.clickout) {
this.unselectAll();
}
}
}
// Reset the cursor.
OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
},
scope: this
});
if(options.hover == true) {
this.hoverResponse = response;
}
},
/**
* Method: selectBestFeature
* Selects the feature from an array of features that is the best match
* for the click position.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)}
* clickPosition - {<OpenLayers.LonLat>}
* options - {Object} additional options for this method
*
* Supported options include:
* hover - {Boolean} Do the selection for the hover handler.
*/
selectBestFeature: function(features, clickPosition, options) {
options = options || {};
if(features.length) {
var point = new OpenLayers.Geometry.Point(clickPosition.lon,
clickPosition.lat);
var feature, resultFeature, dist;
var minDist = Number.MAX_VALUE;
for(var i=0; i<features.length; ++i) {
feature = features[i];
if(feature.geometry) {
dist = point.distanceTo(feature.geometry, {edge: false});
if(dist < minDist) {
minDist = dist;
resultFeature = feature;
if(minDist == 0) {
break;
}
}
}
}
if(options.hover == true) {
this.hoverSelect(resultFeature);
} else {
this.select(resultFeature || features);
}
};
},
/**
* Method: setModifiers
* Sets the multiple and toggle modifiers according to the current event
*
* Parameters:
* evt {<OpenLayers.Event>}
*/
setModifiers: function(evt) {
this.modifiers = {
multiple: this.multiple || (this.multipleKey && evt[this.multipleKey]),
toggle: this.toggle || (this.toggleKey && evt[this.toggleKey])
}
},
/**
* Method: select
* Add feature to the hash of selected features and trigger the
* featureselected event.
*
* Parameters:
* features - {<OpenLayers.Feature.Vector>} or an array of features
*/
select: function(features) {
if(!this.modifiers.multiple && !this.modifiers.toggle) {
this.unselectAll();
}
if(!(features instanceof Array)) {
features = [features];
}
var feature;
for(var i=0, len=features.length; i<len; ++i) {
feature = features[i];
if(this.features[feature.fid || feature.id]) {
if(this.modifiers.toggle) {
this.unselect(this.features[feature.fid || feature.id]);
}
} else {
cont = this.events.triggerEvent("beforefeatureselected", {
feature: feature
});
if(cont !== false) {
this.features[feature.fid || feature.id] = feature;
this.events.triggerEvent("featureselected",
{feature: feature});
}
}
}
},
/**
* Method: hoverSelect
* Sets/unsets the <hoverFeature>
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} the feature to hover-select.
* If none is provided, the current <hoverFeature> will be nulled and
* the outfeature event will be triggered.
*/
hoverSelect: function(feature) {
var fid = feature ? feature.fid || feature.id : null;
var hfid = this.hoverFeature ?
this.hoverFeature.fid || this.hoverFeature.id : null;
if(hfid && hfid != fid) {
this.events.triggerEvent("outfeature",
{feature: this.hoverFeature});
this.hoverFeature = null;
}
if(fid && fid != hfid) {
this.events.triggerEvent("hoverfeature", {feature: feature});
this.hoverFeature = feature;
}
},
/**
* Method: unselect
* Remove feature from the hash of selected features and trigger the
* featureunselected event.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
unselect: function(feature) {
delete this.features[feature.fid || feature.id];
this.events.triggerEvent("featureunselected", {feature: feature});
},
/**
* Method: unselectAll
* Unselect all selected features.
*/
unselectAll: function() {
// we'll want an option to supress notification here
for(var fid in this.features) {
this.unselect(this.features[fid]);
}
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
for(var i in this.handlers) {
this.handlers[i].setMap(map);
}
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
/**
* Method: pixelToBounds
* Takes a pixel as argument and creates bounds after adding the
* <clickTolerance>.
*
* Parameters:
* pixel - {<OpenLayers.Pixel>}
*/
pixelToBounds: function(pixel) {
var llPx = pixel.add(-this.clickTolerance/2, this.clickTolerance/2);
var urPx = pixel.add(this.clickTolerance/2, -this.clickTolerance/2);
var ll = this.map.getLonLatFromPixel(llPx);
var ur = this.map.getLonLatFromPixel(urPx);
return new OpenLayers.Bounds(ll.lon, ll.lat, ur.lon, ur.lat);
},
CLASS_NAME: "OpenLayers.Control.GetFeature"
});

View File

@ -1,121 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Keyboard.js
*/
/**
* Class: OpenLayers.Control.KeyboardDefaults
* The KeyboardDefaults control adds panning and zooming functions, controlled
* with the keyboard. By default arrow keys pan, +/- keys zoom & Page Up/Page
* Down/Home/End scroll by three quarters of a page.
*
* This control has no visible appearance.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.KeyboardDefaults = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: slideFactor
* Pixels to slide by.
*/
slideFactor: 75,
/**
* Constructor: OpenLayers.Control.KeyboardDefaults
*/
initialize: function() {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* APIMethod: destroy
*/
destroy: function() {
if (this.handler) {
this.handler.destroy();
}
this.handler = null;
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Create handler.
*/
draw: function() {
this.handler = new OpenLayers.Handler.Keyboard( this, {
"keydown": this.defaultKeyPress });
this.activate();
},
/**
* Method: defaultKeyPress
* When handling the key event, we only use evt.keyCode. This holds
* some drawbacks, though we get around them below. When interpretting
* the keycodes below (including the comments associated with them),
* consult the URL below. For instance, the Safari browser returns
* "IE keycodes", and so is supported by any keycode labeled "IE".
*
* Very informative URL:
* http://unixpapa.com/js/key.html
*
* Parameters:
* code - {Integer}
*/
defaultKeyPress: function (evt) {
switch(evt.keyCode) {
case OpenLayers.Event.KEY_LEFT:
this.map.pan(-this.slideFactor, 0);
break;
case OpenLayers.Event.KEY_RIGHT:
this.map.pan(this.slideFactor, 0);
break;
case OpenLayers.Event.KEY_UP:
this.map.pan(0, -this.slideFactor);
break;
case OpenLayers.Event.KEY_DOWN:
this.map.pan(0, this.slideFactor);
break;
case 33: // Page Up. Same in all browsers.
var size = this.map.getSize();
this.map.pan(0, -0.75*size.h);
break;
case 34: // Page Down. Same in all browsers.
var size = this.map.getSize();
this.map.pan(0, 0.75*size.h);
break;
case 35: // End. Same in all browsers.
var size = this.map.getSize();
this.map.pan(0.75*size.w, 0);
break;
case 36: // Home. Same in all browsers.
var size = this.map.getSize();
this.map.pan(-0.75*size.w, 0);
break;
case 43: // +/= (ASCII), keypad + (ASCII, Opera)
case 61: // +/= (Mozilla, Opera, some ASCII)
case 187: // +/= (IE)
case 107: // keypad + (IE, Mozilla)
this.map.zoomIn();
break;
case 45: // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
case 109: // -/_ (Mozilla), keypad - (Mozilla, IE)
case 189: // -/_ (IE)
case 95: // -/_ (some ASCII)
this.map.zoomOut();
break;
}
},
CLASS_NAME: "OpenLayers.Control.KeyboardDefaults"
});

View File

@ -1,638 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.LayerSwitcher
* The LayerSwitcher control displays a table of contents for the map. This
* allows the user interface to switch between BaseLasyers and to show or hide
* Overlays. By default the switcher is shown minimized on the right edge of
* the map, the user may expand it by clicking on the handle.
*
* To create the LayerSwitcher outside of the map, pass the Id of a html div
* as the first argument to the constructor.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.LayerSwitcher =
OpenLayers.Class(OpenLayers.Control, {
/**
* Property: activeColor
* {String}
*/
activeColor: "darkblue",
/**
* Property: layerStates
* {Array(Object)} Basically a copy of the "state" of the map's layers
* the last time the control was drawn. We have this in order to avoid
* unnecessarily redrawing the control.
*/
layerStates: null,
// DOM Elements
/**
* Property: layersDiv
* {DOMElement}
*/
layersDiv: null,
/**
* Property: baseLayersDiv
* {DOMElement}
*/
baseLayersDiv: null,
/**
* Property: baseLayers
* {Array(<OpenLayers.Layer>)}
*/
baseLayers: null,
/**
* Property: dataLbl
* {DOMElement}
*/
dataLbl: null,
/**
* Property: dataLayersDiv
* {DOMElement}
*/
dataLayersDiv: null,
/**
* Property: dataLayers
* {Array(<OpenLayers.Layer>)}
*/
dataLayers: null,
/**
* Property: minimizeDiv
* {DOMElement}
*/
minimizeDiv: null,
/**
* Property: maximizeDiv
* {DOMElement}
*/
maximizeDiv: null,
/**
* APIProperty: ascending
* {Boolean}
*/
ascending: true,
/**
* Constructor: OpenLayers.Control.LayerSwitcher
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
this.layerStates = [];
},
/**
* APIMethod: destroy
*/
destroy: function() {
OpenLayers.Event.stopObservingElement(this.div);
OpenLayers.Event.stopObservingElement(this.minimizeDiv);
OpenLayers.Event.stopObservingElement(this.maximizeDiv);
//clear out layers info and unregister their events
this.clearLayersArray("base");
this.clearLayersArray("data");
this.map.events.un({
"addlayer": this.redraw,
"changelayer": this.redraw,
"removelayer": this.redraw,
"changebaselayer": this.redraw,
scope: this
});
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: setMap
*
* Properties:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
OpenLayers.Control.prototype.setMap.apply(this, arguments);
this.map.events.on({
"addlayer": this.redraw,
"changelayer": this.redraw,
"removelayer": this.redraw,
"changebaselayer": this.redraw,
scope: this
});
},
/**
* Method: draw
*
* Returns:
* {DOMElement} A reference to the DIV DOMElement containing the
* switcher tabs.
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this);
// create layout divs
this.loadContents();
// set mode to minimize
if(!this.outsideViewport) {
this.minimizeControl();
}
// populate div with current info
this.redraw();
return this.div;
},
/**
* Method: clearLayersArray
* User specifies either "base" or "data". we then clear all the
* corresponding listeners, the div, and reinitialize a new array.
*
* Parameters:
* layersType - {String}
*/
clearLayersArray: function(layersType) {
var layers = this[layersType + "Layers"];
if (layers) {
for(var i=0, len=layers.length; i<len ; i++) {
var layer = layers[i];
OpenLayers.Event.stopObservingElement(layer.inputElem);
OpenLayers.Event.stopObservingElement(layer.labelSpan);
}
}
this[layersType + "LayersDiv"].innerHTML = "";
this[layersType + "Layers"] = [];
},
/**
* Method: checkRedraw
* Checks if the layer state has changed since the last redraw() call.
*
* Returns:
* {Boolean} The layer state changed since the last redraw() call.
*/
checkRedraw: function() {
var redraw = false;
if ( !this.layerStates.length ||
(this.map.layers.length != this.layerStates.length) ) {
redraw = true;
} else {
for (var i=0, len=this.layerStates.length; i<len; i++) {
var layerState = this.layerStates[i];
var layer = this.map.layers[i];
if ( (layerState.name != layer.name) ||
(layerState.inRange != layer.inRange) ||
(layerState.id != layer.id) ||
(layerState.visibility != layer.visibility) ) {
redraw = true;
break;
}
}
}
return redraw;
},
/**
* Method: redraw
* Goes through and takes the current state of the Map and rebuilds the
* control to display that state. Groups base layers into a
* radio-button group and lists each data layer with a checkbox.
*
* Returns:
* {DOMElement} A reference to the DIV DOMElement containing the control
*/
redraw: function() {
//if the state hasn't changed since last redraw, no need
// to do anything. Just return the existing div.
if (!this.checkRedraw()) {
return this.div;
}
//clear out previous layers
this.clearLayersArray("base");
this.clearLayersArray("data");
var containsOverlays = false;
var containsBaseLayers = false;
// Save state -- for checking layer if the map state changed.
// We save this before redrawing, because in the process of redrawing
// we will trigger more visibility changes, and we want to not redraw
// and enter an infinite loop.
var len = this.map.layers.length;
this.layerStates = new Array(len);
for (var i=0; i <len; i++) {
var layer = this.map.layers[i];
this.layerStates[i] = {
'name': layer.name,
'visibility': layer.visibility,
'inRange': layer.inRange,
'id': layer.id
};
}
var layers = this.map.layers.slice();
if (!this.ascending) { layers.reverse(); }
for(var i=0, len=layers.length; i<len; i++) {
var layer = layers[i];
var baseLayer = layer.isBaseLayer;
if (layer.displayInLayerSwitcher) {
if (baseLayer) {
containsBaseLayers = true;
} else {
containsOverlays = true;
}
// only check a baselayer if it is *the* baselayer, check data
// layers if they are visible
var checked = (baseLayer) ? (layer == this.map.baseLayer)
: layer.getVisibility();
// create input element
var inputElem = document.createElement("input");
inputElem.id = this.id + "_input_" + layer.name;
inputElem.name = (baseLayer) ? "baseLayers" : layer.name;
inputElem.type = (baseLayer) ? "radio" : "checkbox";
inputElem.value = layer.name;
inputElem.checked = checked;
inputElem.defaultChecked = checked;
if (!baseLayer && !layer.inRange) {
inputElem.disabled = true;
}
var context = {
'inputElem': inputElem,
'layer': layer,
'layerSwitcher': this
};
OpenLayers.Event.observe(inputElem, "mouseup",
OpenLayers.Function.bindAsEventListener(this.onInputClick,
context)
);
// create span
var labelSpan = document.createElement("span");
if (!baseLayer && !layer.inRange) {
labelSpan.style.color = "gray";
}
labelSpan.innerHTML = layer.name;
labelSpan.style.verticalAlign = (baseLayer) ? "bottom"
: "baseline";
OpenLayers.Event.observe(labelSpan, "click",
OpenLayers.Function.bindAsEventListener(this.onInputClick,
context)
);
// create line break
var br = document.createElement("br");
var groupArray = (baseLayer) ? this.baseLayers
: this.dataLayers;
groupArray.push({
'layer': layer,
'inputElem': inputElem,
'labelSpan': labelSpan
});
var groupDiv = (baseLayer) ? this.baseLayersDiv
: this.dataLayersDiv;
groupDiv.appendChild(inputElem);
groupDiv.appendChild(labelSpan);
groupDiv.appendChild(br);
}
}
// if no overlays, dont display the overlay label
this.dataLbl.style.display = (containsOverlays) ? "" : "none";
// if no baselayers, dont display the baselayer label
this.baseLbl.style.display = (containsBaseLayers) ? "" : "none";
return this.div;
},
/**
* Method:
* A label has been clicked, check or uncheck its corresponding input
*
* Parameters:
* e - {Event}
*
* Context:
* - {DOMElement} inputElem
* - {<OpenLayers.Control.LayerSwitcher>} layerSwitcher
* - {<OpenLayers.Layer>} layer
*/
onInputClick: function(e) {
if (!this.inputElem.disabled) {
if (this.inputElem.type == "radio") {
this.inputElem.checked = true;
this.layer.map.setBaseLayer(this.layer);
} else {
this.inputElem.checked = !this.inputElem.checked;
this.layerSwitcher.updateMap();
}
}
OpenLayers.Event.stop(e);
},
/**
* Method: onLayerClick
* Need to update the map accordingly whenever user clicks in either of
* the layers.
*
* Parameters:
* e - {Event}
*/
onLayerClick: function(e) {
this.updateMap();
},
/**
* Method: updateMap
* Cycles through the loaded data and base layer input arrays and makes
* the necessary calls to the Map object such that that the map's
* visual state corresponds to what the user has selected in
* the control.
*/
updateMap: function() {
// set the newly selected base layer
for(var i=0, len=this.baseLayers.length; i<len; i++) {
var layerEntry = this.baseLayers[i];
if (layerEntry.inputElem.checked) {
this.map.setBaseLayer(layerEntry.layer, false);
}
}
// set the correct visibilities for the overlays
for(var i=0, len=this.dataLayers.length; i<len; i++) {
var layerEntry = this.dataLayers[i];
layerEntry.layer.setVisibility(layerEntry.inputElem.checked);
}
},
/**
* Method: maximizeControl
* Set up the labels and divs for the control
*
* Parameters:
* e - {Event}
*/
maximizeControl: function(e) {
//HACK HACK HACK - find a way to auto-size this layerswitcher
this.div.style.width = "20em";
this.div.style.height = "";
this.showControls(false);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: minimizeControl
* Hide all the contents of the control, shrink the size,
* add the maximize icon
*
* Parameters:
* e - {Event}
*/
minimizeControl: function(e) {
this.div.style.width = "0px";
this.div.style.height = "0px";
this.showControls(true);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: showControls
* Hide/Show all LayerSwitcher controls depending on whether we are
* minimized or not
*
* Parameters:
* minimize - {Boolean}
*/
showControls: function(minimize) {
this.maximizeDiv.style.display = minimize ? "" : "none";
this.minimizeDiv.style.display = minimize ? "none" : "";
this.layersDiv.style.display = minimize ? "none" : "";
},
/**
* Method: loadContents
* Set up the labels and divs for the control
*/
loadContents: function() {
//configure main div
this.div.style.position = "absolute";
this.div.style.top = "25px";
this.div.style.right = "0px";
this.div.style.left = "";
this.div.style.fontFamily = "sans-serif";
this.div.style.fontWeight = "bold";
this.div.style.marginTop = "3px";
this.div.style.marginLeft = "3px";
this.div.style.marginBottom = "3px";
this.div.style.fontSize = "smaller";
this.div.style.color = "white";
this.div.style.backgroundColor = "transparent";
OpenLayers.Event.observe(this.div, "mouseup",
OpenLayers.Function.bindAsEventListener(this.mouseUp, this));
OpenLayers.Event.observe(this.div, "click",
this.ignoreEvent);
OpenLayers.Event.observe(this.div, "mousedown",
OpenLayers.Function.bindAsEventListener(this.mouseDown, this));
OpenLayers.Event.observe(this.div, "dblclick", this.ignoreEvent);
// layers list div
this.layersDiv = document.createElement("div");
this.layersDiv.id = this.id + "_layersDiv";
this.layersDiv.style.paddingTop = "5px";
this.layersDiv.style.paddingLeft = "10px";
this.layersDiv.style.paddingBottom = "5px";
this.layersDiv.style.paddingRight = "75px";
this.layersDiv.style.backgroundColor = this.activeColor;
// had to set width/height to get transparency in IE to work.
// thanks -- http://jszen.blogspot.com/2005/04/ie6-opacity-filter-caveat.html
//
this.layersDiv.style.width = "100%";
this.layersDiv.style.height = "100%";
this.baseLbl = document.createElement("div");
this.baseLbl.innerHTML = OpenLayers.i18n("baseLayer");
this.baseLbl.style.marginTop = "3px";
this.baseLbl.style.marginLeft = "3px";
this.baseLbl.style.marginBottom = "3px";
this.baseLayersDiv = document.createElement("div");
this.baseLayersDiv.style.paddingLeft = "10px";
/*OpenLayers.Event.observe(this.baseLayersDiv, "click",
OpenLayers.Function.bindAsEventListener(this.onLayerClick, this));
*/
this.dataLbl = document.createElement("div");
this.dataLbl.innerHTML = OpenLayers.i18n("overlays");
this.dataLbl.style.marginTop = "3px";
this.dataLbl.style.marginLeft = "3px";
this.dataLbl.style.marginBottom = "3px";
this.dataLayersDiv = document.createElement("div");
this.dataLayersDiv.style.paddingLeft = "10px";
if (this.ascending) {
this.layersDiv.appendChild(this.baseLbl);
this.layersDiv.appendChild(this.baseLayersDiv);
this.layersDiv.appendChild(this.dataLbl);
this.layersDiv.appendChild(this.dataLayersDiv);
} else {
this.layersDiv.appendChild(this.dataLbl);
this.layersDiv.appendChild(this.dataLayersDiv);
this.layersDiv.appendChild(this.baseLbl);
this.layersDiv.appendChild(this.baseLayersDiv);
}
this.div.appendChild(this.layersDiv);
OpenLayers.Rico.Corner.round(this.div, {corners: "tl bl",
bgColor: "transparent",
color: this.activeColor,
blend: false});
OpenLayers.Rico.Corner.changeOpacity(this.layersDiv, 0.75);
var imgLocation = OpenLayers.Util.getImagesLocation();
var sz = new OpenLayers.Size(18,18);
// maximize button div
var img = imgLocation + 'layer-switcher-maximize.png';
this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(
"OpenLayers_Control_MaximizeDiv",
null,
sz,
img,
"absolute");
this.maximizeDiv.style.top = "5px";
this.maximizeDiv.style.right = "0px";
this.maximizeDiv.style.left = "";
this.maximizeDiv.style.display = "none";
OpenLayers.Event.observe(this.maximizeDiv, "click",
OpenLayers.Function.bindAsEventListener(this.maximizeControl, this)
);
this.div.appendChild(this.maximizeDiv);
// minimize button div
var img = imgLocation + 'layer-switcher-minimize.png';
var sz = new OpenLayers.Size(18,18);
this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv(
"OpenLayers_Control_MinimizeDiv",
null,
sz,
img,
"absolute");
this.minimizeDiv.style.top = "5px";
this.minimizeDiv.style.right = "0px";
this.minimizeDiv.style.left = "";
this.minimizeDiv.style.display = "none";
OpenLayers.Event.observe(this.minimizeDiv, "click",
OpenLayers.Function.bindAsEventListener(this.minimizeControl, this)
);
this.div.appendChild(this.minimizeDiv);
},
/**
* Method: ignoreEvent
*
* Parameters:
* evt - {Event}
*/
ignoreEvent: function(evt) {
OpenLayers.Event.stop(evt);
},
/**
* Method: mouseDown
* Register a local 'mouseDown' flag so that we'll know whether or not
* to ignore a mouseUp event
*
* Parameters:
* evt - {Event}
*/
mouseDown: function(evt) {
this.isMouseDown = true;
this.ignoreEvent(evt);
},
/**
* Method: mouseUp
* If the 'isMouseDown' flag has been set, that means that the drag was
* started from within the LayerSwitcher control, and thus we can
* ignore the mouseup. Otherwise, let the Event continue.
*
* Parameters:
* evt - {Event}
*/
mouseUp: function(evt) {
if (this.isMouseDown) {
this.isMouseDown = false;
this.ignoreEvent(evt);
}
},
CLASS_NAME: "OpenLayers.Control.LayerSwitcher"
});

View File

@ -1,317 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Feature/Vector.js
*/
/**
* Class: OpenLayers.Control.Measure
* Allows for drawing of features for measurements.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Measure = OpenLayers.Class(OpenLayers.Control, {
/**
* Constant: EVENT_TYPES
* {Array(String)} Supported application event types. Register a listener
* for a particular event with the following syntax:
* (code)
* control.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.
*
* Supported control event types (in addition to those from <OpenLayers.Control>):
* measure - Triggered when a measurement sketch is complete. Listeners
* will receive an event with measure, units, order, and geometry
* properties.
* measurepartial - Triggered when a new point is added to the
* measurement sketch. Listeners receive an event with measure,
* units, order, and geometry.
*/
EVENT_TYPES: ['measure', 'measurepartial'],
/**
* APIProperty: handlerOptions
* {Object} Used to set non-default properties on the control's handler
*/
handlerOptions: null,
/**
* Property: callbacks
* {Object} The functions that are sent to the handler for callback
*/
callbacks: null,
/**
* Property: displaySystem
* {String} Display system for output measurements. Supported values
* are 'english', 'metric', and 'geographic'. Default is 'metric'.
*/
displaySystem: 'metric',
/**
* Property: geodesic
* {Boolean} Calculate geodesic metrics instead of planar metrics. This
* requires that geometries can be transformed into Geographic/WGS84
* (if that is not already the map projection). Default is false.
*/
geodesic: false,
/**
* Property: displaySystemUnits
* {Object} Units for various measurement systems. Values are arrays
* of unit abbreviations (from OpenLayers.INCHES_PER_UNIT) in decreasing
* order of length.
*/
displaySystemUnits: {
geographic: ['dd'],
english: ['mi', 'ft', 'in'],
metric: ['km', 'm']
},
/**
* Property: delay
* {Number} Number of milliseconds between clicks before the event is
* considered a double-click. The "measurepartial" event will not
* be triggered if the sketch is completed within this time. This
* is required for IE where creating a browser reflow (if a listener
* is modifying the DOM by displaying the measurement values) messes
* with the dblclick listener in the sketch handler.
*/
partialDelay: 300,
/**
* Property: delayedTrigger
* {Number} Timeout id of trigger for measurepartial.
*/
delayedTrigger: null,
/**
* APIProperty: persist
* {Boolean} Keep the temporary measurement sketch drawn after the
* measurement is complete. The geometry will persist until a new
* measurement is started, the control is deactivated, or <cancel> is
* called.
*/
persist: false,
/**
* Constructor: OpenLayers.Control.Measure
*
* Parameters:
* handler - {<OpenLayers.Handler>}
* options - {Object}
*/
initialize: function(handler, options) {
// concatenate events specific to measure with those from the base
this.EVENT_TYPES =
OpenLayers.Control.Measure.prototype.EVENT_TYPES.concat(
OpenLayers.Control.prototype.EVENT_TYPES
);
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.callbacks = OpenLayers.Util.extend(
{done: this.measureComplete, point: this.measurePartial},
this.callbacks
);
// let the handler options override, so old code that passes 'persist'
// directly to the handler does not need an update
this.handlerOptions = OpenLayers.Util.extend(
{persist: this.persist}, this.handlerOptions
);
this.handler = new handler(this, this.callbacks, this.handlerOptions);
},
/**
* APIMethod: cancel
* Stop the control from measuring. If <persist> is true, the temporary
* sketch will be erased.
*/
cancel: function() {
this.handler.cancel();
},
/**
* Method: updateHandler
*
* Parameters:
* handler - {Function} One of the sketch handler constructors.
* options - {Object} Options for the handler.
*/
updateHandler: function(handler, options) {
var active = this.active;
if(active) {
this.deactivate();
}
this.handler = new handler(this, this.callbacks, options);
if(active) {
this.activate();
}
},
/**
* Method: measureComplete
* Called when the measurement sketch is done.
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*/
measureComplete: function(geometry) {
if(this.delayedTrigger) {
window.clearTimeout(this.delayedTrigger);
}
this.measure(geometry, "measure");
},
/**
* Method: measurePartial
* Called each time a new point is added to the measurement sketch.
*
* Parameters:
* point - {<OpenLayers.Geometry.Point>} The last point added.
* geometry - {<OpenLayers.Geometry>} The sketch geometry.
*/
measurePartial: function(point, geometry) {
this.delayedTrigger = window.setTimeout(
OpenLayers.Function.bind(function() {
this.measure(geometry, "measurepartial");
}, this),
this.partialDelay
);
},
/**
* Method: measure
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
* eventType - {String}
*/
measure: function(geometry, eventType) {
var stat, order;
if(geometry.CLASS_NAME.indexOf('LineString') > -1) {
stat = this.getBestLength(geometry);
order = 1;
} else {
stat = this.getBestArea(geometry);
order = 2;
}
this.events.triggerEvent(eventType, {
measure: stat[0],
units: stat[1],
order: order,
geometry: geometry
});
},
/**
* Method: getBestArea
* Based on the <displaySystem> returns the area of a geometry.
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {Array([Float, String])} Returns a two item array containing the
* area and the units abbreviation.
*/
getBestArea: function(geometry) {
var units = this.displaySystemUnits[this.displaySystem];
var unit, area;
for(var i=0, len=units.length; i<len; ++i) {
unit = units[i];
area = this.getArea(geometry, unit);
if(area > 1) {
break;
}
}
return [area, unit];
},
/**
* Method: getArea
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
* units - {String} Unit abbreviation
*
* Returns:
* {Float} The geometry area in the given units.
*/
getArea: function(geometry, units) {
var area, geomUnits;
if(this.geodesic) {
area = geometry.getGeodesicArea(this.map.getProjectionObject());
geomUnits = "m";
} else {
area = geometry.getArea();
geomUnits = this.map.getUnits();
}
var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT[units];
if(inPerDisplayUnit) {
var inPerMapUnit = OpenLayers.INCHES_PER_UNIT[geomUnits];
area *= Math.pow((inPerMapUnit / inPerDisplayUnit), 2);
}
return area;
},
/**
* Method: getBestLength
* Based on the <displaySystem> returns the length of a geometry.
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {Array([Float, String])} Returns a two item array containing the
* length and the units abbreviation.
*/
getBestLength: function(geometry) {
var units = this.displaySystemUnits[this.displaySystem];
var unit, length;
for(var i=0, len=units.length; i<len; ++i) {
unit = units[i];
length = this.getLength(geometry, unit);
if(length > 1) {
break;
}
}
return [length, unit];
},
/**
* Method: getLength
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
* units - {String} Unit abbreviation
*
* Returns:
* {Float} The geometry length in the given units.
*/
getLength: function(geometry, units) {
var length, geomUnits;
if(this.geodesic) {
length = geometry.getGeodesicLength(this.map.getProjectionObject());
geomUnits = "m";
} else {
length = geometry.getLength();
geomUnits = this.map.getUnits();
}
var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT[units];
if(inPerDisplayUnit) {
var inPerMapUnit = OpenLayers.INCHES_PER_UNIT[geomUnits];
length *= (inPerMapUnit / inPerDisplayUnit);
}
return length;
},
CLASS_NAME: "OpenLayers.Control.Measure"
});

View File

@ -1,738 +0,0 @@
/* Copyright (c) 2006 MetaCarta, Inc., published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt
* for the full text of the license. */
/**
* @requires OpenLayers/Control/DragFeature.js
* @requires OpenLayers/Control/SelectFeature.js
* @requires OpenLayers/Handler/Keyboard.js
*/
/**
* Class: OpenLayers.Control.ModifyFeature
* Control to modify features. When activated, a click renders the vertices
* of a feature - these vertices can then be dragged. By default, the
* delete key will delete the vertex under the mouse. New features are
* added by dragging "virtual vertices" between vertices. Create a new
* control with the <OpenLayers.Control.ModifyFeature> constructor.
*
* Inherits From:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ModifyFeature = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: geometryTypes
* {Array(String)} To restrict modification to a limited set of geometry
* types, send a list of strings corresponding to the geometry class
* names.
*/
geometryTypes: null,
/**
* APIProperty: clickout
* {Boolean} Unselect features when clicking outside any feature.
* Default is true.
*/
clickout: true,
/**
* APIProperty: toggle
* {Boolean} Unselect a selected feature on click.
* Default is true.
*/
toggle: true,
/**
* Property: layer
* {<OpenLayers.Layer.Vector>}
*/
layer: null,
/**
* Property: feature
* {<OpenLayers.Feature.Vector>} Feature currently available for modification.
*/
feature: null,
/**
* Property: vertices
* {Array(<OpenLayers.Feature.Vector>)} Verticies currently available
* for dragging.
*/
vertices: null,
/**
* Property: virtualVertices
* {Array(<OpenLayers.Feature.Vector>)} Virtual vertices in the middle
* of each edge.
*/
virtualVertices: null,
/**
* Property: selectControl
* {<OpenLayers.Control.SelectFeature>}
*/
selectControl: null,
/**
* Property: dragControl
* {<OpenLayers.Control.DragFeature>}
*/
dragControl: null,
/**
* Property: handlers
* {Object}
*/
handlers: null,
/**
* APIProperty: deleteCodes
* {Array(Integer)} Keycodes for deleting verticies. Set to null to disable
* vertex deltion by keypress. If non-null, keypresses with codes
* in this array will delete vertices under the mouse. Default
* is 46 and 68, the 'delete' and lowercase 'd' keys.
*/
deleteCodes: null,
/**
* APIProperty: virtualStyle
* {Object} A symbolizer to be used for virtual vertices.
*/
virtualStyle: null,
/**
* APIProperty: mode
* {Integer} Bitfields specifying the modification mode. Defaults to
* OpenLayers.Control.ModifyFeature.RESHAPE. To set the mode to a
* combination of options, use the | operator. or example, to allow
* the control to both resize and rotate features, use the following
* syntax
* (code)
* control.mode = OpenLayers.Control.ModifyFeature.RESIZE |
* OpenLayers.Control.ModifyFeature.ROTATE;
* (end)
*/
mode: null,
/**
* Property: modified
* {Boolean} The currently selected feature has been modified.
*/
modified: false,
/**
* Property: radiusHandle
* {<OpenLayers.Feature.Vector>} A handle for rotating/resizing a feature.
*/
radiusHandle: null,
/**
* Property: dragHandle
* {<OpenLayers.Feature.Vector>} A handle for dragging a feature.
*/
dragHandle: null,
/**
* APIProperty: onModificationStart
* {Function} *Deprecated*. Register for "beforefeaturemodified" instead.
* The "beforefeaturemodified" event is triggered on the layer before
* any modification begins.
*
* Optional function to be called when a feature is selected
* to be modified. The function should expect to be called with a
* feature. This could be used for example to allow to lock the
* feature on server-side.
*/
onModificationStart: function() {},
/**
* APIProperty: onModification
* {Function} *Deprecated*. Register for "featuremodified" instead.
* The "featuremodified" event is triggered on the layer with each
* feature modification.
*
* Optional function to be called when a feature has been
* modified. The function should expect to be called with a feature.
*/
onModification: function() {},
/**
* APIProperty: onModificationEnd
* {Function} *Deprecated*. Register for "afterfeaturemodified" instead.
* The "afterfeaturemodified" event is triggered on the layer after
* a feature has been modified.
*
* Optional function to be called when a feature is finished
* being modified. The function should expect to be called with a
* feature.
*/
onModificationEnd: function() {},
/**
* Constructor: OpenLayers.Control.ModifyFeature
* Create a new modify feature control.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>} Layer that contains features that
* will be modified.
* options - {Object} Optional object whose properties will be set on the
* control.
*/
initialize: function(layer, options) {
this.layer = layer;
this.vertices = [];
this.virtualVertices = [];
this.virtualStyle = OpenLayers.Util.extend({},
this.layer.style || this.layer.styleMap.createSymbolizer());
this.virtualStyle.fillOpacity = 0.3;
this.virtualStyle.strokeOpacity = 0.3;
this.deleteCodes = [46, 68];
this.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
OpenLayers.Control.prototype.initialize.apply(this, [options]);
if(!(this.deleteCodes instanceof Array)) {
this.deleteCodes = [this.deleteCodes];
}
var control = this;
// configure the select control
var selectOptions = {
geometryTypes: this.geometryTypes,
clickout: this.clickout,
toggle: this.toggle,
onBeforeSelect: this.beforeSelectFeature,
onSelect: this.selectFeature,
onUnselect: this.unselectFeature,
scope: this
};
this.selectControl = new OpenLayers.Control.SelectFeature(
layer, selectOptions
);
// configure the drag control
var dragOptions = {
geometryTypes: ["OpenLayers.Geometry.Point"],
snappingOptions: this.snappingOptions,
onStart: function(feature, pixel) {
control.dragStart.apply(control, [feature, pixel]);
},
onDrag: function(feature, pixel) {
control.dragVertex.apply(control, [feature, pixel]);
},
onComplete: function(feature) {
control.dragComplete.apply(control, [feature]);
}
};
this.dragControl = new OpenLayers.Control.DragFeature(
layer, dragOptions
);
// configure the keyboard handler
var keyboardOptions = {
keydown: this.handleKeypress
};
this.handlers = {
keyboard: new OpenLayers.Handler.Keyboard(this, keyboardOptions)
};
},
/**
* APIMethod: destroy
* Take care of things that are not handled in superclass.
*/
destroy: function() {
this.layer = null;
this.selectControl.destroy();
this.dragControl.destroy();
OpenLayers.Control.prototype.destroy.apply(this, []);
},
/**
* APIMethod: activate
* Activate the control.
*
* Returns:
* {Boolean} Successfully activated the control.
*/
activate: function() {
return (this.selectControl.activate() &&
this.handlers.keyboard.activate() &&
OpenLayers.Control.prototype.activate.apply(this, arguments));
},
/**
* APIMethod: deactivate
* Deactivate the control.
*
* Returns:
* {Boolean} Successfully deactivated the control.
*/
deactivate: function() {
var deactivated = false;
// the return from the controls is unimportant in this case
if(OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
this.layer.removeFeatures(this.vertices, {silent: true});
this.layer.removeFeatures(this.virtualVertices, {silent: true});
this.vertices = [];
this.dragControl.deactivate();
if(this.feature && this.feature.geometry && this.feature.layer) {
this.selectControl.unselect.apply(this.selectControl,
[this.feature]);
}
this.selectControl.deactivate();
this.handlers.keyboard.deactivate();
deactivated = true;
}
return deactivated;
},
/**
* Method: beforeSelectFeature
* Called before a feature is selected.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature about to be selected.
*/
beforeSelectFeature: function(feature) {
return this.layer.events.triggerEvent(
"beforefeaturemodified", {feature: feature}
);
},
/**
* Method: selectFeature
* Called when the select feature control selects a feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} the selected feature.
*/
selectFeature: function(feature) {
this.feature = feature;
this.modified = false;
this.resetVertices();
this.dragControl.activate();
this.onModificationStart(this.feature);
},
/**
* Method: unselectFeature
* Called when the select feature control unselects a feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The unselected feature.
*/
unselectFeature: function(feature) {
this.layer.removeFeatures(this.vertices, {silent: true});
this.vertices = [];
this.layer.destroyFeatures(this.virtualVertices, {silent: true});
this.virtualVertices = [];
if(this.dragHandle) {
this.layer.destroyFeatures([this.dragHandle], {silent: true});
delete this.dragHandle;
}
if(this.radiusHandle) {
this.layer.destroyFeatures([this.radiusHandle], {silent: true});
delete this.radiusHandle;
}
this.feature = null;
this.dragControl.deactivate();
this.onModificationEnd(feature);
this.layer.events.triggerEvent("afterfeaturemodified", {
feature: feature,
modified: this.modified
});
this.modified = false;
},
/**
* Method: dragStart
* Called by the drag feature control with before a feature is dragged.
* This method is used to differentiate between points and vertices
* of higher order geometries. This respects the <geometryTypes>
* property and forces a select of points when the drag control is
* already active (and stops events from propagating to the select
* control).
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The point or vertex about to be
* dragged.
* pixel - {<OpenLayers.Pixel>} Pixel location of the mouse event.
*/
dragStart: function(feature, pixel) {
// only change behavior if the feature is not in the vertices array
if(feature != this.feature && !feature.geometry.parent &&
feature != this.dragHandle && feature != this.radiusHandle) {
if(this.feature) {
// unselect the currently selected feature
this.selectControl.clickFeature.apply(this.selectControl,
[this.feature]);
}
// check any constraints on the geometry type
if(this.geometryTypes == null ||
OpenLayers.Util.indexOf(this.geometryTypes,
feature.geometry.CLASS_NAME) != -1) {
// select the point
this.selectControl.clickFeature.apply(this.selectControl,
[feature]);
/**
* TBD: These lines improve workflow by letting the user
* immediately start dragging after the mouse down.
* However, it is very ugly to be messing with controls
* and their handlers in this way. I'd like a better
* solution if the workflow change is necessary.
*/
// prepare the point for dragging
this.dragControl.overFeature.apply(this.dragControl,
[feature]);
this.dragControl.lastPixel = pixel;
this.dragControl.handlers.drag.started = true;
this.dragControl.handlers.drag.start = pixel;
this.dragControl.handlers.drag.last = pixel;
}
}
},
/**
* Method: dragVertex
* Called by the drag feature control with each drag move of a vertex.
*
* Parameters:
* vertex - {<OpenLayers.Feature.Vector>} The vertex being dragged.
* pixel - {<OpenLayers.Pixel>} Pixel location of the mouse event.
*/
dragVertex: function(vertex, pixel) {
this.modified = true;
/**
* Five cases:
* 1) dragging a simple point
* 2) dragging a virtual vertex
* 3) dragging a drag handle
* 4) dragging a real vertex
* 5) dragging a radius handle
*/
if(this.feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// dragging a simple point
if(this.feature != vertex) {
this.feature = vertex;
}
this.layer.events.triggerEvent("vertexmodified", {
vertex: vertex.geometry,
feature: this.feature,
pixel: pixel
});
} else {
if(vertex._index) {
// dragging a virtual vertex
vertex.geometry.parent.addComponent(vertex.geometry,
vertex._index);
// move from virtual to real vertex
delete vertex._index;
OpenLayers.Util.removeItem(this.virtualVertices, vertex);
this.vertices.push(vertex);
} else if(vertex == this.dragHandle) {
// dragging a drag handle
this.layer.removeFeatures(this.vertices, {silent: true});
this.vertices = [];
if(this.radiusHandle) {
this.layer.destroyFeatures([this.radiusHandle], {silent: true});
this.radiusHandle = null;
}
} else if(vertex !== this.radiusHandle) {
// dragging a real vertex
this.layer.events.triggerEvent("vertexmodified", {
vertex: vertex.geometry,
feature: this.feature,
pixel: pixel
});
}
// dragging a radius handle - no special treatment
if(this.virtualVertices.length > 0) {
this.layer.destroyFeatures(this.virtualVertices, {silent: true});
this.virtualVertices = [];
}
this.layer.drawFeature(this.feature, this.selectControl.renderIntent);
}
// keep the vertex on top so it gets the mouseout after dragging
// this should be removed in favor of an option to draw under or
// maintain node z-index
this.layer.drawFeature(vertex);
},
/**
* Method: dragComplete
* Called by the drag feature control when the feature dragging is complete.
*
* Parameters:
* vertex - {<OpenLayers.Feature.Vector>} The vertex being dragged.
*/
dragComplete: function(vertex) {
this.resetVertices();
this.setFeatureState();
this.onModification(this.feature);
this.layer.events.triggerEvent("featuremodified",
{feature: this.feature});
},
/**
* Method: setFeatureState
* Called when the feature is modified. If the current state is not
* INSERT or DELETE, the state is set to UPDATE.
*/
setFeatureState: function() {
if(this.feature.state != OpenLayers.State.INSERT &&
this.feature.state != OpenLayers.State.DELETE) {
this.feature.state = OpenLayers.State.UPDATE;
}
},
/**
* Method: resetVertices
*/
resetVertices: function() {
// if coming from a drag complete we're about to destroy the vertex
// that was just dragged. For that reason, the drag feature control
// will never detect a mouse-out on that vertex, meaning that the drag
// handler won't be deactivated. This can cause errors because the drag
// feature control still has a feature to drag but that feature is
// destroyed. To prevent this, we call outFeature on the drag feature
// control if the control actually has a feature to drag.
if(this.dragControl.feature) {
this.dragControl.outFeature(this.dragControl.feature);
}
if(this.vertices.length > 0) {
this.layer.removeFeatures(this.vertices, {silent: true});
this.vertices = [];
}
if(this.virtualVertices.length > 0) {
this.layer.removeFeatures(this.virtualVertices, {silent: true});
this.virtualVertices = [];
}
if(this.dragHandle) {
this.layer.destroyFeatures([this.dragHandle], {silent: true});
this.dragHandle = null;
}
if(this.radiusHandle) {
this.layer.destroyFeatures([this.radiusHandle], {silent: true});
this.radiusHandle = null;
}
if(this.feature &&
this.feature.geometry.CLASS_NAME != "OpenLayers.Geometry.Point") {
if((this.mode & OpenLayers.Control.ModifyFeature.DRAG)) {
this.collectDragHandle();
}
if((this.mode & (OpenLayers.Control.ModifyFeature.ROTATE |
OpenLayers.Control.ModifyFeature.RESIZE))) {
this.collectRadiusHandle();
}
if(this.mode & OpenLayers.Control.ModifyFeature.RESHAPE){
// Don't collect vertices when we're resizing
if (!(this.mode & OpenLayers.Control.ModifyFeature.RESIZE)){
this.collectVertices();
}
}
}
},
/**
* Method: handleKeypress
* Called by the feature handler on keypress. This is used to delete
* vertices. If the <deleteCode> property is set, vertices will
* be deleted when a feature is selected for modification and
* the mouse is over a vertex.
*
* Parameters:
* {Integer} Key code corresponding to the keypress event.
*/
handleKeypress: function(evt) {
var code = evt.keyCode;
// check for delete key
if(this.feature &&
OpenLayers.Util.indexOf(this.deleteCodes, code) != -1) {
var vertex = this.dragControl.feature;
if(vertex &&
OpenLayers.Util.indexOf(this.vertices, vertex) != -1 &&
!this.dragControl.handlers.drag.dragging &&
vertex.geometry.parent) {
// remove the vertex
vertex.geometry.parent.removeComponent(vertex.geometry);
this.layer.drawFeature(this.feature,
this.selectControl.renderIntent);
this.resetVertices();
this.setFeatureState();
this.onModification(this.feature);
this.layer.events.triggerEvent("featuremodified",
{feature: this.feature});
}
}
},
/**
* Method: collectVertices
* Collect the vertices from the modifiable feature's geometry and push
* them on to the control's vertices array.
*/
collectVertices: function() {
this.vertices = [];
this.virtualVertices = [];
var control = this;
function collectComponentVertices(geometry) {
var i, vertex, component, len;
if(geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
vertex = new OpenLayers.Feature.Vector(geometry);
vertex._sketch = true;
control.vertices.push(vertex);
} else {
var numVert = geometry.components.length;
if(geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") {
numVert -= 1;
}
for(i=0; i<numVert; ++i) {
component = geometry.components[i];
if(component.CLASS_NAME == "OpenLayers.Geometry.Point") {
vertex = new OpenLayers.Feature.Vector(component);
vertex._sketch = true;
control.vertices.push(vertex);
} else {
collectComponentVertices(component);
}
}
// add virtual vertices in the middle of each edge
if(geometry.CLASS_NAME != "OpenLayers.Geometry.MultiPoint") {
for(i=0, len=geometry.components.length; i<len-1; ++i) {
var prevVertex = geometry.components[i];
var nextVertex = geometry.components[i + 1];
if(prevVertex.CLASS_NAME == "OpenLayers.Geometry.Point" &&
nextVertex.CLASS_NAME == "OpenLayers.Geometry.Point") {
var x = (prevVertex.x + nextVertex.x) / 2;
var y = (prevVertex.y + nextVertex.y) / 2;
var point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(x, y),
null, control.virtualStyle
);
// set the virtual parent and intended index
point.geometry.parent = geometry;
point._index = i + 1;
point._sketch = true;
control.virtualVertices.push(point);
}
}
}
}
}
collectComponentVertices.call(this, this.feature.geometry);
this.layer.addFeatures(this.virtualVertices, {silent: true});
this.layer.addFeatures(this.vertices, {silent: true});
},
/**
* Method: collectDragHandle
* Collect the drag handle for the selected geometry.
*/
collectDragHandle: function() {
var geometry = this.feature.geometry;
var center = geometry.getBounds().getCenterLonLat();
var originGeometry = new OpenLayers.Geometry.Point(
center.lon, center.lat
);
var origin = new OpenLayers.Feature.Vector(originGeometry);
originGeometry.move = function(x, y) {
OpenLayers.Geometry.Point.prototype.move.call(this, x, y);
geometry.move(x, y);
};
origin._sketch = true;
this.dragHandle = origin;
this.layer.addFeatures([this.dragHandle], {silent: true});
},
/**
* Method: collectRadiusHandle
* Collect the radius handle for the selected geometry.
*/
collectRadiusHandle: function() {
var geometry = this.feature.geometry;
var bounds = geometry.getBounds();
var center = bounds.getCenterLonLat();
var originGeometry = new OpenLayers.Geometry.Point(
center.lon, center.lat
);
var radiusGeometry = new OpenLayers.Geometry.Point(
bounds.right, bounds.bottom
);
var radius = new OpenLayers.Feature.Vector(radiusGeometry);
var resize = (this.mode & OpenLayers.Control.ModifyFeature.RESIZE);
var reshape = (this.mode & OpenLayers.Control.ModifyFeature.RESHAPE);
var rotate = (this.mode & OpenLayers.Control.ModifyFeature.ROTATE);
radiusGeometry.move = function(x, y) {
OpenLayers.Geometry.Point.prototype.move.call(this, x, y);
var dx1 = this.x - originGeometry.x;
var dy1 = this.y - originGeometry.y;
var dx0 = dx1 - x;
var dy0 = dy1 - y;
if(rotate) {
var a0 = Math.atan2(dy0, dx0);
var a1 = Math.atan2(dy1, dx1);
var angle = a1 - a0;
angle *= 180 / Math.PI;
geometry.rotate(angle, originGeometry);
}
if(resize) {
var scale, ratio;
// 'resize' together with 'reshape' implies that the aspect
// ratio of the geometry will not be preserved whilst resizing
if (reshape) {
scale = dy1 / dy0;
ratio = (dx1 / dx0) / scale;
} else {
var l0 = Math.sqrt((dx0 * dx0) + (dy0 * dy0));
var l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1));
scale = l1 / l0;
}
geometry.resize(scale, originGeometry, ratio);
}
};
radius._sketch = true;
this.radiusHandle = radius;
this.layer.addFeatures([this.radiusHandle], {silent: true});
},
/**
* Method: setMap
* Set the map property for the control and all handlers.
*
* Parameters:
* map - {<OpenLayers.Map>} The control's map.
*/
setMap: function(map) {
this.selectControl.setMap(map);
this.dragControl.setMap(map);
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
CLASS_NAME: "OpenLayers.Control.ModifyFeature"
});
/**
* Constant: RESHAPE
* {Integer} Constant used to make the control work in reshape mode
*/
OpenLayers.Control.ModifyFeature.RESHAPE = 1;
/**
* Constant: RESIZE
* {Integer} Constant used to make the control work in resize mode
*/
OpenLayers.Control.ModifyFeature.RESIZE = 2;
/**
* Constant: ROTATE
* {Integer} Constant used to make the control work in rotate mode
*/
OpenLayers.Control.ModifyFeature.ROTATE = 4;
/**
* Constant: DRAG
* {Integer} Constant used to make the control work in drag mode
*/
OpenLayers.Control.ModifyFeature.DRAG = 8;

View File

@ -1,367 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.MouseDefaults
* This class is DEPRECATED in 2.4 and will be removed by 3.0.
* If you need this functionality, use <OpenLayers.Control.Navigation>
* instead!!!
*
* This class is DEPRECATED in 2.4 and will be removed by 3.0.
* If you need this functionality, use Control.Navigation instead!!!
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.MouseDefaults = OpenLayers.Class(OpenLayers.Control, {
/** WARNING WARNING WARNING!!!
This class is DEPRECATED in 2.4 and will be removed by 3.0.
If you need this functionality, use Control.Navigation instead!!! */
/**
* Property: performedDrag
* {Boolean}
*/
performedDrag: false,
/**
* Property: wheelObserver
* {Function}
*/
wheelObserver: null,
/**
* Constructor: OpenLayers.Control.MouseDefaults
*/
initialize: function() {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* APIMethod: destroy
*/
destroy: function() {
if (this.handler) {
this.handler.destroy();
}
this.handler = null;
this.map.events.un({
"click": this.defaultClick,
"dblclick": this.defaultDblClick,
"mousedown": this.defaultMouseDown,
"mouseup": this.defaultMouseUp,
"mousemove": this.defaultMouseMove,
"mouseout": this.defaultMouseOut,
scope: this
});
//unregister mousewheel events specifically on the window and document
OpenLayers.Event.stopObserving(window, "DOMMouseScroll",
this.wheelObserver);
OpenLayers.Event.stopObserving(window, "mousewheel",
this.wheelObserver);
OpenLayers.Event.stopObserving(document, "mousewheel",
this.wheelObserver);
this.wheelObserver = null;
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
*/
draw: function() {
this.map.events.on({
"click": this.defaultClick,
"dblclick": this.defaultDblClick,
"mousedown": this.defaultMouseDown,
"mouseup": this.defaultMouseUp,
"mousemove": this.defaultMouseMove,
"mouseout": this.defaultMouseOut,
scope: this
});
this.registerWheelEvents();
},
/**
* Method: registerWheelEvents
*/
registerWheelEvents: function() {
this.wheelObserver = OpenLayers.Function.bindAsEventListener(
this.onWheelEvent, this
);
//register mousewheel events specifically on the window and document
OpenLayers.Event.observe(window, "DOMMouseScroll", this.wheelObserver);
OpenLayers.Event.observe(window, "mousewheel", this.wheelObserver);
OpenLayers.Event.observe(document, "mousewheel", this.wheelObserver);
},
/**
* Method: defaultClick
*
* Parameters:
* evt - {Event}
*
* Returns:
* {Boolean}
*/
defaultClick: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
var notAfterDrag = !this.performedDrag;
this.performedDrag = false;
return notAfterDrag;
},
/**
* Method: defaultDblClick
*
* Parameters:
* evt - {Event}
*/
defaultDblClick: function (evt) {
var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
this.map.setCenter(newCenter, this.map.zoom + 1);
OpenLayers.Event.stop(evt);
return false;
},
/**
* Method: defaultMouseDown
*
* Parameters:
* evt - {Event}
*/
defaultMouseDown: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
this.mouseDragStart = evt.xy.clone();
this.performedDrag = false;
if (evt.shiftKey) {
this.map.div.style.cursor = "crosshair";
this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
this.mouseDragStart,
null,
null,
"absolute",
"2px solid red");
this.zoomBox.style.backgroundColor = "white";
this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
this.zoomBox.style.opacity = "0.50";
this.zoomBox.style.fontSize = "1px";
this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
this.map.viewPortDiv.appendChild(this.zoomBox);
}
document.onselectstart=function() { return false; };
OpenLayers.Event.stop(evt);
},
/**
* Method: defaultMouseMove
*
* Parameters:
* evt - {Event}
*/
defaultMouseMove: function (evt) {
// record the mouse position, used in onWheelEvent
this.mousePosition = evt.xy.clone();
if (this.mouseDragStart != null) {
if (this.zoomBox) {
var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
this.zoomBox.style.width = Math.max(1, deltaX) + "px";
this.zoomBox.style.height = Math.max(1, deltaY) + "px";
if (evt.xy.x < this.mouseDragStart.x) {
this.zoomBox.style.left = evt.xy.x+"px";
}
if (evt.xy.y < this.mouseDragStart.y) {
this.zoomBox.style.top = evt.xy.y+"px";
}
} else {
var deltaX = this.mouseDragStart.x - evt.xy.x;
var deltaY = this.mouseDragStart.y - evt.xy.y;
var size = this.map.getSize();
var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
size.h / 2 + deltaY);
var newCenter = this.map.getLonLatFromViewPortPx( newXY );
this.map.setCenter(newCenter, null, true);
this.mouseDragStart = evt.xy.clone();
this.map.div.style.cursor = "move";
}
this.performedDrag = true;
}
},
/**
* Method: defaultMouseUp
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
defaultMouseUp: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
if (this.zoomBox) {
this.zoomBoxEnd(evt);
} else {
if (this.performedDrag) {
this.map.setCenter(this.map.center);
}
}
document.onselectstart=null;
this.mouseDragStart = null;
this.map.div.style.cursor = "";
},
/**
* Method: defaultMouseOut
*
* Parameters:
* evt - {Event}
*/
defaultMouseOut: function (evt) {
if (this.mouseDragStart != null &&
OpenLayers.Util.mouseLeft(evt, this.map.div)) {
if (this.zoomBox) {
this.removeZoomBox();
}
this.mouseDragStart = null;
}
},
/**
* Method: defaultWheelUp
* User spun scroll wheel up
*
*/
defaultWheelUp: function(evt) {
if (this.map.getZoom() <= this.map.getNumZoomLevels()) {
this.map.setCenter(this.map.getLonLatFromPixel(evt.xy),
this.map.getZoom() + 1);
}
},
/**
* Method: defaultWheelDown
* User spun scroll wheel down
*/
defaultWheelDown: function(evt) {
if (this.map.getZoom() > 0) {
this.map.setCenter(this.map.getLonLatFromPixel(evt.xy),
this.map.getZoom() - 1);
}
},
/**
* Method: zoomBoxEnd
* Zoombox function.
*/
zoomBoxEnd: function(evt) {
if (this.mouseDragStart != null) {
if (Math.abs(this.mouseDragStart.x - evt.xy.x) > 5 ||
Math.abs(this.mouseDragStart.y - evt.xy.y) > 5) {
var start = this.map.getLonLatFromViewPortPx( this.mouseDragStart );
var end = this.map.getLonLatFromViewPortPx( evt.xy );
var top = Math.max(start.lat, end.lat);
var bottom = Math.min(start.lat, end.lat);
var left = Math.min(start.lon, end.lon);
var right = Math.max(start.lon, end.lon);
var bounds = new OpenLayers.Bounds(left, bottom, right, top);
this.map.zoomToExtent(bounds);
} else {
var end = this.map.getLonLatFromViewPortPx( evt.xy );
this.map.setCenter(new OpenLayers.LonLat(
(end.lon),
(end.lat)
), this.map.getZoom() + 1);
}
this.removeZoomBox();
}
},
/**
* Method: removeZoomBox
* Remove the zoombox from the screen and nullify our reference to it.
*/
removeZoomBox: function() {
this.map.viewPortDiv.removeChild(this.zoomBox);
this.zoomBox = null;
},
/**
* Mouse ScrollWheel code thanks to http://adomas.org/javascript-mouse-wheel/
*/
/**
* Method: onWheelEvent
* Catch the wheel event and handle it xbrowserly
*
* Parameters:
* e - {Event}
*/
onWheelEvent: function(e){
// first determine whether or not the wheeling was inside the map
var inMap = false;
var elem = OpenLayers.Event.element(e);
while(elem != null) {
if (this.map && elem == this.map.div) {
inMap = true;
break;
}
elem = elem.parentNode;
}
if (inMap) {
var delta = 0;
if (!e) {
e = window.event;
}
if (e.wheelDelta) {
delta = e.wheelDelta/120;
if (window.opera && window.opera.version() < 9.2) {
delta = -delta;
}
} else if (e.detail) {
delta = -e.detail / 3;
}
if (delta) {
// add the mouse position to the event because mozilla has a bug
// with clientX and clientY (see https://bugzilla.mozilla.org/show_bug.cgi?id=352179)
// getLonLatFromViewPortPx(e) returns wrong values
e.xy = this.mousePosition;
if (delta < 0) {
this.defaultWheelDown(e);
} else {
this.defaultWheelUp(e);
}
}
//only wheel the map, not the window
OpenLayers.Event.stop(e);
}
},
CLASS_NAME: "OpenLayers.Control.MouseDefaults"
});

View File

@ -1,171 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.MousePosition
* The MousePosition control displays geographic coordinates of the mouse
* pointer, as it is moved about the map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.MousePosition = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: element
* {DOMElement}
*/
element: null,
/**
* APIProperty: prefix
* {String}
*/
prefix: '',
/**
* APIProperty: separator
* {String}
*/
separator: ', ',
/**
* APIProperty: suffix
* {String}
*/
suffix: '',
/**
* APIProperty: numDigits
* {Integer}
*/
numDigits: 5,
/**
* APIProperty: granularity
* {Integer}
*/
granularity: 10,
/**
* Property: lastXy
* {<OpenLayers.Pixel>}
*/
lastXy: null,
/**
* APIProperty: displayProjection
* {<OpenLayers.Projection>} The projection in which the
* mouse position is displayed
*/
displayProjection: null,
/**
* Constructor: OpenLayers.Control.MousePosition
*
* Parameters:
* options - {Object} Options for control.
*/
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* Method: destroy
*/
destroy: function() {
if (this.map) {
this.map.events.unregister('mousemove', this, this.redraw);
}
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if (!this.element) {
this.div.left = "";
this.div.top = "";
this.element = this.div;
}
this.redraw();
return this.div;
},
/**
* Method: redraw
*/
redraw: function(evt) {
var lonLat;
if (evt == null) {
lonLat = new OpenLayers.LonLat(0, 0);
} else {
if (this.lastXy == null ||
Math.abs(evt.xy.x - this.lastXy.x) > this.granularity ||
Math.abs(evt.xy.y - this.lastXy.y) > this.granularity)
{
this.lastXy = evt.xy;
return;
}
lonLat = this.map.getLonLatFromPixel(evt.xy);
if (!lonLat) {
// map has not yet been properly initialized
return;
}
if (this.displayProjection) {
lonLat.transform(this.map.getProjectionObject(),
this.displayProjection );
}
this.lastXy = evt.xy;
}
var newHtml = this.formatOutput(lonLat);
if (newHtml != this.element.innerHTML) {
this.element.innerHTML = newHtml;
}
},
/**
* Method: formatOutput
* Override to provide custom display output
*
* Parameters:
* lonLat - {<OpenLayers.LonLat>} Location to display
*/
formatOutput: function(lonLat) {
var digits = parseInt(this.numDigits);
var newHtml =
this.prefix +
lonLat.lon.toFixed(digits) +
this.separator +
lonLat.lat.toFixed(digits) +
this.suffix;
return newHtml;
},
/**
* Method: setMap
*/
setMap: function() {
OpenLayers.Control.prototype.setMap.apply(this, arguments);
this.map.events.register( 'mousemove', this, this.redraw);
},
CLASS_NAME: "OpenLayers.Control.MousePosition"
});

View File

@ -1,405 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Control/MouseDefaults.js
*/
/**
* Class: OpenLayers.Control.MouseToolbar
* This class is DEPRECATED in 2.4 and will be removed by 3.0.
* If you need this functionality, use <OpenLayers.Control.NavToolbar>
* instead!!!
*/
OpenLayers.Control.MouseToolbar = OpenLayers.Class(
OpenLayers.Control.MouseDefaults, {
/**
* Property: mode
*/
mode: null,
/**
* Property: buttons
*/
buttons: null,
/**
* APIProperty: direction
* {String} 'vertical' or 'horizontal'
*/
direction: "vertical",
/**
* Property: buttonClicked
* {String}
*/
buttonClicked: null,
/**
* Constructor: OpenLayers.Control.MouseToolbar
*
* Parameters:
* position - {<OpenLayers.Pixel>}
* direction - {String}
*/
initialize: function(position, direction) {
OpenLayers.Control.prototype.initialize.apply(this, arguments);
this.position = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,
OpenLayers.Control.MouseToolbar.Y);
if (position) {
this.position = position;
}
if (direction) {
this.direction = direction;
}
this.measureDivs = [];
},
/**
* APIMethod: destroy
*/
destroy: function() {
for( var btnId in this.buttons) {
var btn = this.buttons[btnId];
btn.map = null;
btn.events.destroy();
}
OpenLayers.Control.MouseDefaults.prototype.destroy.apply(this,
arguments);
},
/**
* Method: draw
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
OpenLayers.Control.MouseDefaults.prototype.draw.apply(this, arguments);
this.buttons = {};
var sz = new OpenLayers.Size(28,28);
var centered = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,0);
this._addButton("zoombox", "drag-rectangle-off.png", "drag-rectangle-on.png", centered, sz, "Shift->Drag to zoom to area");
centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
this._addButton("pan", "panning-hand-off.png", "panning-hand-on.png", centered, sz, "Drag the map to pan.");
centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
this.switchModeTo("pan");
return this.div;
},
/**
* Method: _addButton
*/
_addButton:function(id, img, activeImg, xy, sz, title) {
var imgLocation = OpenLayers.Util.getImagesLocation() + img;
var activeImgLocation = OpenLayers.Util.getImagesLocation() + activeImg;
// var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz);
var btn = OpenLayers.Util.createAlphaImageDiv(
"OpenLayers_Control_MouseToolbar_" + id,
xy, sz, imgLocation, "absolute");
//we want to add the outer div
this.div.appendChild(btn);
btn.imgLocation = imgLocation;
btn.activeImgLocation = activeImgLocation;
btn.events = new OpenLayers.Events(this, btn, null, true);
btn.events.on({
"mousedown": this.buttonDown,
"mouseup": this.buttonUp,
"dblclick": OpenLayers.Event.stop,
scope: this
});
btn.action = id;
btn.title = title;
btn.alt = title;
btn.map = this.map;
//we want to remember/reference the outer div
this.buttons[id] = btn;
return btn;
},
/**
* Method: buttonDown
*
* Parameters:
* evt - {Event}
*/
buttonDown: function(evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
this.buttonClicked = evt.element.action;
OpenLayers.Event.stop(evt);
},
/**
* Method: buttonUp
*
* Parameters:
* evt - {Event}
*/
buttonUp: function(evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
if (this.buttonClicked != null) {
if (this.buttonClicked == evt.element.action) {
this.switchModeTo(evt.element.action);
}
OpenLayers.Event.stop(evt);
this.buttonClicked = null;
}
},
/**
* Method: defaultDblClick
*
* Parameters:
* evt - {Event}
*/
defaultDblClick: function (evt) {
this.switchModeTo("pan");
this.performedDrag = false;
var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
this.map.setCenter(newCenter, this.map.zoom + 1);
OpenLayers.Event.stop(evt);
return false;
},
/**
* Method: defaultMouseDown
*
* Parameters:
* evt - {Event}
*/
defaultMouseDown: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
this.mouseDragStart = evt.xy.clone();
this.performedDrag = false;
this.startViaKeyboard = false;
if (evt.shiftKey && this.mode !="zoombox") {
this.switchModeTo("zoombox");
this.startViaKeyboard = true;
} else if (evt.altKey && this.mode !="measure") {
this.switchModeTo("measure");
} else if (!this.mode) {
this.switchModeTo("pan");
}
switch (this.mode) {
case "zoombox":
this.map.div.style.cursor = "crosshair";
this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
this.mouseDragStart,
null,
null,
"absolute",
"2px solid red");
this.zoomBox.style.backgroundColor = "white";
this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
this.zoomBox.style.opacity = "0.50";
this.zoomBox.style.fontSize = "1px";
this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
this.map.viewPortDiv.appendChild(this.zoomBox);
this.performedDrag = true;
break;
case "measure":
var distance = "";
if (this.measureStart) {
var measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
distance = Math.round(distance * 100) / 100;
distance = distance + "km";
this.measureStartBox = this.measureBox;
}
this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
this.measureBox = OpenLayers.Util.createDiv(null,
this.mouseDragStart.add(
-2-parseInt(this.map.layerContainerDiv.style.left),
-2-parseInt(this.map.layerContainerDiv.style.top)),
null,
null,
"absolute");
this.measureBox.style.width="4px";
this.measureBox.style.height="4px";
this.measureBox.style.fontSize = "1px";
this.measureBox.style.backgroundColor="red";
this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
this.map.layerContainerDiv.appendChild(this.measureBox);
if (distance) {
this.measureBoxDistance = OpenLayers.Util.createDiv(null,
this.mouseDragStart.add(
-2-parseInt(this.map.layerContainerDiv.style.left),
2-parseInt(this.map.layerContainerDiv.style.top)),
null,
null,
"absolute");
this.measureBoxDistance.innerHTML = distance;
this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
this.measureDivs.push(this.measureBoxDistance);
}
this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
this.map.layerContainerDiv.appendChild(this.measureBox);
this.measureDivs.push(this.measureBox);
break;
default:
this.map.div.style.cursor = "move";
break;
}
document.onselectstart = function() { return false; };
OpenLayers.Event.stop(evt);
},
/**
* Method: switchModeTo
*
* Parameters:
* mode - {String}
*/
switchModeTo: function(mode) {
if (mode != this.mode) {
if (this.mode && this.buttons[this.mode]) {
OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode], null, null, null, this.buttons[this.mode].imgLocation);
}
if (this.mode == "measure" && mode != "measure") {
for(var i=0, len=this.measureDivs.length; i<len; i++) {
if (this.measureDivs[i]) {
this.map.layerContainerDiv.removeChild(this.measureDivs[i]);
}
}
this.measureDivs = [];
this.measureStart = null;
}
this.mode = mode;
if (this.buttons[mode]) {
OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode], null, null, null, this.buttons[mode].activeImgLocation);
}
switch (this.mode) {
case "zoombox":
this.map.div.style.cursor = "crosshair";
break;
default:
this.map.div.style.cursor = "";
break;
}
}
},
/**
* Method: leaveMode
*/
leaveMode: function() {
this.switchModeTo("pan");
},
/**
* Method: defaultMouseMove
*
* Parameters:
* evt - {Event}
*/
defaultMouseMove: function (evt) {
if (this.mouseDragStart != null) {
switch (this.mode) {
case "zoombox":
var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
this.zoomBox.style.width = Math.max(1, deltaX) + "px";
this.zoomBox.style.height = Math.max(1, deltaY) + "px";
if (evt.xy.x < this.mouseDragStart.x) {
this.zoomBox.style.left = evt.xy.x+"px";
}
if (evt.xy.y < this.mouseDragStart.y) {
this.zoomBox.style.top = evt.xy.y+"px";
}
break;
default:
var deltaX = this.mouseDragStart.x - evt.xy.x;
var deltaY = this.mouseDragStart.y - evt.xy.y;
var size = this.map.getSize();
var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
size.h / 2 + deltaY);
var newCenter = this.map.getLonLatFromViewPortPx( newXY );
this.map.setCenter(newCenter, null, true);
this.mouseDragStart = evt.xy.clone();
}
this.performedDrag = true;
}
},
/**
* Method: defaultMouseUp
*
* Parameters:
* evt - {Event}
*/
defaultMouseUp: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
switch (this.mode) {
case "zoombox":
this.zoomBoxEnd(evt);
if (this.startViaKeyboard) {
this.leaveMode();
}
break;
case "pan":
if (this.performedDrag) {
this.map.setCenter(this.map.center);
}
}
document.onselectstart = null;
this.mouseDragStart = null;
this.map.div.style.cursor = "default";
},
/**
* Method: defaultMouseOut
*
* Parameters:
* evt - {Event}
*/
defaultMouseOut: function (evt) {
if (this.mouseDragStart != null
&& OpenLayers.Util.mouseLeft(evt, this.map.div)) {
if (this.zoomBox) {
this.removeZoomBox();
if (this.startViaKeyboard) {
this.leaveMode();
}
}
this.mouseDragStart = null;
this.map.div.style.cursor = "default";
}
},
/**
* Method: defaultClick
*
* Parameters:
* evt - {Event}
*/
defaultClick: function (evt) {
if (this.performedDrag) {
this.performedDrag = false;
return false;
}
},
CLASS_NAME: "OpenLayers.Control.MouseToolbar"
});
OpenLayers.Control.MouseToolbar.X = 6;
OpenLayers.Control.MouseToolbar.Y = 300;

View File

@ -1,54 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control/Panel.js
* @requires OpenLayers/Control/Navigation.js
* @requires OpenLayers/Control/ZoomBox.js
*/
/**
* Class: OpenLayers.Control.NavToolbar
* This Toolbar is an alternative to the Navigation control that displays
* the state of the control, and provides a UI for changing state to
* use the zoomBox via a Panel control.
*
* If you wish to change the properties of the Navigation control used
* in the NavToolbar, see:
* http://trac.openlayers.org/wiki/Toolbars#SubclassingNavToolbar
*
*
* Inherits from:
* - <OpenLayers.Control.Panel>
*/
OpenLayers.Control.NavToolbar = OpenLayers.Class(OpenLayers.Control.Panel, {
/**
* Constructor: OpenLayers.Control.NavToolbar
* Add our two mousedefaults controls.
*
* Parameters:
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function(options) {
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls([
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.ZoomBox()
]);
},
/**
* Method: draw
* calls the default draw, and then activates mouse defaults.
*/
draw: function() {
var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
this.activateControl(this.controls[0]);
return div;
},
CLASS_NAME: "OpenLayers.Control.NavToolbar"
});

View File

@ -1,247 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control/ZoomBox.js
* @requires OpenLayers/Control/DragPan.js
* @requires OpenLayers/Handler/MouseWheel.js
* @requires OpenLayers/Handler/Click.js
*/
/**
* Class: OpenLayers.Control.Navigation
* The navigation control handles map browsing with mouse events (dragging,
* double-clicking, and scrolling the wheel). Create a new navigation
* control with the <OpenLayers.Control.Navigation> control.
*
* Note that this control is added to the map by default (if no controls
* array is sent in the options object to the <OpenLayers.Map>
* constructor).
*
* Inherits:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: dragPan
* {<OpenLayers.Control.DragPan>}
*/
dragPan: null,
/**
* APIProprety: dragPanOptions
* {Object} Options passed to the DragPan control.
*/
dragPanOptions: null,
/**
* Property: zoomBox
* {<OpenLayers.Control.ZoomBox>}
*/
zoomBox: null,
/**
* APIProperty: zoomWheelEnabled
* {Boolean} Whether the mousewheel should zoom the map
*/
zoomWheelEnabled: true,
/**
* APIProperty: handleRightClicks
* {Boolean} Whether or not to handle right clicks. Default is false.
*/
handleRightClicks: false,
/**
* APIProperty: zoomBoxKeyMask
* {Integer} <OpenLayers.Handler> key code of the key, which has to be
* pressed, while drawing the zoom box with the mouse on the screen.
* You should probably set handleRightClicks to true if you use this
* with MOD_CTRL, to disable the context menu for machines which use
* CTRL-Click as a right click.
* Default: <OpenLayers.Handler.MOD_SHIFT
*/
zoomBoxKeyMask: OpenLayers.Handler.MOD_SHIFT,
/**
* Constructor: OpenLayers.Control.Navigation
* Create a new navigation control
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* the control
*/
initialize: function(options) {
this.handlers = {};
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* Method: destroy
* The destroy method is used to perform any clean up before the control
* is dereferenced. Typically this is where event listeners are removed
* to prevent memory leaks.
*/
destroy: function() {
this.deactivate();
if (this.dragPan) {
this.dragPan.destroy();
}
this.dragPan = null;
if (this.zoomBox) {
this.zoomBox.destroy();
}
this.zoomBox = null;
OpenLayers.Control.prototype.destroy.apply(this,arguments);
},
/**
* Method: activate
*/
activate: function() {
this.dragPan.activate();
if (this.zoomWheelEnabled) {
this.handlers.wheel.activate();
}
this.handlers.click.activate();
this.zoomBox.activate();
return OpenLayers.Control.prototype.activate.apply(this,arguments);
},
/**
* Method: deactivate
*/
deactivate: function() {
this.zoomBox.deactivate();
this.dragPan.deactivate();
this.handlers.click.deactivate();
this.handlers.wheel.deactivate();
return OpenLayers.Control.prototype.deactivate.apply(this,arguments);
},
/**
* Method: draw
*/
draw: function() {
// disable right mouse context menu for support of right click events
if (this.handleRightClicks) {
this.map.viewPortDiv.oncontextmenu = function () { return false;};
}
var clickCallbacks = {
'dblclick': this.defaultDblClick,
'dblrightclick': this.defaultDblRightClick
};
var clickOptions = {
'double': true,
'stopDouble': true
};
this.handlers.click = new OpenLayers.Handler.Click(
this, clickCallbacks, clickOptions
);
this.dragPan = new OpenLayers.Control.DragPan(
OpenLayers.Util.extend({map: this.map}, this.dragPanOptions)
);
this.zoomBox = new OpenLayers.Control.ZoomBox(
{map: this.map, keyMask: this.zoomBoxKeyMask});
this.dragPan.draw();
this.zoomBox.draw();
this.handlers.wheel = new OpenLayers.Handler.MouseWheel(
this, {"up" : this.wheelUp,
"down": this.wheelDown} );
this.activate();
},
/**
* Method: defaultDblClick
*
* Parameters:
* evt - {Event}
*/
defaultDblClick: function (evt) {
var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
this.map.setCenter(newCenter, this.map.zoom + 1);
},
/**
* Method: defaultDblRightClick
*
* Parameters:
* evt - {Event}
*/
defaultDblRightClick: function (evt) {
var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
this.map.setCenter(newCenter, this.map.zoom - 1);
},
/**
* Method: wheelChange
*
* Parameters:
* evt - {Event}
* deltaZ - {Integer}
*/
wheelChange: function(evt, deltaZ) {
var newZoom = this.map.getZoom() + deltaZ;
if (!this.map.isValidZoomLevel(newZoom)) {
return;
}
var size = this.map.getSize();
var deltaX = size.w/2 - evt.xy.x;
var deltaY = evt.xy.y - size.h/2;
var newRes = this.map.baseLayer.getResolutionForZoom(newZoom);
var zoomPoint = this.map.getLonLatFromPixel(evt.xy);
var newCenter = new OpenLayers.LonLat(
zoomPoint.lon + deltaX * newRes,
zoomPoint.lat + deltaY * newRes );
this.map.setCenter( newCenter, newZoom );
},
/**
* Method: wheelUp
* User spun scroll wheel up
*
* Parameters:
* evt - {Event}
*/
wheelUp: function(evt) {
this.wheelChange(evt, 1);
},
/**
* Method: wheelDown
* User spun scroll wheel down
*
* Parameters:
* evt - {Event}
*/
wheelDown: function(evt) {
this.wheelChange(evt, -1);
},
/**
* Method: disableZoomWheel
*/
disableZoomWheel : function() {
this.zoomWheelEnabled = false;
this.handlers.wheel.deactivate();
},
/**
* Method: enableZoomWheel
*/
enableZoomWheel : function() {
this.zoomWheelEnabled = true;
if (this.active) {
this.handlers.wheel.activate();
}
},
CLASS_NAME: "OpenLayers.Control.Navigation"
});

View File

@ -1,399 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Control/Button.js
*/
/**
* Class: OpenLayers.Control.NavigationHistory
* A navigation history control. This is a meta-control, that creates two
* dependent controls: <previous> and <next>. Call the trigger method
* on the <previous> and <next> controls to restore previous and next
* history states. The previous and next controls will become active
* when there are available states to restore and will become deactive
* when there are no states to restore.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.NavigationHistory = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {String} Note that this control is not intended to be added directly
* to a control panel. Instead, add the sub-controls previous and
* next. These sub-controls are button type controls that activate
* and deactivate themselves. If this parent control is added to
* a panel, it will act as a toggle.
*/
type: OpenLayers.Control.TYPE_TOGGLE,
/**
* APIProperty: previous
* {<OpenLayers.Control>} A button type control whose trigger method restores
* the previous state managed by this control.
*/
previous: null,
/**
* APIProperty: previousOptions
* {Object} Set this property on the options argument of the constructor
* to set optional properties on the <previous> control.
*/
previousOptions: null,
/**
* APIProperty: next
* {<OpenLayers.Control>} A button type control whose trigger method restores
* the next state managed by this control.
*/
next: null,
/**
* APIProperty: nextOptions
* {Object} Set this property on the options argument of the constructor
* to set optional properties on the <next> control.
*/
nextOptions: null,
/**
* APIProperty: limit
* {Integer} Optional limit on the number of history items to retain. If
* null, there is no limit. Default is 50.
*/
limit: 50,
/**
* Property: activateOnDraw
* {Boolean} Activate the control when it is first added to the map.
* Default is true.
*/
activateOnDraw: true,
/**
* Property: clearOnDeactivate
* {Boolean} Clear the history when the control is deactivated. Default
* is false.
*/
clearOnDeactivate: false,
/**
* Property: registry
* {Object} An object with keys corresponding to event types. Values
* are functions that return an object representing the current state.
*/
registry: null,
/**
* Property: nextStack
* {Array} Array of items in the history.
*/
nextStack: null,
/**
* Property: previousStack
* {Array} List of items in the history. First item represents the current
* state.
*/
previousStack: null,
/**
* Property: listeners
* {Object} An object containing properties corresponding to event types.
* This object is used to configure the control and is modified on
* construction.
*/
listeners: null,
/**
* Property: restoring
* {Boolean} Currently restoring a history state. This is set to true
* before calling restore and set to false after restore returns.
*/
restoring: false,
/**
* Constructor: OpenLayers.Control.NavigationHistory
*
* 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.registry = OpenLayers.Util.extend({
"moveend": function() {
return {
center: this.map.getCenter(),
resolution: this.map.getResolution()
};
}
}, this.registry);
this.clear();
var previousOptions = {
trigger: OpenLayers.Function.bind(this.previousTrigger, this),
displayClass: this.displayClass + " " + this.displayClass + "Previous"
};
OpenLayers.Util.extend(previousOptions, this.previousOptions);
this.previous = new OpenLayers.Control.Button(previousOptions);
var nextOptions = {
trigger: OpenLayers.Function.bind(this.nextTrigger, this),
displayClass: this.displayClass + " " + this.displayClass + "Next"
};
OpenLayers.Util.extend(nextOptions, this.nextOptions);
this.next = new OpenLayers.Control.Button(nextOptions);
},
/**
* Method: onPreviousChange
* Called when the previous history stack changes.
*
* Parameters:
* state - {Object} An object representing the state to be restored
* if previous is triggered again or null if no previous states remain.
* length - {Integer} The number of remaining previous states that can
* be restored.
*/
onPreviousChange: function(state, length) {
if(state && !this.previous.active) {
this.previous.activate();
} else if(!state && this.previous.active) {
this.previous.deactivate();
}
},
/**
* Method: onNextChange
* Called when the next history stack changes.
*
* Parameters:
* state - {Object} An object representing the state to be restored
* if next is triggered again or null if no next states remain.
* length - {Integer} The number of remaining next states that can
* be restored.
*/
onNextChange: function(state, length) {
if(state && !this.next.active) {
this.next.activate();
} else if(!state && this.next.active) {
this.next.deactivate();
}
},
/**
* APIMethod: destroy
* Destroy the control.
*/
destroy: function() {
OpenLayers.Control.prototype.destroy.apply(this);
this.previous.destroy();
this.next.destroy();
this.deactivate();
for(var prop in this) {
this[prop] = null;
}
},
/**
* Method: setMap
* Set the map property for the control and <previous> and <next> child
* controls.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
this.map = map;
this.next.setMap(map);
this.previous.setMap(map);
},
/**
* Method: draw
* Called when the control is added to the map.
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
this.next.draw();
this.previous.draw();
if(this.activateOnDraw) {
this.activate();
}
},
/**
* Method: previousTrigger
* Restore the previous state. If no items are in the previous history
* stack, this has no effect.
*
* Returns:
* {Object} Item representing state that was restored. Undefined if no
* items are in the previous history stack.
*/
previousTrigger: function() {
var current = this.previousStack.shift();
var state = this.previousStack.shift();
if(state != undefined) {
this.nextStack.unshift(current);
this.previousStack.unshift(state);
this.restoring = true;
this.restore(state);
this.restoring = false;
this.onNextChange(this.nextStack[0], this.nextStack.length);
this.onPreviousChange(
this.previousStack[1], this.previousStack.length - 1
);
} else {
this.previousStack.unshift(current);
}
return state;
},
/**
* APIMethod: nextTrigger
* Restore the next state. If no items are in the next history
* stack, this has no effect. The next history stack is populated
* as states are restored from the previous history stack.
*
* Returns:
* {Object} Item representing state that was restored. Undefined if no
* items are in the next history stack.
*/
nextTrigger: function() {
var state = this.nextStack.shift();
if(state != undefined) {
this.previousStack.unshift(state);
this.restoring = true;
this.restore(state);
this.restoring = false;
this.onNextChange(this.nextStack[0], this.nextStack.length);
this.onPreviousChange(
this.previousStack[1], this.previousStack.length - 1
);
}
return state;
},
/**
* APIMethod: clear
* Clear history.
*/
clear: function() {
this.previousStack = [];
this.nextStack = [];
},
/**
* Method: restore
* Update the state with the given object.
*
* Parameters:
* state - {Object} An object representing the state to restore.
*/
restore: function(state) {
var zoom = this.map.getZoomForResolution(state.resolution);
this.map.setCenter(state.center, zoom);
},
/**
* Method: setListeners
* Sets functions to be registered in the listeners object.
*/
setListeners: function() {
this.listeners = {};
for(var type in this.registry) {
this.listeners[type] = OpenLayers.Function.bind(function() {
if(!this.restoring) {
var state = this.registry[type].apply(this, arguments);
this.previousStack.unshift(state);
if(this.previousStack.length > 1) {
this.onPreviousChange(
this.previousStack[1], this.previousStack.length - 1
);
}
if(this.previousStack.length > (this.limit + 1)) {
this.previousStack.pop();
}
if(this.nextStack.length > 0) {
this.nextStack = [];
this.onNextChange(null, 0);
}
}
return true;
}, this);
}
},
/**
* APIMethod: activate
* Activate the control. This registers any listeners.
*
* Returns:
* {Boolean} Control successfully activated.
*/
activate: function() {
var activated = false;
if(this.map) {
if(OpenLayers.Control.prototype.activate.apply(this)) {
if(this.listeners == null) {
this.setListeners();
}
for(var type in this.listeners) {
this.map.events.register(type, this, this.listeners[type]);
}
activated = true;
if(this.previousStack.length == 0) {
this.initStack();
}
}
}
return activated;
},
/**
* Method: initStack
* Called after the control is activated if the previous history stack is
* empty.
*/
initStack: function() {
if(this.map.getCenter()) {
this.listeners.moveend();
}
},
/**
* APIMethod: deactivate
* Deactivate the control. This unregisters any listeners.
*
* Returns:
* {Boolean} Control successfully deactivated.
*/
deactivate: function() {
var deactivated = false;
if(this.map) {
if(OpenLayers.Control.prototype.deactivate.apply(this)) {
for(var type in this.listeners) {
this.map.events.unregister(
type, this, this.listeners[type]
);
}
if(this.clearOnDeactivate) {
this.clear();
}
deactivated = true;
}
}
return deactivated;
},
CLASS_NAME: "OpenLayers.Control.NavigationHistory"
});

View File

@ -1,700 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/BaseTypes.js
* @requires OpenLayers/Events.js
*/
/**
* Class: OpenLayers.Control.OverviewMap
* The OverMap control creates a small overview map, useful to display the
* extent of a zoomed map and your main map and provide additional
* navigation options to the User. By default the overview map is drawn in
* the lower right corner of the main map. Create a new overview map with the
* <OpenLayers.Control.OverviewMap> constructor.
*
* Inerits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.OverviewMap = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: element
* {DOMElement} The DOM element that contains the overview map
*/
element: null,
/**
* APIProperty: ovmap
* {<OpenLayers.Map>} A reference to the overview map itself.
*/
ovmap: null,
/**
* APIProperty: size
* {<OpenLayers.Size>} The overvew map size in pixels. Note that this is
* the size of the map itself - the element that contains the map (default
* class name olControlOverviewMapElement) may have padding or other style
* attributes added via CSS.
*/
size: new OpenLayers.Size(180, 90),
/**
* APIProperty: layers
* {Array(<OpenLayers.Layer>)} Ordered list of layers in the overview map.
* If none are sent at construction, the base layer for the main map is used.
*/
layers: null,
/**
* APIProperty: minRectSize
* {Integer} The minimum width or height (in pixels) of the extent
* rectangle on the overview map. When the extent rectangle reaches
* this size, it will be replaced depending on the value of the
* <minRectDisplayClass> property. Default is 15 pixels.
*/
minRectSize: 15,
/**
* APIProperty: minRectDisplayClass
* {String} Replacement style class name for the extent rectangle when
* <minRectSize> is reached. This string will be suffixed on to the
* displayClass. Default is "RectReplacement".
*
* Example CSS declaration:
* (code)
* .olControlOverviewMapRectReplacement {
* overflow: hidden;
* cursor: move;
* background-image: url("img/overview_replacement.gif");
* background-repeat: no-repeat;
* background-position: center;
* }
* (end)
*/
minRectDisplayClass: "RectReplacement",
/**
* APIProperty: minRatio
* {Float} The ratio of the overview map resolution to the main map
* resolution at which to zoom farther out on the overview map.
*/
minRatio: 8,
/**
* APIProperty: maxRatio
* {Float} The ratio of the overview map resolution to the main map
* resolution at which to zoom farther in on the overview map.
*/
maxRatio: 32,
/**
* APIProperty: mapOptions
* {Object} An object containing any non-default properties to be sent to
* the overview map's map constructor. These should include any
* non-default options that the main map was constructed with.
*/
mapOptions: null,
/**
* APIProperty: autoPan
* {Boolean} Always pan the overview map, so the extent marker remains in
* the center. Default is false. If true, when you drag the extent
* marker, the overview map will update itself so the marker returns
* to the center.
*/
autoPan: false,
/**
* Property: handlers
* {Object}
*/
handlers: null,
/**
* Property: resolutionFactor
* {Object}
*/
resolutionFactor: 1,
/**
* Constructor: OpenLayers.Control.OverviewMap
* Create a new overview map
*
* Parameters:
* object - {Object} Properties of this object will be set on the overview
* map object. Note, to set options on the map object contained in this
* control, set <mapOptions> as one of the options properties.
*/
initialize: function(options) {
this.layers = [];
this.handlers = {};
OpenLayers.Control.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: destroy
* Deconstruct the control
*/
destroy: function() {
if (!this.mapDiv) { // we've already been destroyed
return;
}
this.handlers.click.destroy();
this.mapDiv.removeChild(this.extentRectangle);
this.extentRectangle = null;
this.rectEvents.destroy();
this.rectEvents = null;
this.ovmap.destroy();
this.ovmap = null;
this.element.removeChild(this.mapDiv);
this.mapDiv = null;
this.div.removeChild(this.element);
this.element = null;
if (this.maximizeDiv) {
OpenLayers.Event.stopObservingElement(this.maximizeDiv);
this.div.removeChild(this.maximizeDiv);
this.maximizeDiv = null;
}
if (this.minimizeDiv) {
OpenLayers.Event.stopObservingElement(this.minimizeDiv);
this.div.removeChild(this.minimizeDiv);
this.minimizeDiv = null;
}
this.map.events.un({
"moveend": this.update,
"changebaselayer": this.baseLayerDraw,
scope: this
});
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Render the control in the browser.
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if(!(this.layers.length > 0)) {
if (this.map.baseLayer) {
var layer = this.map.baseLayer.clone();
this.layers = [layer];
} else {
this.map.events.register("changebaselayer", this, this.baseLayerDraw);
return this.div;
}
}
// create overview map DOM elements
this.element = document.createElement('div');
this.element.className = this.displayClass + 'Element';
this.element.style.display = 'none';
this.mapDiv = document.createElement('div');
this.mapDiv.style.width = this.size.w + 'px';
this.mapDiv.style.height = this.size.h + 'px';
this.mapDiv.style.position = 'relative';
this.mapDiv.style.overflow = 'hidden';
this.mapDiv.id = OpenLayers.Util.createUniqueID('overviewMap');
this.extentRectangle = document.createElement('div');
this.extentRectangle.style.position = 'absolute';
this.extentRectangle.style.zIndex = 1000; //HACK
this.extentRectangle.className = this.displayClass+'ExtentRectangle';
this.mapDiv.appendChild(this.extentRectangle);
this.element.appendChild(this.mapDiv);
this.div.appendChild(this.element);
// Optionally add min/max buttons if the control will go in the
// map viewport.
if(!this.outsideViewport) {
this.div.className += " " + this.displayClass + 'Container';
var imgLocation = OpenLayers.Util.getImagesLocation();
// maximize button div
var img = imgLocation + 'layer-switcher-maximize.png';
this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(
this.displayClass + 'MaximizeButton',
null,
new OpenLayers.Size(18,18),
img,
'absolute');
this.maximizeDiv.style.display = 'none';
this.maximizeDiv.className = this.displayClass + 'MaximizeButton';
OpenLayers.Event.observe(this.maximizeDiv, 'click',
OpenLayers.Function.bindAsEventListener(this.maximizeControl,
this)
);
this.div.appendChild(this.maximizeDiv);
// minimize button div
var img = imgLocation + 'layer-switcher-minimize.png';
this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv(
'OpenLayers_Control_minimizeDiv',
null,
new OpenLayers.Size(18,18),
img,
'absolute');
this.minimizeDiv.style.display = 'none';
this.minimizeDiv.className = this.displayClass + 'MinimizeButton';
OpenLayers.Event.observe(this.minimizeDiv, 'click',
OpenLayers.Function.bindAsEventListener(this.minimizeControl,
this)
);
this.div.appendChild(this.minimizeDiv);
var eventsToStop = ['dblclick','mousedown'];
for (var i=0, len=eventsToStop.length; i<len; i++) {
OpenLayers.Event.observe(this.maximizeDiv,
eventsToStop[i],
OpenLayers.Event.stop);
OpenLayers.Event.observe(this.minimizeDiv,
eventsToStop[i],
OpenLayers.Event.stop);
}
this.minimizeControl();
} else {
// show the overview map
this.element.style.display = '';
}
if(this.map.getExtent()) {
this.update();
}
this.map.events.register('moveend', this, this.update);
return this.div;
},
/**
* Method: baseLayerDraw
* Draw the base layer - called if unable to complete in the initial draw
*/
baseLayerDraw: function() {
this.draw();
this.map.events.unregister("changebaselayer", this, this.baseLayerDraw);
},
/**
* Method: rectDrag
* Handle extent rectangle drag
*
* Parameters:
* px - {<OpenLayers.Pixel>} The pixel location of the drag.
*/
rectDrag: function(px) {
var deltaX = this.handlers.drag.last.x - px.x;
var deltaY = this.handlers.drag.last.y - px.y;
if(deltaX != 0 || deltaY != 0) {
var rectTop = this.rectPxBounds.top;
var rectLeft = this.rectPxBounds.left;
var rectHeight = Math.abs(this.rectPxBounds.getHeight());
var rectWidth = this.rectPxBounds.getWidth();
// don't allow dragging off of parent element
var newTop = Math.max(0, (rectTop - deltaY));
newTop = Math.min(newTop,
this.ovmap.size.h - this.hComp - rectHeight);
var newLeft = Math.max(0, (rectLeft - deltaX));
newLeft = Math.min(newLeft,
this.ovmap.size.w - this.wComp - rectWidth);
this.setRectPxBounds(new OpenLayers.Bounds(newLeft,
newTop + rectHeight,
newLeft + rectWidth,
newTop));
}
},
/**
* Method: mapDivClick
* Handle browser events
*
* Parameters:
* evt - {<OpenLayers.Event>} evt
*/
mapDivClick: function(evt) {
var pxCenter = this.rectPxBounds.getCenterPixel();
var deltaX = evt.xy.x - pxCenter.x;
var deltaY = evt.xy.y - pxCenter.y;
var top = this.rectPxBounds.top;
var left = this.rectPxBounds.left;
var height = Math.abs(this.rectPxBounds.getHeight());
var width = this.rectPxBounds.getWidth();
var newTop = Math.max(0, (top + deltaY));
newTop = Math.min(newTop, this.ovmap.size.h - height);
var newLeft = Math.max(0, (left + deltaX));
newLeft = Math.min(newLeft, this.ovmap.size.w - width);
this.setRectPxBounds(new OpenLayers.Bounds(newLeft,
newTop + height,
newLeft + width,
newTop));
this.updateMapToRect();
},
/**
* Method: maximizeControl
* Unhide the control. Called when the control is in the map viewport.
*
* Parameters:
* e - {<OpenLayers.Event>}
*/
maximizeControl: function(e) {
this.element.style.display = '';
this.showToggle(false);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: minimizeControl
* Hide all the contents of the control, shrink the size,
* add the maximize icon
*
* Parameters:
* e - {<OpenLayers.Event>}
*/
minimizeControl: function(e) {
this.element.style.display = 'none';
this.showToggle(true);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: showToggle
* Hide/Show the toggle depending on whether the control is minimized
*
* Parameters:
* minimize - {Boolean}
*/
showToggle: function(minimize) {
this.maximizeDiv.style.display = minimize ? '' : 'none';
this.minimizeDiv.style.display = minimize ? 'none' : '';
},
/**
* Method: update
* Update the overview map after layers move.
*/
update: function() {
if(this.ovmap == null) {
this.createMap();
}
if(this.autoPan || !this.isSuitableOverview()) {
this.updateOverview();
}
// update extent rectangle
this.updateRectToMap();
},
/**
* Method: isSuitableOverview
* Determines if the overview map is suitable given the extent and
* resolution of the main map.
*/
isSuitableOverview: function() {
var mapExtent = this.map.getExtent();
var maxExtent = this.map.maxExtent;
var testExtent = new OpenLayers.Bounds(
Math.max(mapExtent.left, maxExtent.left),
Math.max(mapExtent.bottom, maxExtent.bottom),
Math.min(mapExtent.right, maxExtent.right),
Math.min(mapExtent.top, maxExtent.top));
if (this.ovmap.getProjection() != this.map.getProjection()) {
testExtent = testExtent.transform(
this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
}
var resRatio = this.ovmap.getResolution() / this.map.getResolution();
return ((resRatio > this.minRatio) &&
(resRatio <= this.maxRatio) &&
(this.ovmap.getExtent().containsBounds(testExtent)));
},
/**
* Method updateOverview
* Called by <update> if <isSuitableOverview> returns true
*/
updateOverview: function() {
var mapRes = this.map.getResolution();
var targetRes = this.ovmap.getResolution();
var resRatio = targetRes / mapRes;
if(resRatio > this.maxRatio) {
// zoom in overview map
targetRes = this.minRatio * mapRes;
} else if(resRatio <= this.minRatio) {
// zoom out overview map
targetRes = this.maxRatio * mapRes;
}
var center;
if (this.ovmap.getProjection() != this.map.getProjection()) {
center = this.map.center.clone();
center.transform(this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
} else {
center = this.map.center;
}
this.ovmap.setCenter(center, this.ovmap.getZoomForResolution(
targetRes * this.resolutionFactor));
this.updateRectToMap();
},
/**
* Method: createMap
* Construct the map that this control contains
*/
createMap: function() {
// create the overview map
var options = OpenLayers.Util.extend(
{controls: [], maxResolution: 'auto',
fallThrough: false}, this.mapOptions);
this.ovmap = new OpenLayers.Map(this.mapDiv, options);
// prevent ovmap from being destroyed when the page unloads, because
// the OverviewMap control has to do this (and does it).
OpenLayers.Event.stopObserving(window, 'unload', this.ovmap.unloadDestroy);
this.ovmap.addLayers(this.layers);
this.ovmap.zoomToMaxExtent();
// check extent rectangle border width
this.wComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-left-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-right-width'));
this.wComp = (this.wComp) ? this.wComp : 2;
this.hComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-top-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-bottom-width'));
this.hComp = (this.hComp) ? this.hComp : 2;
this.handlers.drag = new OpenLayers.Handler.Drag(
this, {move: this.rectDrag, done: this.updateMapToRect},
{map: this.ovmap}
);
this.handlers.click = new OpenLayers.Handler.Click(
this, {
"click": this.mapDivClick
},{
"single": true, "double": false,
"stopSingle": true, "stopDouble": true,
"pixelTolerance": 1,
map: this.ovmap
}
);
this.handlers.click.activate();
this.rectEvents = new OpenLayers.Events(this, this.extentRectangle,
null, true);
this.rectEvents.register("mouseover", this, function(e) {
if(!this.handlers.drag.active && !this.map.dragging) {
this.handlers.drag.activate();
}
});
this.rectEvents.register("mouseout", this, function(e) {
if(!this.handlers.drag.dragging) {
this.handlers.drag.deactivate();
}
});
if (this.ovmap.getProjection() != this.map.getProjection()) {
var sourceUnits = this.map.getProjectionObject().getUnits() ||
this.map.units || this.map.baseLayer.units;
var targetUnits = this.ovmap.getProjectionObject().getUnits() ||
this.ovmap.units || this.ovmap.baseLayer.units;
this.resolutionFactor = sourceUnits && targetUnits ?
OpenLayers.INCHES_PER_UNIT[sourceUnits] /
OpenLayers.INCHES_PER_UNIT[targetUnits] : 1;
}
},
/**
* Method: updateRectToMap
* Updates the extent rectangle position and size to match the map extent
*/
updateRectToMap: function() {
// If the projections differ we need to reproject
var bounds;
if (this.ovmap.getProjection() != this.map.getProjection()) {
bounds = this.map.getExtent().transform(
this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
} else {
bounds = this.map.getExtent();
}
var pxBounds = this.getRectBoundsFromMapBounds(bounds);
if (pxBounds) {
this.setRectPxBounds(pxBounds);
}
},
/**
* Method: updateMapToRect
* Updates the map extent to match the extent rectangle position and size
*/
updateMapToRect: function() {
var lonLatBounds = this.getMapBoundsFromRectBounds(this.rectPxBounds);
if (this.ovmap.getProjection() != this.map.getProjection()) {
lonLatBounds = lonLatBounds.transform(
this.ovmap.getProjectionObject(),
this.map.getProjectionObject() );
}
this.map.panTo(lonLatBounds.getCenterLonLat());
},
/**
* Method: setRectPxBounds
* Set extent rectangle pixel bounds.
*
* Parameters:
* pxBounds - {<OpenLayers.Bounds>}
*/
setRectPxBounds: function(pxBounds) {
var top = Math.max(pxBounds.top, 0);
var left = Math.max(pxBounds.left, 0);
var bottom = Math.min(pxBounds.top + Math.abs(pxBounds.getHeight()),
this.ovmap.size.h - this.hComp);
var right = Math.min(pxBounds.left + pxBounds.getWidth(),
this.ovmap.size.w - this.wComp);
var width = Math.max(right - left, 0);
var height = Math.max(bottom - top, 0);
if(width < this.minRectSize || height < this.minRectSize) {
this.extentRectangle.className = this.displayClass +
this.minRectDisplayClass;
var rLeft = left + (width / 2) - (this.minRectSize / 2);
var rTop = top + (height / 2) - (this.minRectSize / 2);
this.extentRectangle.style.top = Math.round(rTop) + 'px';
this.extentRectangle.style.left = Math.round(rLeft) + 'px';
this.extentRectangle.style.height = this.minRectSize + 'px';
this.extentRectangle.style.width = this.minRectSize + 'px';
} else {
this.extentRectangle.className = this.displayClass +
'ExtentRectangle';
this.extentRectangle.style.top = Math.round(top) + 'px';
this.extentRectangle.style.left = Math.round(left) + 'px';
this.extentRectangle.style.height = Math.round(height) + 'px';
this.extentRectangle.style.width = Math.round(width) + 'px';
}
this.rectPxBounds = new OpenLayers.Bounds(
Math.round(left), Math.round(bottom),
Math.round(right), Math.round(top)
);
},
/**
* Method: getRectBoundsFromMapBounds
* Get the rect bounds from the map bounds.
*
* Parameters:
* lonLatBounds - {<OpenLayers.Bounds>}
*
* Returns:
* {<OpenLayers.Bounds>}A bounds which is the passed-in map lon/lat extent
* translated into pixel bounds for the overview map
*/
getRectBoundsFromMapBounds: function(lonLatBounds) {
var leftBottomLonLat = new OpenLayers.LonLat(lonLatBounds.left,
lonLatBounds.bottom);
var rightTopLonLat = new OpenLayers.LonLat(lonLatBounds.right,
lonLatBounds.top);
var leftBottomPx = this.getOverviewPxFromLonLat(leftBottomLonLat);
var rightTopPx = this.getOverviewPxFromLonLat(rightTopLonLat);
var bounds = null;
if (leftBottomPx && rightTopPx) {
bounds = new OpenLayers.Bounds(leftBottomPx.x, leftBottomPx.y,
rightTopPx.x, rightTopPx.y);
}
return bounds;
},
/**
* Method: getMapBoundsFromRectBounds
* Get the map bounds from the rect bounds.
*
* Parameters:
* pxBounds - {<OpenLayers.Bounds>}
*
* Returns:
* {<OpenLayers.Bounds>} Bounds which is the passed-in overview rect bounds
* translated into lon/lat bounds for the overview map
*/
getMapBoundsFromRectBounds: function(pxBounds) {
var leftBottomPx = new OpenLayers.Pixel(pxBounds.left,
pxBounds.bottom);
var rightTopPx = new OpenLayers.Pixel(pxBounds.right,
pxBounds.top);
var leftBottomLonLat = this.getLonLatFromOverviewPx(leftBottomPx);
var rightTopLonLat = this.getLonLatFromOverviewPx(rightTopPx);
return new OpenLayers.Bounds(leftBottomLonLat.lon, leftBottomLonLat.lat,
rightTopLonLat.lon, rightTopLonLat.lat);
},
/**
* Method: getLonLatFromOverviewPx
* Get a map location from a pixel location
*
* Parameters:
* overviewMapPx - {<OpenLayers.Pixel>}
*
* Returns:
* {<OpenLayers.LonLat>} Location which is the passed-in overview map
* OpenLayers.Pixel, translated into lon/lat by the overview map
*/
getLonLatFromOverviewPx: function(overviewMapPx) {
var size = this.ovmap.size;
var res = this.ovmap.getResolution();
var center = this.ovmap.getExtent().getCenterLonLat();
var delta_x = overviewMapPx.x - (size.w / 2);
var delta_y = overviewMapPx.y - (size.h / 2);
return new OpenLayers.LonLat(center.lon + delta_x * res ,
center.lat - delta_y * res);
},
/**
* Method: getOverviewPxFromLonLat
* Get a pixel location from a map location
*
* Parameters:
* lonlat - {<OpenLayers.LonLat>}
*
* Returns:
* {<OpenLayers.Pixel>} Location which is the passed-in OpenLayers.LonLat,
* translated into overview map pixels
*/
getOverviewPxFromLonLat: function(lonlat) {
var res = this.ovmap.getResolution();
var extent = this.ovmap.getExtent();
var px = null;
if (extent) {
px = new OpenLayers.Pixel(
Math.round(1/res * (lonlat.lon - extent.left)),
Math.round(1/res * (extent.top - lonlat.lat)));
}
return px;
},
CLASS_NAME: 'OpenLayers.Control.OverviewMap'
});

View File

@ -1,85 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Pan
* The Pan control is a single button to pan the map in one direction. For
* a more complete control see <OpenLayers.Control.PanPanel>.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Pan = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: slideFactor
* {Integer} Number of pixels by which we'll pan the map in any direction
* on clicking the arrow buttons.
*/
slideFactor: 50,
/**
* Property: direction
* {String} in {'North', 'South', 'East', 'West'}
*/
direction: null,
/**
* Property: type
* {String} The type of <OpenLayers.Control> -- When added to a
* <Control.Panel>, 'type' is used by the panel to determine how to
* handle our events.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/**
* Constructor: OpenLayers.Control.Pan
* Control which handles the panning (in any of the cardinal directions)
* of the map by a set px distance.
*
* Parameters:
* direction - {String} The direction this button should pan.
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function(direction, options) {
this.direction = direction;
this.CLASS_NAME += this.direction;
OpenLayers.Control.prototype.initialize.apply(this, [options]);
},
/**
* Method: trigger
*/
trigger: function(){
switch (this.direction) {
case OpenLayers.Control.Pan.NORTH:
this.map.pan(0, -this.slideFactor);
break;
case OpenLayers.Control.Pan.SOUTH:
this.map.pan(0, this.slideFactor);
break;
case OpenLayers.Control.Pan.WEST:
this.map.pan(-this.slideFactor, 0);
break;
case OpenLayers.Control.Pan.EAST:
this.map.pan(this.slideFactor, 0);
break;
}
},
CLASS_NAME: "OpenLayers.Control.Pan"
});
OpenLayers.Control.Pan.NORTH = "North";
OpenLayers.Control.Pan.SOUTH = "South";
OpenLayers.Control.Pan.EAST = "East";
OpenLayers.Control.Pan.WEST = "West";

View File

@ -1,47 +0,0 @@
/**
* @requires OpenLayers/Control/Panel.js
* @requires OpenLayers/Control/Pan.js
*/
/**
* Class: OpenLayers.Control.PanPanel
* The PanPanel is visible control for panning the map North, South, East or
* West in small steps. By default it is drawn in the top left corner of the
* map.
*
* Note:
* If you wish to use this class with the default images and you want
* it to look nice in ie6, you should add the following, conditionally
* added css stylesheet to your HTML file:
*
* (code)
* <!--[if lte IE 6]>
* <link rel="stylesheet" href="../theme/default/ie6-style.css" type="text/css" />
* <![endif]-->
* (end)
*
* Inherits from:
* - <OpenLayers.Control.Panel>
*/
OpenLayers.Control.PanPanel = OpenLayers.Class(OpenLayers.Control.Panel, {
/**
* Constructor: OpenLayers.Control.PanPanel
* Add the four directional pan buttons.
*
* Parameters:
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function(options) {
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls([
new OpenLayers.Control.Pan(OpenLayers.Control.Pan.NORTH),
new OpenLayers.Control.Pan(OpenLayers.Control.Pan.SOUTH),
new OpenLayers.Control.Pan(OpenLayers.Control.Pan.EAST),
new OpenLayers.Control.Pan(OpenLayers.Control.Pan.WEST)
]);
},
CLASS_NAME: "OpenLayers.Control.PanPanel"
});

View File

@ -1,244 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.PanZoom
* The PanZoom is a visible control, composed of a
* <OpenLayers.Control.PanPanel> and a <OpenLayers.Control.ZoomPanel>. By
* default it is drawn in the upper left corner of the map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.PanZoom = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: slideFactor
* {Integer} Number of pixels by which we'll pan the map in any direction
* on clicking the arrow buttons. If you want to pan by some ratio
* of the map dimensions, use <slideRatio> instead.
*/
slideFactor: 50,
/**
* APIProperty: slideRatio
* {Number} The fraction of map width/height by which we'll pan the map
* on clicking the arrow buttons. Default is null. If set, will
* override <slideFactor>. E.g. if slideRatio is .5, then the Pan Up
* button will pan up half the map height.
*/
slideRatio: null,
/**
* Property: buttons
* {Array(DOMElement)} Array of Button Divs
*/
buttons: null,
/**
* Property: position
* {<OpenLayers.Pixel>}
*/
position: null,
/**
* Constructor: OpenLayers.Control.PanZoom
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
this.position = new OpenLayers.Pixel(OpenLayers.Control.PanZoom.X,
OpenLayers.Control.PanZoom.Y);
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* APIMethod: destroy
*/
destroy: function() {
OpenLayers.Control.prototype.destroy.apply(this, arguments);
this.removeButtons();
this.buttons = null;
this.position = null;
},
/**
* Method: draw
*
* Parameters:
* px - {<OpenLayers.Pixel>}
*
* Returns:
* {DOMElement} A reference to the container div for the PanZoom control.
*/
draw: function(px) {
// initialize our internal div
OpenLayers.Control.prototype.draw.apply(this, arguments);
px = this.position;
// place the controls
this.buttons = [];
var sz = new OpenLayers.Size(18,18);
var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);
this._addButton("panup", "north-mini.png", centered, sz);
px.y = centered.y+sz.h;
this._addButton("panleft", "west-mini.png", px, sz);
this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz);
this._addButton("pandown", "south-mini.png",
centered.add(0, sz.h*2), sz);
this._addButton("zoomin", "zoom-plus-mini.png",
centered.add(0, sz.h*3+5), sz);
this._addButton("zoomworld", "zoom-world-mini.png",
centered.add(0, sz.h*4+5), sz);
this._addButton("zoomout", "zoom-minus-mini.png",
centered.add(0, sz.h*5+5), sz);
return this.div;
},
/**
* Method: _addButton
*
* Parameters:
* id - {String}
* img - {String}
* xy - {<OpenLayers.Pixel>}
* sz - {<OpenLayers.Size>}
*
* Returns:
* {DOMElement} A Div (an alphaImageDiv, to be precise) that contains the
* image of the button, and has all the proper event handlers set.
*/
_addButton:function(id, img, xy, sz) {
var imgLocation = OpenLayers.Util.getImagesLocation() + img;
var btn = OpenLayers.Util.createAlphaImageDiv(
this.id + "_" + id,
xy, sz, imgLocation, "absolute");
//we want to add the outer div
this.div.appendChild(btn);
OpenLayers.Event.observe(btn, "mousedown",
OpenLayers.Function.bindAsEventListener(this.buttonDown, btn));
OpenLayers.Event.observe(btn, "dblclick",
OpenLayers.Function.bindAsEventListener(this.doubleClick, btn));
OpenLayers.Event.observe(btn, "click",
OpenLayers.Function.bindAsEventListener(this.doubleClick, btn));
btn.action = id;
btn.map = this.map;
if(!this.slideRatio){
var slideFactorPixels = this.slideFactor;
var getSlideFactor = function() {
return slideFactorPixels;
};
} else {
var slideRatio = this.slideRatio;
var getSlideFactor = function(dim) {
return this.map.getSize()[dim] * slideRatio;
};
}
btn.getSlideFactor = getSlideFactor;
//we want to remember/reference the outer div
this.buttons.push(btn);
return btn;
},
/**
* Method: _removeButton
*
* Parameters:
* btn - {Object}
*/
_removeButton: function(btn) {
OpenLayers.Event.stopObservingElement(btn);
btn.map = null;
this.div.removeChild(btn);
OpenLayers.Util.removeItem(this.buttons, btn);
},
/**
* Method: removeButtons
*/
removeButtons: function() {
for(var i=this.buttons.length-1; i>=0; --i) {
this._removeButton(this.buttons[i]);
}
},
/**
* Method: doubleClick
*
* Parameters:
* evt - {Event}
*
* Returns:
* {Boolean}
*/
doubleClick: function (evt) {
OpenLayers.Event.stop(evt);
return false;
},
/**
* Method: buttonDown
*
* Parameters:
* evt - {Event}
*/
buttonDown: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
switch (this.action) {
case "panup":
this.map.pan(0, -this.getSlideFactor("h"));
break;
case "pandown":
this.map.pan(0, this.getSlideFactor("h"));
break;
case "panleft":
this.map.pan(-this.getSlideFactor("w"), 0);
break;
case "panright":
this.map.pan(this.getSlideFactor("w"), 0);
break;
case "zoomin":
this.map.zoomIn();
break;
case "zoomout":
this.map.zoomOut();
break;
case "zoomworld":
this.map.zoomToMaxExtent();
break;
}
OpenLayers.Event.stop(evt);
},
CLASS_NAME: "OpenLayers.Control.PanZoom"
});
/**
* Constant: X
* {Integer}
*/
OpenLayers.Control.PanZoom.X = 4;
/**
* Constant: Y
* {Integer}
*/
OpenLayers.Control.PanZoom.Y = 4;

View File

@ -1,373 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control/PanZoom.js
*/
/**
* Class: OpenLayers.Control.PanZoomBar
* The PanZoomBar is a visible control composed of a
* <OpenLayers.Control.PanPanel> and a <OpenLayers.Control.ZoomBar>.
* By default it is displayed in the upper left corner of the map as 4
* directional arrows above a vertical slider.
*
* Inherits from:
* - <OpenLayers.Control.PanZoom>
*/
OpenLayers.Control.PanZoomBar = OpenLayers.Class(OpenLayers.Control.PanZoom, {
/**
* APIProperty: zoomStopWidth
*/
zoomStopWidth: 18,
/**
* APIProperty: zoomStopHeight
*/
zoomStopHeight: 11,
/**
* Property: slider
*/
slider: null,
/**
* Property: sliderEvents
* {<OpenLayers.Events>}
*/
sliderEvents: null,
/**
* Property: zoomBarDiv
* {DOMElement}
*/
zoomBarDiv: null,
/**
* Property: divEvents
* {<OpenLayers.Events>}
*/
divEvents: null,
/**
* APIProperty: zoomWorldIcon
* {Boolean}
*/
zoomWorldIcon: false,
/**
* Constructor: OpenLayers.Control.PanZoomBar
*/
initialize: function() {
OpenLayers.Control.PanZoom.prototype.initialize.apply(this, arguments);
},
/**
* APIMethod: destroy
*/
destroy: function() {
this._removeZoomBar();
this.map.events.un({
"changebaselayer": this.redraw,
scope: this
});
OpenLayers.Control.PanZoom.prototype.destroy.apply(this, arguments);
},
/**
* Method: setMap
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
OpenLayers.Control.PanZoom.prototype.setMap.apply(this, arguments);
this.map.events.register("changebaselayer", this, this.redraw);
},
/**
* Method: redraw
* clear the div and start over.
*/
redraw: function() {
if (this.div != null) {
this.removeButtons();
this._removeZoomBar();
}
this.draw();
},
/**
* Method: draw
*
* Parameters:
* px - {<OpenLayers.Pixel>}
*/
draw: function(px) {
// initialize our internal div
OpenLayers.Control.prototype.draw.apply(this, arguments);
px = this.position.clone();
// place the controls
this.buttons = [];
var sz = new OpenLayers.Size(18,18);
var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);
var wposition = sz.w;
if (this.zoomWorldIcon) {
centered = new OpenLayers.Pixel(px.x+sz.w, px.y);
}
this._addButton("panup", "north-mini.png", centered, sz);
px.y = centered.y+sz.h;
this._addButton("panleft", "west-mini.png", px, sz);
if (this.zoomWorldIcon) {
this._addButton("zoomworld", "zoom-world-mini.png", px.add(sz.w, 0), sz);
wposition *= 2;
}
this._addButton("panright", "east-mini.png", px.add(wposition, 0), sz);
this._addButton("pandown", "south-mini.png", centered.add(0, sz.h*2), sz);
this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0, sz.h*3+5), sz);
centered = this._addZoomBar(centered.add(0, sz.h*4 + 5));
this._addButton("zoomout", "zoom-minus-mini.png", centered, sz);
return this.div;
},
/**
* Method: _addZoomBar
*
* Parameters:
* location - {<OpenLayers.Pixel>} where zoombar drawing is to start.
*/
_addZoomBar:function(centered) {
var imgLocation = OpenLayers.Util.getImagesLocation();
var id = this.id + "_" + this.map.id;
var zoomsToEnd = this.map.getNumZoomLevels() - 1 - this.map.getZoom();
var slider = OpenLayers.Util.createAlphaImageDiv(id,
centered.add(-1, zoomsToEnd * this.zoomStopHeight),
new OpenLayers.Size(20,9),
imgLocation+"slider.png",
"absolute");
this.slider = slider;
this.sliderEvents = new OpenLayers.Events(this, slider, null, true,
{includeXY: true});
this.sliderEvents.on({
"mousedown": this.zoomBarDown,
"mousemove": this.zoomBarDrag,
"mouseup": this.zoomBarUp,
"dblclick": this.doubleClick,
"click": this.doubleClick
});
var sz = new OpenLayers.Size();
sz.h = this.zoomStopHeight * this.map.getNumZoomLevels();
sz.w = this.zoomStopWidth;
var div = null;
if (OpenLayers.Util.alphaHack()) {
var id = this.id + "_" + this.map.id;
div = OpenLayers.Util.createAlphaImageDiv(id, centered,
new OpenLayers.Size(sz.w,
this.zoomStopHeight),
imgLocation + "zoombar.png",
"absolute", null, "crop");
div.style.height = sz.h + "px";
} else {
div = OpenLayers.Util.createDiv(
'OpenLayers_Control_PanZoomBar_Zoombar' + this.map.id,
centered,
sz,
imgLocation+"zoombar.png");
}
this.zoombarDiv = div;
this.divEvents = new OpenLayers.Events(this, div, null, true,
{includeXY: true});
this.divEvents.on({
"mousedown": this.divClick,
"mousemove": this.passEventToSlider,
"dblclick": this.doubleClick,
"click": this.doubleClick
});
this.div.appendChild(div);
this.startTop = parseInt(div.style.top);
this.div.appendChild(slider);
this.map.events.register("zoomend", this, this.moveZoomBar);
centered = centered.add(0,
this.zoomStopHeight * this.map.getNumZoomLevels());
return centered;
},
/**
* Method: _removeZoomBar
*/
_removeZoomBar: function() {
this.sliderEvents.un({
"mousedown": this.zoomBarDown,
"mousemove": this.zoomBarDrag,
"mouseup": this.zoomBarUp,
"dblclick": this.doubleClick,
"click": this.doubleClick
});
this.sliderEvents.destroy();
this.divEvents.un({
"mousedown": this.divClick,
"mousemove": this.passEventToSlider,
"dblclick": this.doubleClick,
"click": this.doubleClick
});
this.divEvents.destroy();
this.div.removeChild(this.zoombarDiv);
this.zoombarDiv = null;
this.div.removeChild(this.slider);
this.slider = null;
this.map.events.unregister("zoomend", this, this.moveZoomBar);
},
/**
* Method: passEventToSlider
* This function is used to pass events that happen on the div, or the map,
* through to the slider, which then does its moving thing.
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
passEventToSlider:function(evt) {
this.sliderEvents.handleBrowserEvent(evt);
},
/**
* Method: divClick
* Picks up on clicks directly on the zoombar div
* and sets the zoom level appropriately.
*/
divClick: function (evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
var y = evt.xy.y;
var top = OpenLayers.Util.pagePosition(evt.object)[1];
var levels = (y - top)/this.zoomStopHeight;
if(!this.map.fractionalZoom) {
levels = Math.floor(levels);
}
var zoom = (this.map.getNumZoomLevels() - 1) - levels;
zoom = Math.min(Math.max(zoom, 0), this.map.getNumZoomLevels() - 1);
this.map.zoomTo(zoom);
OpenLayers.Event.stop(evt);
},
/*
* Method: zoomBarDown
* event listener for clicks on the slider
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
zoomBarDown:function(evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
this.map.events.on({
"mousemove": this.passEventToSlider,
"mouseup": this.passEventToSlider,
scope: this
});
this.mouseDragStart = evt.xy.clone();
this.zoomStart = evt.xy.clone();
this.div.style.cursor = "move";
// reset the div offsets just in case the div moved
this.zoombarDiv.offsets = null;
OpenLayers.Event.stop(evt);
},
/*
* Method: zoomBarDrag
* This is what happens when a click has occurred, and the client is
* dragging. Here we must ensure that the slider doesn't go beyond the
* bottom/top of the zoombar div, as well as moving the slider to its new
* visual location
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
zoomBarDrag:function(evt) {
if (this.mouseDragStart != null) {
var deltaY = this.mouseDragStart.y - evt.xy.y;
var offsets = OpenLayers.Util.pagePosition(this.zoombarDiv);
if ((evt.clientY - offsets[1]) > 0 &&
(evt.clientY - offsets[1]) < parseInt(this.zoombarDiv.style.height) - 2) {
var newTop = parseInt(this.slider.style.top) - deltaY;
this.slider.style.top = newTop+"px";
this.mouseDragStart = evt.xy.clone();
}
OpenLayers.Event.stop(evt);
}
},
/*
* Method: zoomBarUp
* Perform cleanup when a mouseup event is received -- discover new zoom
* level and switch to it.
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
zoomBarUp:function(evt) {
if (!OpenLayers.Event.isLeftClick(evt)) {
return;
}
if (this.zoomStart) {
this.div.style.cursor="";
this.map.events.un({
"mouseup": this.passEventToSlider,
"mousemove": this.passEventToSlider,
scope: this
});
var deltaY = this.zoomStart.y - evt.xy.y;
var zoomLevel = this.map.zoom;
if (this.map.fractionalZoom) {
zoomLevel += deltaY/this.zoomStopHeight;
zoomLevel = Math.min(Math.max(zoomLevel, 0),
this.map.getNumZoomLevels() - 1);
} else {
zoomLevel += Math.round(deltaY/this.zoomStopHeight);
}
this.map.zoomTo(zoomLevel);
this.moveZoomBar();
this.mouseDragStart = null;
OpenLayers.Event.stop(evt);
}
},
/*
* Method: moveZoomBar
* Change the location of the slider to match the current zoom level.
*/
moveZoomBar:function() {
var newTop =
((this.map.getNumZoomLevels()-1) - this.map.getZoom()) *
this.zoomStopHeight + this.startTop + 1;
this.slider.style.top = newTop + "px";
},
CLASS_NAME: "OpenLayers.Control.PanZoomBar"
});

View File

@ -1,286 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Panel
* The Panel control is a container for other controls. With it toolbars
* may be composed.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Panel = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: controls
* {Array(<OpenLayers.Control>)}
*/
controls: null,
/**
* APIProperty: defaultControl
* {<OpenLayers.Control>} The control which is activated when the control is
* activated (turned on), which also happens at instantiation.
*/
defaultControl: null,
/**
* Constructor: OpenLayers.Control.Panel
* Create a new control panel.
*
* 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.controls = [];
},
/**
* APIMethod: destroy
*/
destroy: function() {
OpenLayers.Control.prototype.destroy.apply(this, arguments);
for(var i = this.controls.length - 1 ; i >= 0; i--) {
if(this.controls[i].events) {
this.controls[i].events.un({
"activate": this.redraw,
"deactivate": this.redraw,
scope: this
});
}
OpenLayers.Event.stopObservingElement(this.controls[i].panel_div);
this.controls[i].panel_div = null;
}
},
/**
* APIMethod: activate
*/
activate: function() {
if (OpenLayers.Control.prototype.activate.apply(this, arguments)) {
for(var i=0, len=this.controls.length; i<len; i++) {
if (this.controls[i] == this.defaultControl) {
this.controls[i].activate();
}
}
this.redraw();
return true;
} else {
return false;
}
},
/**
* APIMethod: deactivate
*/
deactivate: function() {
if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
for(var i=0, len=this.controls.length; i<len; i++) {
this.controls[i].deactivate();
}
return true;
} else {
return false;
}
},
/**
* Method: draw
*
* Returns:
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
for (var i=0, len=this.controls.length; i<len; i++) {
this.map.addControl(this.controls[i]);
this.controls[i].deactivate();
this.controls[i].events.on({
"activate": this.redraw,
"deactivate": this.redraw,
scope: this
});
}
this.activate();
return this.div;
},
/**
* Method: redraw
*/
redraw: function() {
this.div.innerHTML = "";
if (this.active) {
for (var i=0, len=this.controls.length; i<len; i++) {
var element = this.controls[i].panel_div;
if (this.controls[i].active) {
element.className = this.controls[i].displayClass + "ItemActive";
} else {
element.className = this.controls[i].displayClass + "ItemInactive";
}
this.div.appendChild(element);
}
}
},
/**
* APIMethod: activateControl
*
* Parameters:
* control - {<OpenLayers.Control>}
*/
activateControl: function (control) {
if (!this.active) { return false; }
if (control.type == OpenLayers.Control.TYPE_BUTTON) {
control.trigger();
this.redraw();
return;
}
if (control.type == OpenLayers.Control.TYPE_TOGGLE) {
if (control.active) {
control.deactivate();
} else {
control.activate();
}
this.redraw();
return;
}
for (var i=0, len=this.controls.length; i<len; i++) {
if (this.controls[i] != control) {
if (this.controls[i].type != OpenLayers.Control.TYPE_TOGGLE) {
this.controls[i].deactivate();
}
}
}
control.activate();
},
/**
* APIMethod: addControls
* To build a toolbar, you add a set of controls to it. addControls
* lets you add a single control or a list of controls to the
* Control Panel.
*
* Parameters:
* controls - {<OpenLayers.Control>}
*/
addControls: function(controls) {
if (!(controls instanceof Array)) {
controls = [controls];
}
this.controls = this.controls.concat(controls);
// Give each control a panel_div which will be used later.
// Access to this div is via the panel_div attribute of the
// control added to the panel.
// Also, stop mousedowns and clicks, but don't stop mouseup,
// since they need to pass through.
for (var i=0, len=controls.length; i<len; i++) {
var element = document.createElement("div");
var textNode = document.createTextNode(" ");
controls[i].panel_div = element;
if (controls[i].title != "") {
controls[i].panel_div.title = controls[i].title;
}
OpenLayers.Event.observe(controls[i].panel_div, "click",
OpenLayers.Function.bind(this.onClick, this, controls[i]));
OpenLayers.Event.observe(controls[i].panel_div, "mousedown",
OpenLayers.Function.bindAsEventListener(OpenLayers.Event.stop));
}
if (this.map) { // map.addControl() has already been called on the panel
for (var i=0, len=controls.length; i<len; i++) {
this.map.addControl(controls[i]);
controls[i].deactivate();
controls[i].events.on({
"activate": this.redraw,
"deactivate": this.redraw,
scope: this
});
}
this.redraw();
}
},
/**
* Method: onClick
*/
onClick: function (ctrl, evt) {
OpenLayers.Event.stop(evt ? evt : window.event);
this.activateControl(ctrl);
},
/**
* 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(control[property]) evaluates to true, the control will be
* included in the array returned. If no controls are found, an empty
* array is returned.
*
* Returns:
* {Array(<OpenLayers.Control>)} A list of controls matching the given criteria.
* An empty array is returned if no matches are found.
*/
getControlsBy: function(property, match) {
var test = (typeof match.test == "function");
var found = OpenLayers.Array.filter(this.controls, function(item) {
return item[property] == match || (test && match.test(item[property]));
});
return found;
},
/**
* APIMethod: getControlsByName
* Get a list of contorls with names matching the given name.
*
* Parameter:
* match - {String | Object} A control 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(control.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(<OpenLayers.Control>)} A list of controls matching the given name.
* An empty array is returned if no matches are found.
*/
getControlsByName: function(match) {
return this.getControlsBy("name", match);
},
/**
* APIMethod: getControlsByClass
* Get a list of controls of a given type (CLASS_NAME).
*
* Parameter:
* match - {String | Object} A control class name. The type 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(<OpenLayers.Control>)} A list of controls matching the given type.
* An empty array is returned if no matches are found.
*/
getControlsByClass: function(match) {
return this.getControlsBy("CLASS_NAME", match);
},
CLASS_NAME: "OpenLayers.Control.Panel"
});

View File

@ -1,219 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Control/ArgParser.js
*/
/**
* Class: OpenLayers.Control.Permalink
* The Permalink control is hyperlink that will return the user to the
* current map view. By default it is drawn in the lower right corner of the
* map. The href is updated as the map is zoomed, panned and whilst layers
* are switched.
* `
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Permalink = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: argParserClass
* {Class} The ArgParser control class (not instance) to use with this
* control.
*/
argParserClass: OpenLayers.Control.ArgParser,
/**
* Property: element
* {DOMElement}
*/
element: null,
/**
* APIProperty: base
* {String}
*/
base: '',
/**
* APIProperty: displayProjection
* {<OpenLayers.Projection>} Requires proj4js support. Projection used
* when creating the coordinates in the link. This will reproject the
* map coordinates into display coordinates. If you are using this
* functionality, the permalink which is last added to the map will
* determine the coordinate type which is read from the URL, which
* means you should not add permalinks with different
* displayProjections to the same map.
*/
displayProjection: null,
/**
* Constructor: OpenLayers.Control.Permalink
*
* Parameters:
* element - {DOMElement}
* base - {String}
* options - {Object} options to the control.
*/
initialize: function(element, base, options) {
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.element = OpenLayers.Util.getElement(element);
this.base = base || document.location.href;
},
/**
* APIMethod: destroy
*/
destroy: function() {
if (this.element.parentNode == this.div) {
this.div.removeChild(this.element);
}
this.element = null;
this.map.events.unregister('moveend', this, this.updateLink);
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
OpenLayers.Control.prototype.setMap.apply(this, arguments);
//make sure we have an arg parser attached
for(var i=0, len=this.map.controls.length; i<len; i++) {
var control = this.map.controls[i];
if (control.CLASS_NAME == this.argParserClass.CLASS_NAME) {
// If a permalink is added to the map, and an ArgParser already
// exists, we override the displayProjection to be the one
// on the permalink.
if (control.displayProjection != this.displayProjection) {
this.displayProjection = control.displayProjection;
}
break;
}
}
if (i == this.map.controls.length) {
this.map.addControl(new this.argParserClass(
{ 'displayProjection': this.displayProjection }));
}
},
/**
* Method: draw
*
* Returns:
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if (!this.element) {
this.div.className = this.displayClass;
this.element = document.createElement("a");
this.element.innerHTML = OpenLayers.i18n("permalink");
this.element.href="";
this.div.appendChild(this.element);
}
this.map.events.on({
'moveend': this.updateLink,
'changelayer': this.updateLink,
'changebaselayer': this.updateLink,
scope: this
});
// Make it so there is at least a link even though the map may not have
// moved yet.
this.updateLink();
return this.div;
},
/**
* Method: updateLink
*/
updateLink: function() {
var href = this.base;
if (href.indexOf('?') != -1) {
href = href.substring( 0, href.indexOf('?') );
}
href += '?' + OpenLayers.Util.getParameterString(this.createParams());
this.element.href = href;
},
/**
* APIMethod: createParams
* Creates the parameters that need to be encoded into the permalink url.
*
* Parameters:
* center - {<OpenLayers.LonLat>} center to encode in the permalink.
* Defaults to the current map center.
* zoom - {Integer} zoom level to encode in the permalink. Defaults to the
* current map zoom level.
* layers - {Array(<OpenLayers.Layer>)} layers to encode in the permalink.
* Defaults to the current map layers.
*
* Returns:
* {Object} Hash of parameters that will be url-encoded into the
* permalink.
*/
createParams: function(center, zoom, layers) {
center = center || this.map.getCenter();
var params = OpenLayers.Util.getParameters(this.base);
// If there's still no center, map is not initialized yet.
// Break out of this function, and simply return the params from the
// base link.
if (center) {
//zoom
params.zoom = zoom || this.map.getZoom();
//lon,lat
var lat = center.lat;
var lon = center.lon;
if (this.displayProjection) {
var mapPosition = OpenLayers.Projection.transform(
{ x: lon, y: lat },
this.map.getProjectionObject(),
this.displayProjection );
lon = mapPosition.x;
lat = mapPosition.y;
}
params.lat = Math.round(lat*100000)/100000;
params.lon = Math.round(lon*100000)/100000;
//layers
layers = layers || this.map.layers;
params.layers = '';
for (var i=0, len=layers.length; i<len; i++) {
var layer = layers[i];
if (layer.isBaseLayer) {
params.layers += (layer == this.map.baseLayer) ? "B" : "0";
} else {
params.layers += (layer.getVisibility()) ? "T" : "F";
}
}
}
return params;
},
CLASS_NAME: "OpenLayers.Control.Permalink"
});

View File

@ -1,77 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.Scale
* The Scale control displays the current map scale as a ratio (e.g. Scale =
* 1:1M). By default it is displayed in the lower right corner of the map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Scale = OpenLayers.Class(OpenLayers.Control, {
/**
* Parameter: element
* {DOMElement}
*/
element: null,
/**
* Constructor: OpenLayers.Control.Scale
*
* Parameters:
* element - {DOMElement}
* options - {Object}
*/
initialize: function(element, options) {
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.element = OpenLayers.Util.getElement(element);
},
/**
* Method: draw
*
* Returns:
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if (!this.element) {
this.element = document.createElement("div");
this.div.appendChild(this.element);
}
this.map.events.register( 'moveend', this, this.updateScale);
this.updateScale();
return this.div;
},
/**
* Method: updateScale
*/
updateScale: function() {
var scale = this.map.getScale();
if (!scale) {
return;
}
if (scale >= 9500 && scale <= 950000) {
scale = Math.round(scale / 1000) + "K";
} else if (scale >= 950000) {
scale = Math.round(scale / 1000000) + "M";
} else {
scale = Math.round(scale);
}
this.element.innerHTML = OpenLayers.i18n("scale", {'scaleDenom':scale});
},
CLASS_NAME: "OpenLayers.Control.Scale"
});

View File

@ -1,208 +0,0 @@
/* Copyright (c) 2006-2007 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.ScaleLine
* The ScaleLine displays a small line indicator representing the current
* map scale on the map. By default it is drawn in the lower left corner of
* the map.
*
* Inherits from:
* - <OpenLayers.Control>
*
* Is a very close copy of:
* - <OpenLayers.Control.Scale>
*/
OpenLayers.Control.ScaleLine = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: maxWidth
* {Integer} Maximum width of the scale line in pixels. Default is 100.
*/
maxWidth: 100,
/**
* Property: topOutUnits
* {String} Units for zoomed out on top bar. Default is km.
*/
topOutUnits: "km",
/**
* Property: topInUnits
* {String} Units for zoomed in on top bar. Default is m.
*/
topInUnits: "m",
/**
* Property: bottomOutUnits
* {String} Units for zoomed out on bottom bar. Default is mi.
*/
bottomOutUnits: "mi",
/**
* Property: bottomInUnits
* {String} Units for zoomed in on bottom bar. Default is ft.
*/
bottomInUnits: "ft",
/**
* Property: eTop
* {DOMElement}
*/
eTop: null,
/**
* Property: eBottom
* {DOMElement}
*/
eBottom:null,
/**
* Constructor: OpenLayers.Control.ScaleLine
* Create a new scale line control.
*
* 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]);
},
/**
* Method: draw
*
* Returns:
* {DOMElement}
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if (!this.eTop) {
this.div.style.display = "block";
this.div.style.position = "absolute";
// stick in the top bar
this.eTop = document.createElement("div");
this.eTop.className = this.displayClass + "Top";
var theLen = this.topInUnits.length;
this.div.appendChild(this.eTop);
if((this.topOutUnits == "") || (this.topInUnits == "")) {
this.eTop.style.visibility = "hidden";
} else {
this.eTop.style.visibility = "visible";
}
// and the bottom bar
this.eBottom = document.createElement("div");
this.eBottom.className = this.displayClass + "Bottom";
this.div.appendChild(this.eBottom);
if((this.bottomOutUnits == "") || (this.bottomInUnits == "")) {
this.eBottom.style.visibility = "hidden";
} else {
this.eBottom.style.visibility = "visible";
}
}
this.map.events.register('moveend', this, this.update);
this.update();
return this.div;
},
/**
* Method: getBarLen
* Given a number, round it down to the nearest 1,2,5 times a power of 10.
* That seems a fairly useful set of number groups to use.
*
* Parameters:
* maxLen - {float} the number we're rounding down from
*
* Returns:
* {Float} the rounded number (less than or equal to maxLen)
*/
getBarLen: function(maxLen) {
// nearest power of 10 lower than maxLen
var digits = parseInt(Math.log(maxLen) / Math.log(10));
var pow10 = Math.pow(10, digits);
// ok, find first character
var firstChar = parseInt(maxLen / pow10);
// right, put it into the correct bracket
var barLen;
if(firstChar > 5) {
barLen = 5;
} else if(firstChar > 2) {
barLen = 2;
} else {
barLen = 1;
}
// scale it up the correct power of 10
return barLen * pow10;
},
/**
* Method: update
* Update the size of the bars, and the labels they contain.
*/
update: function() {
var res = this.map.getResolution();
if (!res) {
return;
}
var curMapUnits = this.map.getUnits();
var inches = OpenLayers.INCHES_PER_UNIT;
// convert maxWidth to map units
var maxSizeData = this.maxWidth * res * inches[curMapUnits];
// decide whether to use large or small scale units
var topUnits;
var bottomUnits;
if(maxSizeData > 100000) {
topUnits = this.topOutUnits;
bottomUnits = this.bottomOutUnits;
} else {
topUnits = this.topInUnits;
bottomUnits = this.bottomInUnits;
}
// and to map units units
var topMax = maxSizeData / inches[topUnits];
var bottomMax = maxSizeData / inches[bottomUnits];
// now trim this down to useful block length
var topRounded = this.getBarLen(topMax);
var bottomRounded = this.getBarLen(bottomMax);
// and back to display units
topMax = topRounded / inches[curMapUnits] * inches[topUnits];
bottomMax = bottomRounded / inches[curMapUnits] * inches[bottomUnits];
// and to pixel units
var topPx = topMax / res;
var bottomPx = bottomMax / res;
// now set the pixel widths
// and the values inside them
if (this.eBottom.style.visibility == "visible"){
this.eBottom.style.width = Math.round(bottomPx) + "px";
this.eBottom.innerHTML = bottomRounded + " " + bottomUnits ;
}
if (this.eTop.style.visibility == "visible"){
this.eTop.style.width = Math.round(topPx) + "px";
this.eTop.innerHTML = topRounded + " " + topUnits;
}
},
CLASS_NAME: "OpenLayers.Control.ScaleLine"
});

View File

@ -1,562 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Handler/Feature.js
* @requires OpenLayers/Layer/Vector/RootContainer.js
*/
/**
* Class: OpenLayers.Control.SelectFeature
* The SelectFeature control selects vector features from a given layer on
* click or hover.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.SelectFeature = OpenLayers.Class(OpenLayers.Control, {
/**
* Constant: EVENT_TYPES
*
* Supported event types:
* - *beforefeaturehighlighted* Triggered before a feature is highlighted
* - *featurehighlighted* Triggered when a feature is highlighted
* - *featureunhighlighted* Triggered when a feature is unhighlighted
*/
EVENT_TYPES: ["beforefeaturehighlighted", "featurehighlighted", "featureunhighlighted"],
/**
* Property: multipleKey
* {String} An event modifier ('altKey' or 'shiftKey') that temporarily sets
* the <multiple> property to true. Default is null.
*/
multipleKey: null,
/**
* Property: toggleKey
* {String} An event modifier ('altKey' or 'shiftKey') that temporarily sets
* the <toggle> property to true. Default is null.
*/
toggleKey: null,
/**
* APIProperty: multiple
* {Boolean} Allow selection of multiple geometries. Default is false.
*/
multiple: false,
/**
* APIProperty: clickout
* {Boolean} Unselect features when clicking outside any feature.
* Default is true.
*/
clickout: true,
/**
* APIProperty: toggle
* {Boolean} Unselect a selected feature on click. Default is false. Only
* has meaning if hover is false.
*/
toggle: false,
/**
* APIProperty: hover
* {Boolean} Select on mouse over and deselect on mouse out. If true, this
* ignores clicks and only listens to mouse moves.
*/
hover: false,
/**
* APIProperty: highlightOnly
* {Boolean} If true do not actually select features (i.e. place them in the
* layer's selected features array), just highlight them. This property has
* no effect if hover is false. Defaults to false.
*/
highlightOnly: false,
/**
* APIProperty: box
* {Boolean} Allow feature selection by drawing a box.
*/
box: false,
/**
* Property: onBeforeSelect
* {Function} Optional function to be called before a feature is selected.
* The function should expect to be called with a feature.
*/
onBeforeSelect: function() {},
/**
* APIProperty: onSelect
* {Function} Optional function to be called when a feature is selected.
* The function should expect to be called with a feature.
*/
onSelect: function() {},
/**
* APIProperty: onUnselect
* {Function} Optional function to be called when a feature is unselected.
* The function should expect to be called with a feature.
*/
onUnselect: function() {},
/**
* Property: scope
* {Object} The scope to use with the onBeforeSelect, onSelect, onUnselect
* callbacks. If null the scope will be this control.
*/
scope: null,
/**
* APIProperty: geometryTypes
* {Array(String)} To restrict selecting to a limited set of geometry types,
* send a list of strings corresponding to the geometry class names.
*/
geometryTypes: null,
/**
* Property: layer
* {<OpenLayers.Layer.Vector>} The vector layer with a common renderer
* root for all layers this control is configured with (if an array of
* layers was passed to the constructor), or the vector layer the control
* was configured with (if a single layer was passed to the constructor).
*/
layer: null,
/**
* Property: layers
* {Array(<OpenLayers.Layer.Vector>} The layers this control will work on,
* or null if the control was configured with a single layer
*/
layers: null,
/**
* APIProperty: callbacks
* {Object} The functions that are sent to the handlers.feature for callback
*/
callbacks: null,
/**
* APIProperty: selectStyle
* {Object} Hash of styles
*/
selectStyle: null,
/**
* Property: renderIntent
* {String} key used to retrieve the select style from the layer's
* style map.
*/
renderIntent: "select",
/**
* Property: handlers
* {Object} Object with references to multiple <OpenLayers.Handler>
* instances.
*/
handlers: null,
/**
* Constructor: OpenLayers.Control.SelectFeature
* Create a new control for selecting features.
*
* Parameters:
* layers - {<OpenLayers.Layer.Vector>}, or an array of vector layers. The
* layer(s) this control will select features from.
* options - {Object}
*/
initialize: function(layers, options) {
// concatenate events specific to this control with those from the base
this.EVENT_TYPES =
OpenLayers.Control.SelectFeature.prototype.EVENT_TYPES.concat(
OpenLayers.Control.prototype.EVENT_TYPES
);
OpenLayers.Control.prototype.initialize.apply(this, [options]);
if(this.scope === null) {
this.scope = this;
}
if(layers instanceof Array) {
this.layers = layers;
this.layer = new OpenLayers.Layer.Vector.RootContainer(
this.id + "_container", {
layers: layers
}
);
} else {
this.layer = layers;
}
var callbacks = {
click: this.clickFeature,
clickout: this.clickoutFeature
};
if (this.hover) {
callbacks.over = this.overFeature;
callbacks.out = this.outFeature;
}
this.callbacks = OpenLayers.Util.extend(callbacks, this.callbacks);
this.handlers = {
feature: new OpenLayers.Handler.Feature(
this, this.layer, this.callbacks,
{geometryTypes: this.geometryTypes}
)
};
if (this.box) {
this.handlers.box = new OpenLayers.Handler.Box(
this, {done: this.selectBox},
{boxDivClassName: "olHandlerBoxSelectFeature"}
);
}
},
/**
* Method: destroy
*/
destroy: function() {
OpenLayers.Control.prototype.destroy.apply(this, arguments);
if(this.layers) {
this.layer.destroy();
}
},
/**
* Method: activate
* Activates the control.
*
* Returns:
* {Boolean} The control was effectively activated.
*/
activate: function () {
if (!this.active) {
if(this.layers) {
this.map.addLayer(this.layer);
}
this.handlers.feature.activate();
if(this.box && this.handlers.box) {
this.handlers.box.activate();
}
}
return OpenLayers.Control.prototype.activate.apply(
this, arguments
);
},
/**
* Method: deactivate
* Deactivates the control.
*
* Returns:
* {Boolean} The control was effectively deactivated.
*/
deactivate: function () {
if (this.active) {
this.handlers.feature.deactivate();
if(this.handlers.box) {
this.handlers.box.deactivate();
}
if(this.layers) {
this.map.removeLayer(this.layer);
}
}
return OpenLayers.Control.prototype.deactivate.apply(
this, arguments
);
},
/**
* Method: unselectAll
* Unselect all selected features. To unselect all except for a single
* feature, set the options.except property to the feature.
*
* Parameters:
* options - {Object} Optional configuration object.
*/
unselectAll: function(options) {
// we'll want an option to supress notification here
var layers = this.layers || [this.layer];
var layer, feature;
for(var l=0; l<layers.length; ++l) {
layer = layers[l];
for(var i=layer.selectedFeatures.length-1; i>=0; --i) {
feature = layer.selectedFeatures[i];
if(!options || options.except != feature) {
this.unselect(feature);
}
}
}
},
/**
* Method: clickFeature
* Called on click in a feature
* Only responds if this.hover is false.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
clickFeature: function(feature) {
if(!this.hover) {
var selected = (OpenLayers.Util.indexOf(
feature.layer.selectedFeatures, feature) > -1);
if(selected) {
if(this.toggleSelect()) {
this.unselect(feature);
} else if(!this.multipleSelect()) {
this.unselectAll({except: feature});
}
} else {
if(!this.multipleSelect()) {
this.unselectAll({except: feature});
}
this.select(feature);
}
}
},
/**
* Method: multipleSelect
* Allow for multiple selected features based on <multiple> property and
* <multipleKey> event modifier.
*
* Returns:
* {Boolean} Allow for multiple selected features.
*/
multipleSelect: function() {
return this.multiple || (this.handlers.feature.evt &&
this.handlers.feature.evt[this.multipleKey]);
},
/**
* Method: toggleSelect
* Event should toggle the selected state of a feature based on <toggle>
* property and <toggleKey> event modifier.
*
* Returns:
* {Boolean} Toggle the selected state of a feature.
*/
toggleSelect: function() {
return this.toggle || (this.handlers.feature.evt &&
this.handlers.feature.evt[this.toggleKey]);
},
/**
* Method: clickoutFeature
* Called on click outside a previously clicked (selected) feature.
* Only responds if this.hover is false.
*
* Parameters:
* feature - {<OpenLayers.Vector.Feature>}
*/
clickoutFeature: function(feature) {
if(!this.hover && this.clickout) {
this.unselectAll();
}
},
/**
* Method: overFeature
* Called on over a feature.
* Only responds if this.hover is true.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
overFeature: function(feature) {
var layer = feature.layer;
if(this.hover) {
if(this.highlightOnly) {
this.highlight(feature);
} else if(OpenLayers.Util.indexOf(
layer.selectedFeatures, feature) == -1) {
this.select(feature);
}
}
},
/**
* Method: outFeature
* Called on out of a selected feature.
* Only responds if this.hover is true.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
outFeature: function(feature) {
if(this.hover) {
if(this.highlightOnly) {
// we do nothing if we're not the last highlighter of the
// feature
if(feature._lastHighlighter == this.id) {
// if another select control had highlighted the feature before
// we did it ourself then we use that control to highlight the
// feature as it was before we highlighted it, else we just
// unhighlight it
if(feature._prevHighlighter &&
feature._prevHighlighter != this.id) {
delete feature._lastHighlighter;
var control = this.map.getControl(
feature._prevHighlighter);
if(control) {
control.highlight(feature);
}
} else {
this.unhighlight(feature);
}
}
} else {
this.unselect(feature);
}
}
},
/**
* Method: highlight
* Redraw feature with the select style.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
highlight: function(feature) {
var layer = feature.layer;
var cont = this.events.triggerEvent("beforefeaturehighlighted", {
feature : feature
});
if(cont !== false) {
feature._prevHighlighter = feature._lastHighlighter;
feature._lastHighlighter = this.id;
var style = this.selectStyle || this.renderIntent;
layer.drawFeature(feature, style);
this.events.triggerEvent("featurehighlighted", {feature : feature});
}
},
/**
* Method: unhighlight
* Redraw feature with the "default" style
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
unhighlight: function(feature) {
var layer = feature.layer;
feature._lastHighlighter = feature._prevHighlighter;
delete feature._prevHighlighter;
layer.drawFeature(feature, feature.style || feature.layer.style ||
"default");
this.events.triggerEvent("featureunhighlighted", {feature : feature});
},
/**
* Method: select
* Add feature to the layer's selectedFeature array, render the feature as
* selected, and call the onSelect function.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
select: function(feature) {
var cont = this.onBeforeSelect.call(this.scope, feature);
var layer = feature.layer;
if(cont !== false) {
cont = layer.events.triggerEvent("beforefeatureselected", {
feature: feature
});
if(cont !== false) {
layer.selectedFeatures.push(feature);
this.highlight(feature);
layer.events.triggerEvent("featureselected", {feature: feature});
this.onSelect.call(this.scope, feature);
}
}
},
/**
* Method: unselect
* Remove feature from the layer's selectedFeature array, render the feature as
* normal, and call the onUnselect function.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
unselect: function(feature) {
var layer = feature.layer;
// Store feature style for restoration later
this.unhighlight(feature);
OpenLayers.Util.removeItem(layer.selectedFeatures, feature);
layer.events.triggerEvent("featureunselected", {feature: feature});
this.onUnselect.call(this.scope, feature);
},
/**
* Method: selectBox
* Callback from the handlers.box set up when <box> selection is true
* on.
*
* Parameters:
* position - {<OpenLayers.Bounds> || <OpenLayers.Pixel> }
*/
selectBox: function(position) {
if (position instanceof OpenLayers.Bounds) {
var minXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.left, position.bottom)
);
var maxXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.right, position.top)
);
var bounds = new OpenLayers.Bounds(
minXY.lon, minXY.lat, maxXY.lon, maxXY.lat
);
// if multiple is false, first deselect currently selected features
if (!this.multipleSelect()) {
this.unselectAll();
}
// because we're using a box, we consider we want multiple selection
var prevMultiple = this.multiple;
this.multiple = true;
var layers = this.layers || [this.layer];
var layer;
for(var l=0; l<layers.length; ++l) {
layer = layers[l];
for(var i=0, len = layer.features.length; i<len; ++i) {
var feature = layer.features[i];
if (this.geometryTypes == null || OpenLayers.Util.indexOf(
this.geometryTypes, feature.geometry.CLASS_NAME) > -1) {
if (bounds.toGeometry().intersects(feature.geometry)) {
if (OpenLayers.Util.indexOf(layer.selectedFeatures, feature) == -1) {
this.select(feature);
}
}
}
}
}
this.multiple = prevMultiple;
}
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
this.handlers.feature.setMap(map);
if (this.box) {
this.handlers.box.setMap(map);
}
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
CLASS_NAME: "OpenLayers.Control.SelectFeature"
});

View File

@ -1,546 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Layer/Vector.js
*/
/**
* Class: OpenLayers.Control.Snapping
* Acts as a snapping agent while editing vector features.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Snapping = OpenLayers.Class(OpenLayers.Control, {
/**
* Constant: EVENT_TYPES
* {Array(String)} Supported application event types. Register a listener
* for a particular event with the following syntax:
* (code)
* control.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.
*
* Supported control event types (in addition to those from <OpenLayers.Control>):
* beforesnap - Triggered before a snap occurs. Listeners receive an
* event object with *point*, *x*, *y*, *distance*, *layer*, and
* *snapType* properties. The point property will be original point
* geometry considered for snapping. The x and y properties represent
* coordinates the point will receive. The distance is the distance
* of the snap. The layer is the target layer. The snapType property
* will be one of "node", "vertex", or "edge". Return false to stop
* snapping from occurring.
* snap - Triggered when a snap occurs. Listeners receive an event with
* *point*, *snapType*, *layer*, and *distance* properties. The point
* will be the location snapped to. The snapType will be one of "node",
* "vertex", or "edge". The layer will be the target layer. The
* distance will be the distance of the snap in map units.
* unsnap - Triggered when a vertex is unsnapped. Listeners receive an
* event with a *point* property.
*/
EVENT_TYPES: ["beforesnap", "snap", "unsnap"],
/**
* CONSTANT: DEFAULTS
* Default target properties.
*/
DEFAULTS: {
tolerance: 10,
node: true,
edge: true,
vertex: true
},
/**
* Property: greedy
* {Boolean} Snap to closest feature in first layer with an eligible
* feature. Default is true.
*/
greedy: true,
/**
* Property: precedence
* {Array} List representing precedence of different snapping types.
* Default is "node", "vertex", "edge".
*/
precedence: ["node", "vertex", "edge"],
/**
* Property: resolution
* {Float} The map resolution for the previously considered snap.
*/
resolution: null,
/**
* Property: geoToleranceCache
* {Object} A cache of geo-tolerances. Tolerance values (in map units) are
* calculated when the map resolution changes.
*/
geoToleranceCache: null,
/**
* Property: layer
* {<OpenLayers.Layer.Vector>} The current editable layer. Set at
* construction or after construction with <setLayer>.
*/
layer: null,
/**
* Property: feature
* {<OpenLayers.Feature.Vector>} The current editable feature.
*/
feature: null,
/**
* Property: point
* {<OpenLayers.Geometry.Point>} The currently snapped vertex.
*/
point: null,
/**
* Constructor: OpenLayers.Control.Snapping
* Creates a new snapping control. A control is constructed with an editable
* layer and a set of configuration objects for target layers. While the
* control is active, dragging vertices while drawing new features or
* modifying existing features on the editable layer will engage
* snapping to features on the target layers. Whether a vertex snaps to
* a feature on a target layer depends on the target layer configuration.
*
* Parameters:
* options - {Object} An object containing all configuration properties for
* the control.
*
* Valid options:
* layer - {OpenLayers.Layer.Vector} The editable layer. Features from this
* layer that are digitized or modified may have vertices snapped to
* features from any of the target layers.
* targets - {Array(Object | OpenLayers.Layer.Vector)} A list of objects for
* configuring target layers. See valid properties of the target
* objects below. If the items in the targets list are vector layers
* (instead of configuration objects), the defaults from the <defaults>
* property will apply. The editable layer itself may be a target
* layer - allowing newly created or edited features to be snapped to
* existing features from the same layer. If no targets are provided
* the layer given in the constructor (as <layer>) will become the
* initial target.
* defaults - {Object} An object with default properties to be applied
* to all target objects.
* greedy - {Boolean} Snap to closest feature in first target layer that
* applies. Default is true. If false, all features in all target
* layers will be checked and the closest feature in all target layers
* will be chosen. The greedy property determines if the order of the
* target layers is significant. By default, the order of the target
* layers is significant where layers earlier in the target layer list
* have precedence over layers later in the list. Within a single
* layer, the closest feature is always chosen for snapping. This
* property only determines whether the search for a closer feature
* continues after an eligible feature is found in a target layer.
*
* Valid target properties:
* layer - {OpenLayers.Layer.Vector} A target layer. Features from this
* layer will be eligible to act as snapping target for the editable
* layer.
* tolerance - {Float} The distance (in pixels) at which snapping may occur.
* Default is 10.
* node - {Boolean} Snap to nodes (first or last point in a geometry) in
* target layer. Default is true.
* nodeTolerance - {Float} Optional distance at which snapping may occur
* for nodes specifically. If none is provided, <tolerance> will be
* used.
* vertex - {Boolean} Snap to vertices in target layer. Default is true.
* vertexTolerance - {Float} Optional distance at which snapping may occur
* for vertices specifically. If none is provided, <tolerance> will be
* used.
* edge - {Boolean} Snap to edges in target layer. Default is true.
* edgeTolerance - {Float} Optional distance at which snapping may occur
* for edges specifically. If none is provided, <tolerance> will be
* used.
* filter - {OpenLayers.Filter} Optional filter to evaluate to determine if
* feature is eligible for snapping. If filter evaluates to true for a
* target feature a vertex may be snapped to the feature.
*/
initialize: function(options) {
// concatenate events specific to measure with those from the base
Array.prototype.push.apply(
this.EVENT_TYPES, OpenLayers.Control.prototype.EVENT_TYPES
);
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.options = options || {}; // TODO: this could be done by the super
// set the editable layer if provided
if(this.options.layer) {
this.setLayer(this.options.layer);
}
// configure target layers
var defaults = OpenLayers.Util.extend({}, this.options.defaults);
this.defaults = OpenLayers.Util.applyDefaults(defaults, this.DEFAULTS);
this.setTargets(this.options.targets);
if(this.targets.length === 0 && this.layer) {
this.addTargetLayer(this.layer);
}
this.geoToleranceCache = {};
},
/**
* APIMethod: setLayer
* Set the editable layer. Call the setLayer method if the editable layer
* changes and the same control should be used on a new editable layer.
* If the control is already active, it will be active after the new
* layer is set.
*
* Parameters:
* layer - {OpenLayers.Layer.Vector} The new editable layer.
*/
setLayer: function(layer) {
if(this.active) {
this.deactivate();
this.layer = layer;
this.activate();
} else {
this.layer = layer;
}
},
/**
* Method: setTargets
* Set the targets for the snapping agent.
*
* Parameters:
* targets - {Array} An array of target configs or target layers.
*/
setTargets: function(targets) {
this.targets = [];
if(targets && targets.length) {
var target;
for(var i=0, len=targets.length; i<len; ++i) {
target = targets[i];
if(target instanceof OpenLayers.Layer.Vector) {
this.addTargetLayer(target);
} else {
this.addTarget(target);
}
}
}
},
/**
* Method: addTargetLayer
* Add a target layer with the default target config.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>} A target layer.
*/
addTargetLayer: function(layer) {
this.addTarget({layer: layer});
},
/**
* Method: addTarget
* Add a configured target layer.
*
* Parameters:
* target - {Object} A target config.
*/
addTarget: function(target) {
target = OpenLayers.Util.applyDefaults(target, this.defaults);
target.nodeTolerance = target.nodeTolerance || target.tolerance;
target.vertexTolerance = target.vertexTolerance || target.tolerance;
target.edgeTolerance = target.edgeTolerance || target.tolerance;
this.targets.push(target);
},
/**
* Method: removeTargetLayer
* Remove a target layer.
*
* Parameters:
* layer - {<OpenLayers.Layer.Vector>} The target layer to remove.
*/
removeTargetLayer: function(layer) {
var target;
for(var i=this.targets.length-1; i>=0; --i) {
target = this.targets[i];
if(target.layer === layer) {
this.removeTarget(target);
}
}
},
/**
* Method: removeTarget
* Remove a target.
*
* Parameters:
* target - {Object} A target config.
*
* Returns:
* {Array} The targets array.
*/
removeTarget: function(target) {
return OpenLayers.Util.removeItem(this.targets, target);
},
/**
* APIMethod: activate
* Activate the control. Activating the control registers listeners for
* editing related events so that during feature creation and
* modification, moving vertices will trigger snapping.
*/
activate: function() {
var activated = OpenLayers.Control.prototype.activate.call(this);
if(activated) {
if(this.layer && this.layer.events) {
this.layer.events.on({
sketchstarted: this.onSketchModified,
sketchmodified: this.onSketchModified,
vertexmodified: this.onVertexModified,
scope: this
});
}
}
return activated;
},
/**
* APIMethod: deactivate
* Deactivate the control. Deactivating the control unregisters listeners
* so feature editing may proceed without engaging the snapping agent.
*/
deactivate: function() {
var deactivated = OpenLayers.Control.prototype.deactivate.call(this);
if(deactivated) {
if(this.layer && this.layer.events) {
this.layer.events.un({
sketchstarted: this.onSketchModified,
sketchmodified: this.onSketchModified,
vertexmodified: this.onVertexModified,
scope: this
});
}
}
this.feature = null;
this.point = null;
return deactivated;
},
/**
* Method: onSketchModified
* Registered as a listener for the sketchmodified event on the editable
* layer.
*
* Parameters:
* event - {Object} The sketch modified event.
*/
onSketchModified: function(event) {
this.feature = event.feature;
this.considerSnapping(event.vertex, event.vertex);
},
/**
* Method: onVertexModified
* Registered as a listener for the vertexmodified event on the editable
* layer.
*
* Parameters:
* event - {Object} The vertex modified event.
*/
onVertexModified: function(event) {
this.feature = event.feature;
var loc = this.layer.map.getLonLatFromViewPortPx(event.pixel);
this.considerSnapping(
event.vertex, new OpenLayers.Geometry.Point(loc.lon, loc.lat)
);
},
/**
* Method: considerSnapping
*
* Parameters:
* point - {<OpenLayers.Geometry.Point}} The vertex to be snapped (or
* unsnapped).
* loc - {<OpenLayers.Geometry.Point>} The location of the mouse in map
* coords.
*/
considerSnapping: function(point, loc) {
var best = {
rank: Number.POSITIVE_INFINITY,
dist: Number.POSITIVE_INFINITY,
x: null, y: null
};
var snapped = false;
var result, target;
for(var i=0, len=this.targets.length; i<len; ++i) {
target = this.targets[i];
result = this.testTarget(target, loc);
if(result) {
if(this.greedy) {
best = result;
best.target = target;
snapped = true;
break;
} else {
if((result.rank < best.rank) ||
(result.rank === best.rank && result.dist < best.dist)) {
best = result;
best.target = target;
snapped = true;
}
}
}
}
if(snapped) {
var proceed = this.events.triggerEvent("beforesnap", {
point: point, x: best.x, y: best.y, distance: best.dist,
layer: best.target.layer, snapType: this.precedence[best.rank]
});
if(proceed !== false) {
point.x = best.x;
point.y = best.y;
this.point = point;
this.events.triggerEvent("snap", {
point: point,
snapType: this.precedence[best.rank],
layer: best.target.layer,
distance: best.dist
});
} else {
snapped = false;
}
}
if(this.point && !snapped) {
point.x = loc.x;
point.y = loc.y;
this.point = null;
this.events.triggerEvent("unsnap", {point: point});
}
},
/**
* Method: testTarget
*
* Parameters:
* target - {Object} Object with target layer configuration.
* loc - {<OpenLayers.Geometry.Point>} The location of the mouse in map
* coords.
*
* Returns:
* {Object} A result object with rank, dist, x, and y properties.
* Returns null if candidate is not eligible for snapping.
*/
testTarget: function(target, loc) {
var tolerance = {
node: this.getGeoTolerance(target.nodeTolerance),
vertex: this.getGeoTolerance(target.vertexTolerance),
edge: this.getGeoTolerance(target.edgeTolerance)
};
// this could be cached if we don't support setting tolerance values directly
var maxTolerance = Math.max(
tolerance.node, tolerance.vertex, tolerance.edge
);
var result = {
rank: Number.POSITIVE_INFINITY, dist: Number.POSITIVE_INFINITY
};
var eligible = false;
var features = target.layer.features;
var feature, type, vertices, vertex, closest, dist, found;
var numTypes = this.precedence.length;
var ll = new OpenLayers.LonLat(loc.x, loc.y);
for(var i=0, len=features.length; i<len; ++i) {
feature = features[i];
if(feature !== this.feature && !feature._sketch &&
feature.state !== OpenLayers.State.DELETE &&
(!target.filter || target.filter.evaluate(feature.attributes))) {
if(feature.atPoint(ll, maxTolerance, maxTolerance)) {
for(var j=0, stop=Math.min(result.rank+1, numTypes); j<stop; ++j) {
type = this.precedence[j];
if(target[type]) {
if(type === "edge") {
closest = feature.geometry.distanceTo(loc, {details: true});
dist = closest.distance;
if(dist <= tolerance[type] && dist < result.dist) {
result = {
rank: j, dist: dist,
x: closest.x0, y: closest.y0 // closest coords on feature
};
eligible = true;
// don't look for lower precedence types for this feature
break;
}
} else {
// look for nodes or vertices
vertices = feature.geometry.getVertices(type === "node");
found = false;
for(var k=0, klen=vertices.length; k<klen; ++k) {
vertex = vertices[k];
dist = vertex.distanceTo(loc);
if(dist <= tolerance[type] &&
(j < result.rank || (j === result.rank && dist < result.dist))) {
result = {
rank: j, dist: dist,
x: vertex.x, y: vertex.y
};
eligible = true;
found = true;
}
}
if(found) {
// don't look for lower precedence types for this feature
break;
}
}
}
}
}
}
}
return eligible ? result : null;
},
/**
* Method: getGeoTolerance
* Calculate a tolerance in map units given a tolerance in pixels. This
* takes advantage of the <geoToleranceCache> when the map resolution
* has not changed.
*
* Parameters:
* tolerance - {Number} A tolerance value in pixels.
*
* Returns:
* {Number} A tolerance value in map units.
*/
getGeoTolerance: function(tolerance) {
var resolution = this.layer.map.getResolution();
if(resolution !== this.resolution) {
this.resolution = resolution;
this.geoToleranceCache = {};
}
var geoTolerance = this.geoToleranceCache[tolerance];
if(geoTolerance === undefined) {
geoTolerance = tolerance * resolution;
this.geoToleranceCache[tolerance] = geoTolerance;
}
return geoTolerance;
},
/**
* Method: destroy
* Clean up the control.
*/
destroy: function() {
if(this.active) {
this.deactivate(); // TODO: this should be handled by the super
}
delete this.layer;
delete this.targets;
OpenLayers.Control.prototype.destroy.call(this);
},
CLASS_NAME: "OpenLayers.Control.Snapping"
});

View File

@ -1,497 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Path.js
* @requires OpenLayers/Layer/Vector.js
*/
/**
* Class: OpenLayers.Control.Split
* Acts as a split feature agent while editing vector features.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.Split = OpenLayers.Class(OpenLayers.Control, {
/**
* Constant: EVENT_TYPES
* {Array(String)} Supported application event types. Register a listener
* for a particular event with the following syntax:
* (code)
* control.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.
*
* Supported control event types (in addition to those from <OpenLayers.Control>):
* beforesplit - Triggered before a split occurs. Listeners receive an
* event object with *source* and *target* properties.
* split - Triggered when a split occurs. Listeners receive an event with
* an *original* property and a *features* property. The original
* is a reference to the target feature that the sketch or modified
* feature intersects. The features property is a list of all features
* that result from this single split. This event is triggered before
* the resulting features are added to the layer (while the layer still
* has a reference to the original).
* aftersplit - Triggered after all splits resulting from a single sketch
* or feature modification have occurred. The original features
* have been destroyed and features that result from the split
* have already been added to the layer. Listeners receive an event
* with a *source* and *features* property. The source references the
* sketch or modified feature used as a splitter. The features
* property is a list of all resulting features.
*/
EVENT_TYPES: ["beforesplit", "split", "aftersplit"],
/**
* APIProperty: layer
* {<OpenLayers.Layer.Vector>} The target layer with features to be split.
* Set at construction or after construction with <setLayer>.
*/
layer: null,
/**
* Property: source
* {<OpenLayers.Layer.Vector>} Optional source layer. Any newly created
* or modified features from this layer will be used to split features
* on the target layer. If not provided, a temporary sketch layer will
* be created.
*/
source: null,
/**
* Property: sourceOptions
* {Options} If a temporary sketch layer is created, these layer options
* will be applied.
*/
sourceOptions: null,
/**
* APIProperty: tolerance
* {Number} Distance between the calculated intersection and a vertex on
* the source geometry below which the existing vertex will be used
* for the split. Default is null.
*/
tolerance: null,
/**
* APIProperty: edge
* {Boolean} Allow splits given intersection of edges only. Default is
* true. If false, a vertex on the source must be within the
* <tolerance> distance of the calculated intersection for a split
* to occur.
*/
edge: true,
/**
* APIProperty: deferDelete
* {Boolean} Instead of removing features from the layer, set feature
* states of split features to DELETE. This assumes a save strategy
* or other component is in charge of removing features from the
* layer. Default is false. If false, split features will be
* immediately deleted from the layer.
*/
deferDelete: false,
/**
* APIProperty: mutual
* {Boolean} If source and target layers are the same, split source
* features and target features where they intersect. Default is
* true. If false, only target features will be split.
*/
mutual: true,
/**
* APIProperty: targetFilter
* {OpenLayers.Filter} Optional filter that will be evaluated
* to determine if a feature from the target layer is eligible for
* splitting.
*/
targetFilter: null,
/**
* APIProperty: sourceFilter
* {OpenLayers.Filter} Optional filter that will be evaluated
* to determine if a feature from the target layer is eligible for
* splitting.
*/
sourceFilter: null,
/**
* Property: handler
* {<OpenLayers.Handler.Path>} The temporary sketch handler created if
* no source layer is provided.
*/
handler: null,
/**
* Constructor: OpenLayers.Control.Split
* Creates a new split control. A control is constructed with a target
* layer and an optional source layer. While the control is active,
* creating new features or modifying existing features on the source
* layer will result in splitting any eligible features on the target
* layer. If no source layer is provided, a temporary sketch layer will
* be created to create lines for splitting features on the target.
*
* Parameters:
* options - {Object} An object containing all configuration properties for
* the control.
*
* Valid options:
* layer - {OpenLayers.Layer.Vector} The target layer. Features from this
* layer will be split by new or modified features on the source layer
* or temporary sketch layer.
* source - {OpenLayers.Layer.Vector} Optional source layer. If provided
* newly created features or modified features will be used to split
* features on the target layer. If not provided, a temporary sketch
* layer will be created for drawing lines.
* tolerance - {Number} Optional value for the distance between a source
* vertex and the calculated intersection below which the split will
* occur at the vertex.
* edge - {Boolean} Allow splits given intersection of edges only. Default
* is true. If false, a vertex on the source must be within the
* <tolerance> distance of the calculated intersection for a split
* to occur.
* mutual - {Boolean} If source and target are the same, split source
* features and target features where they intersect. Default is
* true. If false, only target features will be split.
* targetFilter - {OpenLayers.Filter} Optional filter that will be evaluated
* to determine if a feature from the target layer is eligible for
* splitting.
* sourceFilter - {OpenLayers.Filter} Optional filter that will be evaluated
* to determine if a feature from the target layer is eligible for
* splitting.
*/
initialize: function(options) {
// concatenate events specific to measure with those from the base
Array.prototype.push.apply(
this.EVENT_TYPES, OpenLayers.Control.prototype.EVENT_TYPES
);
OpenLayers.Control.prototype.initialize.apply(this, [options]);
this.options = options || {}; // TODO: this could be done by the super
// set the source layer if provided
if(this.options.source) {
this.setSource(this.options.source);
}
},
/**
* APIMethod: setSource
* Set the source layer for edits layer.
*
* Parameters:
* layer - {OpenLayers.Layer.Vector} The new source layer layer. If
* null, a temporary sketch layer will be created.
*/
setSource: function(layer) {
if(this.active) {
this.deactivate();
if(this.handler) {
this.handler.destroy();
delete this.handler;
}
this.source = layer;
this.activate();
} else {
this.source = layer;
}
},
/**
* APIMethod: activate
* Activate the control. Activating the control registers listeners for
* editing related events so that during feature creation and
* modification, features in the target will be considered for
* splitting.
*/
activate: function() {
var activated = OpenLayers.Control.prototype.activate.call(this);
if(activated) {
if(!this.source) {
if(!this.handler) {
this.handler = new OpenLayers.Handler.Path(this,
{done: function(geometry) {
this.onSketchComplete({
feature: new OpenLayers.Feature.Vector(geometry)
});
}},
{layerOptions: this.sourceOptions}
);
}
this.handler.activate();
} else if(this.source.events) {
this.source.events.on({
sketchcomplete: this.onSketchComplete,
afterfeaturemodified: this.afterFeatureModified,
scope: this
});
}
}
return activated;
},
/**
* APIMethod: deactivate
* Deactivate the control. Deactivating the control unregisters listeners
* so feature editing may proceed without engaging the split agent.
*/
deactivate: function() {
var deactivated = OpenLayers.Control.prototype.deactivate.call(this);
if(deactivated) {
if(this.source && this.source.events) {
this.layer.events.un({
sketchcomplete: this.onSketchComplete,
afterfeaturemodified: this.afterFeatureModified,
scope: this
});
}
}
return deactivated;
},
/**
* Method: onSketchComplete
* Registered as a listener for the sketchcomplete event on the editable
* layer.
*
* Parameters:
* event - {Object} The sketch complete event.
*
* Returns:
* {Boolean} Stop the sketch from being added to the layer (it has been
* split).
*/
onSketchComplete: function(event) {
this.feature = null;
return !this.considerSplit(event.feature);
},
/**
* Method: afterFeatureModified
* Registered as a listener for the afterfeaturemodified event on the
* editable layer.
*
* Parameters:
* event - {Object} The after feature modified event.
*/
afterFeatureModified: function(event) {
if(event.modified) {
var feature = event.feature;
if(feature.geometry instanceof OpenLayers.Geometry.LineString ||
feature.geometry instanceof OpenLayers.Geometry.MultiLineString) {
this.feature = event.feature;
this.considerSplit(event.feature);
}
}
},
/**
* Method: removeByGeometry
* Remove a feature from a list based on the given geometry.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>} A list of features.
* geometry - {<OpenLayers.Geometry>} A geometry.
*/
removeByGeometry: function(features, geometry) {
for(var i=0, len=features.length; i<len; ++i) {
if(features[i].geometry === geometry) {
features.splice(i, 1);
break;
}
}
},
/**
* Method: isEligible
* Test if a target feature is eligible for splitting.
*
* Parameters:
* target - {<OpenLayers.Feature.Vector>} The target feature.
*
* Returns:
* {Boolean} The target is eligible for splitting.
*/
isEligible: function(target) {
return (
target.state !== OpenLayers.State.DELETE
) && (
target.geometry instanceof OpenLayers.Geometry.LineString ||
target.geometry instanceof OpenLayers.Geometry.MultiLineString
) && (
this.feature !== target
) && (
!this.targetFilter ||
this.targetFilter.evaluate(target.attributes)
);
},
/**
* Method: considerSplit
* Decide whether or not to split target features with the supplied
* feature. If <mutual> is true, both the source and target features
* will be split if eligible.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector}} The newly created or modified
* feature.
*
* Returns:
* {Boolean} The supplied feature was split (and destroyed).
*/
considerSplit: function(feature) {
sourceSplit = false;
targetSplit = false;
if(!this.sourceFilter ||
this.sourceFilter.evaluate(feature.attributes)) {
var features = this.layer && this.layer.features || [];
var target, results, result, proceed;
var additions = [], removals = [];
var mutual = (this.layer === this.source) && this.mutual;
var options = {
edge: this.edge,
tolerance: this.tolerance,
mutual: mutual
};
var sourceParts = [feature.geometry];
var targetFeature, targetParts;
var source, parts;
for(var i=0, len=features.length; i<len; ++i) {
targetFeature = features[i];
if(this.isEligible(targetFeature)) {
targetParts = [targetFeature.geometry];
// work through source geoms - this array may change
for(var j=0; j<sourceParts.length; ++j) {
source = sourceParts[j];
// work through target parts - this array may change
for(var k=0; k<targetParts.length; ++k) {
target = targetParts[k];
if(source.getBounds().intersectsBounds(target.getBounds())) {
results = source.split(target, options);
if(results) {
proceed = this.events.triggerEvent(
"beforesplit", {source: feature, target: targetFeature}
);
if(proceed !== false) {
if(mutual) {
parts = results[0];
// handle parts that result from source splitting
if(parts.length > 1) {
// splice in new source parts
parts.unshift(j, 1); // add args for splice below
Array.prototype.splice.apply(sourceParts, parts);
j += parts.length - 3;
}
results = results[1];
}
// handle parts that result from target splitting
if(results.length > 1) {
// splice in new target parts
results.unshift(k, 1); // add args for splice below
Array.prototype.splice.apply(targetParts, results);
k += results.length - 3;
}
}
}
}
}
}
if(targetParts && targetParts.length > 1) {
this.geomsToFeatures(targetFeature, targetParts);
this.events.triggerEvent("split", {
original: targetFeature,
features: targetParts
});
Array.prototype.push.apply(additions, targetParts);
removals.push(targetFeature);
targetSplit = true;
}
}
}
if(sourceParts && sourceParts.length > 1) {
this.geomsToFeatures(feature, sourceParts);
this.events.triggerEvent("split", {
original: feature,
features: sourceParts
});
Array.prototype.push.apply(additions, sourceParts);
removals.push(feature);
sourceSplit = true;
}
if(sourceSplit || targetSplit) {
// remove and add feature events are suppressed
// listen for split event on this control instead
if(this.deferDelete) {
// Set state instead of removing. Take care to avoid
// setting delete for features that have not yet been
// inserted - those should be destroyed immediately.
var feat, destroys = [];
for(var i=0, len=removals.length; i<len; ++i) {
feat = removals[i];
if(feat.state === OpenLayers.State.INSERT) {
destroys.push(feat);
} else {
feat.state = OpenLayers.State.DELETE;
this.layer.drawFeature(feat);
}
}
this.layer.destroyFeatures(destroys, {silent: true});
for(var i=0, len=additions.length; i<len; ++i) {
additions[i].state = OpenLayers.State.INSERT;
}
} else {
this.layer.destroyFeatures(removals, {silent: true});
}
this.layer.addFeatures(additions, {silent: true});
this.events.triggerEvent("aftersplit", {
source: feature,
features: additions
});
}
}
return sourceSplit;
},
/**
* Method: geomsToFeatures
* Create new features given a template feature and a list of geometries.
* The list of geometries is modified in place. The result will be
* a list of new features.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature to be cloned.
* geoms - {Array(<OpenLayers.Geometry>)} List of goemetries. This will
* become a list of new features.
*/
geomsToFeatures: function(feature, geoms) {
var clone = feature.clone();
delete clone.geometry;
var newFeature;
for(var i=0, len=geoms.length; i<len; ++i) {
// turn results list from geoms to features
newFeature = clone.clone();
newFeature.geometry = geoms[i];
newFeature.state = OpenLayers.State.INSERT;
geoms[i] = newFeature;
}
},
/**
* Method: destroy
* Clean up the control.
*/
destroy: function() {
if(this.active) {
this.deactivate(); // TODO: this should be handled by the super
}
OpenLayers.Control.prototype.destroy.call(this);
},
CLASS_NAME: "OpenLayers.Control.Split"
});

View File

@ -1,415 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Click.js
* @requires OpenLayers/Handler/Hover.js
* @requires OpenLayers/Request.js
*/
/**
* Class: OpenLayers.Control.WMSGetFeatureInfo
* The WMSGetFeatureInfo control uses a WMS query to get information about a point on the map. The
* information may be in a display-friendly format such as HTML, or a machine-friendly format such
* as GML, depending on the server's capabilities and the client's configuration. This control
* handles click or hover events, attempts to parse the results using an OpenLayers.Format, and
* fires a 'getfeatureinfo' event with the click position, the raw body of the response, and an
* array of features if it successfully read the response.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.WMSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: hover
* {Boolean} Send GetFeatureInfo requests when mouse stops moving.
* Default is false.
*/
hover: false,
/**
* APIProperty: maxFeatures
* {Integer} Maximum number of features to return from a WMS query. This
* sets the feature_count parameter on WMS GetFeatureInfo
* requests.
*/
maxFeatures: 10,
/**
* Property: layers
* {Array(<OpenLayers.Layer.WMS>)} The layers to query for feature info.
* If omitted, all map WMS layers with a url that matches this <url> or
* <layerUrl> will be considered.
*/
layers: null,
/**
* Property: queryVisible
* {Boolean} If true, filter out hidden layers when searching the map for
* layers to query. Default is false.
*/
queryVisible: false,
/**
* Property: url
* {String} The URL of the WMS service to use. If not provided, the url
* of the first eligible layer will be used.
*/
url: null,
/**
* Property: layerUrls
* {Array(String)} Optional list of urls for layers that should be queried.
* This can be used when the layer url differs from the url used for
* making GetFeatureInfo requests (in the case of a layer using cached
* tiles).
*/
layerUrls: null,
/**
* Property: infoFormat
* {String} The mimetype to request from the server
*/
infoFormat: 'text/html',
/**
* Property: vendorParams
* {Object} Additional parameters that will be added to the request, for
* WMS implementations that support them. This could e.g. look like
* (start code)
* {
* radius: 5
* }
* (end)
*/
vendorParams: {},
/**
* Property: format
* {<OpenLayers.Format>} A format for parsing GetFeatureInfo responses.
* Default is <OpenLayers.Format.WMSGetFeatureInfo>.
*/
format: null,
/**
* Property: formatOptions
* {Object} Optional properties to set on the format (if one is not provided
* in the <format> property.
*/
formatOptions: null,
/**
* APIProperty: handlerOptions
* {Object} Additional options for the handlers used by this control, e.g.
* (start code)
* {
* "click": {delay: 100},
* "hover": {delay: 300}
* }
* (end)
*/
handlerOptions: null,
/**
* Property: handler
* {Object} Reference to the <OpenLayers.Handler> for this control
*/
handler: null,
/**
* Property: hoverRequest
* {<OpenLayers.Request>} contains the currently running hover request
* (if any).
*/
hoverRequest: null,
/**
* Constant: EVENT_TYPES
*
* Supported event types (in addition to those from <OpenLayers.Control>):
* getfeatureinfo - Triggered when a GetFeatureInfo response is received.
* The event object has a *text* property with the body of the
* response (String), a *features* property with an array of the
* parsed features, an *xy* property with the position of the mouse
* click or hover event that triggered the request, and a *request*
* property with the request itself.
*/
EVENT_TYPES: ["getfeatureinfo"],
/**
* Constructor: <OpenLayers.Control.WMSGetFeatureInfo>
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
// concatenate events specific to vector with those from the base
this.EVENT_TYPES =
OpenLayers.Control.WMSGetFeatureInfo.prototype.EVENT_TYPES.concat(
OpenLayers.Control.prototype.EVENT_TYPES
);
options = options || {};
options.handlerOptions = options.handlerOptions || {};
OpenLayers.Control.prototype.initialize.apply(this, [options]);
if(!this.format) {
this.format = new OpenLayers.Format.WMSGetFeatureInfo(
options.formatOptions
);
}
if (this.hover) {
this.handler = new OpenLayers.Handler.Hover(
this, {
'move': this.cancelHover,
'pause': this.getInfoForHover
},
OpenLayers.Util.extend(this.handlerOptions.hover || {}, {
'delay': 250
}));
} else {
this.handler = new OpenLayers.Handler.Click(this,
{click: this.getInfoForClick}, this.handlerOptions.click || {});
}
},
/**
* Method: activate
* Activates the control.
*
* Returns:
* {Boolean} The control was effectively activated.
*/
activate: function () {
if (!this.active) {
this.handler.activate();
}
return OpenLayers.Control.prototype.activate.apply(
this, arguments
);
},
/**
* Method: deactivate
* Deactivates the control.
*
* Returns:
* {Boolean} The control was effectively deactivated.
*/
deactivate: function () {
return OpenLayers.Control.prototype.deactivate.apply(
this, arguments
);
},
/**
* Method: getInfoForClick
* Called on click
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
getInfoForClick: function(evt) {
// Set the cursor to "wait" to tell the user we're working on their
// click.
OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait");
this.request(evt.xy, {});
},
/**
* Method: getInfoForHover
* Pause callback for the hover handler
*
* Parameters:
* evt - {Object}
*/
getInfoForHover: function(evt) {
this.request(evt.xy, {hover: true});
},
/**
* Method: cancelHover
* Cancel callback for the hover handler
*/
cancelHover: function() {
if (this.hoverRequest) {
this.hoverRequest.abort();
this.hoverRequest = null;
}
},
/**
* Method: findLayers
* Internal method to get the layers, independent of whether we are
* inspecting the map or using a client-provided array
*/
findLayers: function() {
var layers = [];
var candidates = this.layers || this.map.layers;
var layer, url;
for(var i=0, len=candidates.length; i<len; ++i) {
layer = candidates[i];
if(layer instanceof OpenLayers.Layer.WMS &&
(!this.queryVisible || layer.getVisibility())) {
url = layer.url instanceof Array ? layer.url[0] : layer.url;
// if the control was not configured with a url, set it
// to the first layer url
if(!this.url) {
this.url = url;
}
if(this.urlMatches(url)) {
layers.push(layer);
}
}
}
return layers;
},
/**
* Method: urlMatches
* Test to see if the provided url matches either the control <url> or one
* of the <layerUrls>.
*
* Parameters:
* url - {String} The url to test.
*
* Returns:
* {Boolean} The provided url matches the control <url> or one of the
* <layerUrls>.
*/
urlMatches: function(url) {
var matches = OpenLayers.Util.isEquivalentUrl(this.url, url);
if(!matches && this.layerUrls) {
for(var i=0, len=this.layerUrls.length; i<len; ++i) {
if(OpenLayers.Util.isEquivalentUrl(this.layerUrls[i], url)) {
matches = true;
break;
}
}
}
return matches;
},
/**
* Method: request
* Sends a GetFeatureInfo request to the WMS
*
* Parameters:
* clickPosition - {<OpenLayers.Pixel>} The position on the map where the
* mouse event occurred.
* options - {Object} additional options for this method.
*
* Valid options:
* - *hover* {Boolean} true if we do the request for the hover handler
*/
request: function(clickPosition, options) {
options = options || {};
var layerNames = [];
var styleNames = [];
var layers = this.findLayers();
if(layers.length > 0) {
for (var i = 0, len = layers.length; i < len; i++) {
layerNames = layerNames.concat(layers[i].params.LAYERS);
// in the event of a WMS layer bundling multiple layers but not
// specifying styles,we need the same number of commas to specify
// the default style for each of the layers. We can't just leave it
// blank as we may be including other layers that do specify styles.
if (layers[i].params.STYLES) {
styleNames = styleNames.concat(layers[i].params.STYLES);
} else {
if (layers[i].params.LAYERS instanceof Array) {
styleNames = styleNames.concat(new Array(layers[i].params.LAYERS.length));
} else { // Assume it's a String
styleNames = styleNames.concat(layers[i].params.LAYERS.replace(/[^,]/g, ""));
}
}
}
var wmsOptions = {
url: this.url,
params: OpenLayers.Util.applyDefaults({
service: "WMS",
version: "1.1.0",
request: "GetFeatureInfo",
layers: layerNames,
query_layers: layerNames,
styles: styleNames,
bbox: this.map.getExtent().toBBOX(),
srs: this.map.getProjection(),
feature_count: this.maxFeatures,
x: clickPosition.x,
y: clickPosition.y,
height: this.map.getSize().h,
width: this.map.getSize().w,
info_format: this.infoFormat
}, this.vendorParams),
callback: function(request) {
this.handleResponse(clickPosition, request);
},
scope: this
};
var response = OpenLayers.Request.GET(wmsOptions);
if (options.hover === true) {
this.hoverRequest = response.priv;
}
} else {
// Reset the cursor.
OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
}
},
/**
* Method: handleResponse
* Handler for the GetFeatureInfo response.
*
* Parameters:
* xy - {<OpenLayers.Pixel>} The position on the map where the
* mouse event occurred.
* request - {XMLHttpRequest} The request object.
*/
handleResponse: function(xy, request) {
var doc = request.responseXML;
if(!doc || !doc.documentElement) {
doc = request.responseText;
}
var features = this.format.read(doc);
this.events.triggerEvent("getfeatureinfo", {
text: request.responseText,
features: features,
request: request,
xy: xy
});
// Reset the cursor.
OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
},
/**
* Method: setMap
* Set the map property for the control.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
this.handler.setMap(map);
OpenLayers.Control.prototype.setMap.apply(this, arguments);
},
CLASS_NAME: "OpenLayers.Control.WMSGetFeatureInfo"
});

View File

@ -1,93 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Box.js
*/
/**
* Class: OpenLayers.Control.ZoomBox
* The ZoomBox control enables zooming directly to a given extent, by drawing
* a box on the map. The box is drawn by holding down shift, whilst dragging
* the mouse.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ZoomBox = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {OpenLayers.Control.TYPE}
*/
type: OpenLayers.Control.TYPE_TOOL,
/**
* Property: out
* {Boolean} Should the control be used for zooming out?
*/
out: false,
/**
* Property: alwaysZoom
* {Boolean} Always zoom in/out, when box drawed
*/
alwaysZoom: false,
/**
* Method: draw
*/
draw: function() {
this.handler = new OpenLayers.Handler.Box( this,
{done: this.zoomBox}, {keyMask: this.keyMask} );
},
/**
* Method: zoomBox
*
* Parameters:
* position - {<OpenLayers.Bounds>} or {<OpenLayers.Pixel>}
*/
zoomBox: function (position) {
if (position instanceof OpenLayers.Bounds) {
if (!this.out) {
var minXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.left, position.bottom));
var maxXY = this.map.getLonLatFromPixel(
new OpenLayers.Pixel(position.right, position.top));
var bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat,
maxXY.lon, maxXY.lat);
} else {
var pixWidth = Math.abs(position.right-position.left);
var pixHeight = Math.abs(position.top-position.bottom);
var zoomFactor = Math.min((this.map.size.h / pixHeight),
(this.map.size.w / pixWidth));
var extent = this.map.getExtent();
var center = this.map.getLonLatFromPixel(
position.getCenterPixel());
var xmin = center.lon - (extent.getWidth()/2)*zoomFactor;
var xmax = center.lon + (extent.getWidth()/2)*zoomFactor;
var ymin = center.lat - (extent.getHeight()/2)*zoomFactor;
var ymax = center.lat + (extent.getHeight()/2)*zoomFactor;
var bounds = new OpenLayers.Bounds(xmin, ymin, xmax, ymax);
}
// always zoom in/out
var lastZoom = this.map.getZoom();
this.map.zoomToExtent(bounds);
if (lastZoom == this.map.getZoom() && this.alwaysZoom == true){
this.map.zoomTo(lastZoom + (this.out ? -1 : 1));
}
} else { // it's a pixel
if (!this.out) {
this.map.setCenter(this.map.getLonLatFromPixel(position),
this.map.getZoom() + 1);
} else {
this.map.setCenter(this.map.getLonLatFromPixel(position),
this.map.getZoom() - 1);
}
}
},
CLASS_NAME: "OpenLayers.Control.ZoomBox"
});

View File

@ -1,34 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.ZoomIn
* The ZoomIn control is a button to increase the zoom level of a map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ZoomIn = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {String} The type of <OpenLayers.Control> -- When added to a
* <Control.Panel>, 'type' is used by the panel to determine how to
* handle our events.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/**
* Method: trigger
*/
trigger: function(){
this.map.zoomIn();
},
CLASS_NAME: "OpenLayers.Control.ZoomIn"
});

View File

@ -1,34 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.ZoomOut
* The ZoomOut control is a button to decrease the zoom level of a map.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ZoomOut = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {String} The type of <OpenLayers.Control> -- When added to a
* <Control.Panel>, 'type' is used by the panel to determine how to
* handle our events.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/**
* Method: trigger
*/
trigger: function(){
this.map.zoomOut();
},
CLASS_NAME: "OpenLayers.Control.ZoomOut"
});

View File

@ -1,53 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control/Panel.js
* @requires OpenLayers/Control/ZoomIn.js
* @requires OpenLayers/Control/ZoomOut.js
* @requires OpenLayers/Control/ZoomToMaxExtent.js
*/
/**
* Class: OpenLayers.Control.ZoomPanel
* The ZoomPanel control is a compact collecton of 3 zoom controls: a
* <OpenLayers.Control.ZoomIn>, a <OpenLayers.Control.ZoomToMaxExtent>, and a
* <OpenLayers.Control.ZoomOut>. By default it is drawn in the upper left
* corner of the map.
*
* Note:
* If you wish to use this class with the default images and you want
* it to look nice in ie6, you should add the following, conditionally
* added css stylesheet to your HTML file:
*
* (code)
* <!--[if lte IE 6]>
* <link rel="stylesheet" href="../theme/default/ie6-style.css" type="text/css" />
* <![endif]-->
* (end)
*
* Inherits from:
* - <OpenLayers.Control.Panel>
*/
OpenLayers.Control.ZoomPanel = OpenLayers.Class(OpenLayers.Control.Panel, {
/**
* Constructor: OpenLayers.Control.ZoomPanel
* Add the three zooming controls.
*
* Parameters:
* options - {Object} An optional object whose properties will be used
* to extend the control.
*/
initialize: function(options) {
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls([
new OpenLayers.Control.ZoomIn(),
new OpenLayers.Control.ZoomToMaxExtent(),
new OpenLayers.Control.ZoomOut()
]);
},
CLASS_NAME: "OpenLayers.Control.ZoomPanel"
});

View File

@ -1,39 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
*/
/**
* Class: OpenLayers.Control.ZoomToMaxExtent
* The ZoomToMaxExtent control is a button that zooms out to the maximum
* extent of the map. It is designed to be used with a
* <OpenLayers.Control.Panel>.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.ZoomToMaxExtent = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: type
* {String} The type of <OpenLayers.Control> -- When added to a
* <Control.Panel>, 'type' is used by the panel to determine how to
* handle our events.
*/
type: OpenLayers.Control.TYPE_BUTTON,
/*
* Method: trigger
* Do the zoom.
*/
trigger: function() {
if (this.map) {
this.map.zoomToMaxExtent();
}
},
CLASS_NAME: "OpenLayers.Control.ZoomToMaxExtent"
});

View File

@ -1,828 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Util.js
*/
/**
* Namespace: OpenLayers.Event
* Utility functions for event handling.
*/
OpenLayers.Event = {
/**
* Property: observers
* {Object} A hashtable cache of the event observers. Keyed by
* element._eventCacheID
*/
observers: false,
/**
* Constant: KEY_BACKSPACE
* {int}
*/
KEY_BACKSPACE: 8,
/**
* Constant: KEY_TAB
* {int}
*/
KEY_TAB: 9,
/**
* Constant: KEY_RETURN
* {int}
*/
KEY_RETURN: 13,
/**
* Constant: KEY_ESC
* {int}
*/
KEY_ESC: 27,
/**
* Constant: KEY_LEFT
* {int}
*/
KEY_LEFT: 37,
/**
* Constant: KEY_UP
* {int}
*/
KEY_UP: 38,
/**
* Constant: KEY_RIGHT
* {int}
*/
KEY_RIGHT: 39,
/**
* Constant: KEY_DOWN
* {int}
*/
KEY_DOWN: 40,
/**
* Constant: KEY_DELETE
* {int}
*/
KEY_DELETE: 46,
/**
* Method: element
* Cross browser event element detection.
*
* Parameters:
* event - {Event}
*
* Returns:
* {DOMElement} The element that caused the event
*/
element: function(event) {
return event.target || event.srcElement;
},
/**
* Method: isLeftClick
* Determine whether event was caused by a left click.
*
* Parameters:
* event - {Event}
*
* Returns:
* {Boolean}
*/
isLeftClick: function(event) {
return (((event.which) && (event.which == 1)) ||
((event.button) && (event.button == 1)));
},
/**
* Method: isRightClick
* Determine whether event was caused by a right mouse click.
*
* Parameters:
* event - {Event}
*
* Returns:
* {Boolean}
*/
isRightClick: function(event) {
return (((event.which) && (event.which == 3)) ||
((event.button) && (event.button == 2)));
},
/**
* Method: stop
* Stops an event from propagating.
*
* Parameters:
* event - {Event}
* allowDefault - {Boolean} If true, we stop the event chain but
* still allow the default browser
* behaviour (text selection, radio-button
* clicking, etc)
* Default false
*/
stop: function(event, allowDefault) {
if (!allowDefault) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
/**
* Method: findElement
*
* Parameters:
* event - {Event}
* tagName - {String}
*
* Returns:
* {DOMElement} The first node with the given tagName, starting from the
* node the event was triggered on and traversing the DOM upwards
*/
findElement: function(event, tagName) {
var element = OpenLayers.Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase()))){
element = element.parentNode;
}
return element;
},
/**
* Method: observe
*
* Parameters:
* elementParam - {DOMElement || String}
* name - {String}
* observer - {function}
* useCapture - {Boolean}
*/
observe: function(elementParam, name, observer, useCapture) {
var element = OpenLayers.Util.getElement(elementParam);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.attachEvent)) {
name = 'keydown';
}
//if observers cache has not yet been created, create it
if (!this.observers) {
this.observers = {};
}
//if not already assigned, make a new unique cache ID
if (!element._eventCacheID) {
var idPrefix = "eventCacheID_";
if (element.id) {
idPrefix = element.id + "_" + idPrefix;
}
element._eventCacheID = OpenLayers.Util.createUniqueID(idPrefix);
}
var cacheID = element._eventCacheID;
//if there is not yet a hash entry for this element, add one
if (!this.observers[cacheID]) {
this.observers[cacheID] = [];
}
//add a new observer to this element's list
this.observers[cacheID].push({
'element': element,
'name': name,
'observer': observer,
'useCapture': useCapture
});
//add the actual browser event listener
if (element.addEventListener) {
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
element.attachEvent('on' + name, observer);
}
},
/**
* Method: stopObservingElement
* Given the id of an element to stop observing, cycle through the
* element's cached observers, calling stopObserving on each one,
* skipping those entries which can no longer be removed.
*
* parameters:
* elementParam - {DOMElement || String}
*/
stopObservingElement: function(elementParam) {
var element = OpenLayers.Util.getElement(elementParam);
var cacheID = element._eventCacheID;
this._removeElementObservers(OpenLayers.Event.observers[cacheID]);
},
/**
* Method: _removeElementObservers
*
* Parameters:
* elementObservers - {Array(Object)} Array of (element, name,
* observer, usecapture) objects,
* taken directly from hashtable
*/
_removeElementObservers: function(elementObservers) {
if (elementObservers) {
for(var i = elementObservers.length-1; i >= 0; i--) {
var entry = elementObservers[i];
var args = new Array(entry.element,
entry.name,
entry.observer,
entry.useCapture);
var removed = OpenLayers.Event.stopObserving.apply(this, args);
}
}
},
/**
* Method: stopObserving
*
* Parameters:
* elementParam - {DOMElement || String}
* name - {String}
* observer - {function}
* useCapture - {Boolean}
*
* Returns:
* {Boolean} Whether or not the event observer was removed
*/
stopObserving: function(elementParam, name, observer, useCapture) {
useCapture = useCapture || false;
var element = OpenLayers.Util.getElement(elementParam);
var cacheID = element._eventCacheID;
if (name == 'keypress') {
if ( navigator.appVersion.match(/Konqueror|Safari|KHTML/) ||
element.detachEvent) {
name = 'keydown';
}
}
// find element's entry in this.observers cache and remove it
var foundEntry = false;
var elementObservers = OpenLayers.Event.observers[cacheID];
if (elementObservers) {
// find the specific event type in the element's list
var i=0;
while(!foundEntry && i < elementObservers.length) {
var cacheEntry = elementObservers[i];
if ((cacheEntry.name == name) &&
(cacheEntry.observer == observer) &&
(cacheEntry.useCapture == useCapture)) {
elementObservers.splice(i, 1);
if (elementObservers.length == 0) {
delete OpenLayers.Event.observers[cacheID];
}
foundEntry = true;
break;
}
i++;
}
}
//actually remove the event listener from browser
if (foundEntry) {
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element && element.detachEvent) {
element.detachEvent('on' + name, observer);
}
}
return foundEntry;
},
/**
* Method: unloadCache
* Cycle through all the element entries in the events cache and call
* stopObservingElement on each.
*/
unloadCache: function() {
// check for OpenLayers.Event before checking for observers, because
// OpenLayers.Event may be undefined in IE if no map instance was
// created
if (OpenLayers.Event && OpenLayers.Event.observers) {
for (var cacheID in OpenLayers.Event.observers) {
var elementObservers = OpenLayers.Event.observers[cacheID];
OpenLayers.Event._removeElementObservers.apply(this,
[elementObservers]);
}
OpenLayers.Event.observers = false;
}
},
CLASS_NAME: "OpenLayers.Event"
};
/* prevent memory leaks in IE */
OpenLayers.Event.observe(window, 'unload', OpenLayers.Event.unloadCache, false);
// FIXME: Remove this in 3.0. In 3.0, Event.stop will no longer be provided
// by OpenLayers.
if (window.Event) {
OpenLayers.Util.applyDefaults(window.Event, OpenLayers.Event);
} else {
var Event = OpenLayers.Event;
}
/**
* Class: OpenLayers.Events
*/
OpenLayers.Events = OpenLayers.Class({
/**
* Constant: BROWSER_EVENTS
* {Array(String)} supported events
*/
BROWSER_EVENTS: [
"mouseover", "mouseout",
"mousedown", "mouseup", "mousemove",
"click", "dblclick", "rightclick", "dblrightclick",
"resize", "focus", "blur"
],
/**
* Property: listeners
* {Object} Hashtable of Array(Function): events listener functions
*/
listeners: null,
/**
* Property: object
* {Object} the code object issuing application events
*/
object: null,
/**
* Property: element
* {DOMElement} the DOM element receiving browser events
*/
element: null,
/**
* Property: eventTypes
* {Array(String)} list of support application events
*/
eventTypes: null,
/**
* Property: eventHandler
* {Function} bound event handler attached to elements
*/
eventHandler: null,
/**
* APIProperty: fallThrough
* {Boolean}
*/
fallThrough: null,
/**
* APIProperty: includeXY
* {Boolean} Should the .xy property automatically be created for browser
* mouse events? In general, this should be false. If it is true, then
* mouse events will automatically generate a '.xy' property on the
* event object that is passed. (Prior to OpenLayers 2.7, this was true
* by default.) Otherwise, you can call the getMousePosition on the
* relevant events handler on the object available via the 'evt.object'
* property of the evt object. So, for most events, you can call:
* function named(evt) {
* this.xy = this.object.events.getMousePosition(evt)
* }
*
* This option typically defaults to false for performance reasons:
* when creating an events object whose primary purpose is to manage
* relatively positioned mouse events within a div, it may make
* sense to set it to true.
*
* This option is also used to control whether the events object caches
* offsets. If this is false, it will not: the reason for this is that
* it is only expected to be called many times if the includeXY property
* is set to true. If you set this to true, you are expected to clear
* the offset cache manually (using this.clearMouseCache()) if:
* the border of the element changes
* the location of the element in the page changes
*/
includeXY: false,
/**
* Method: clearMouseListener
* A version of <clearMouseCache> that is bound to this instance so that
* it can be used with <OpenLayers.Event.observe> and
* <OpenLayers.Event.stopObserving>.
*/
clearMouseListener: null,
/**
* Constructor: OpenLayers.Events
* Construct an OpenLayers.Events object.
*
* Parameters:
* object - {Object} The js object to which this Events object is being
* added element - {DOMElement} A dom element to respond to browser events
* eventTypes - {Array(String)} Array of custom application events
* fallThrough - {Boolean} Allow events to fall through after these have
* been handled?
* options - {Object} Options for the events object.
*/
initialize: function (object, element, eventTypes, fallThrough, options) {
OpenLayers.Util.extend(this, options);
this.object = object;
this.fallThrough = fallThrough;
this.listeners = {};
// keep a bound copy of handleBrowserEvent() so that we can
// pass the same function to both Event.observe() and .stopObserving()
this.eventHandler = OpenLayers.Function.bindAsEventListener(
this.handleBrowserEvent, this
);
// to be used with observe and stopObserving
this.clearMouseListener = OpenLayers.Function.bind(
this.clearMouseCache, this
);
// if eventTypes is specified, create a listeners list for each
// custom application event.
this.eventTypes = [];
if (eventTypes != null) {
for (var i=0, len=eventTypes.length; i<len; i++) {
this.addEventType(eventTypes[i]);
}
}
// if a dom element is specified, add a listeners list
// for browser events on the element and register them
if (element != null) {
this.attachToElement(element);
}
},
/**
* APIMethod: destroy
*/
destroy: function () {
if (this.element) {
OpenLayers.Event.stopObservingElement(this.element);
if(this.element.hasScrollEvent) {
OpenLayers.Event.stopObserving(
window, "scroll", this.clearMouseListener
);
}
}
this.element = null;
this.listeners = null;
this.object = null;
this.eventTypes = null;
this.fallThrough = null;
this.eventHandler = null;
},
/**
* APIMethod: addEventType
* Add a new event type to this events object.
* If the event type has already been added, do nothing.
*
* Parameters:
* eventName - {String}
*/
addEventType: function(eventName) {
if (!this.listeners[eventName]) {
this.eventTypes.push(eventName);
this.listeners[eventName] = [];
}
},
/**
* Method: attachToElement
*
* Parameters:
* element - {HTMLDOMElement} a DOM element to attach browser events to
*/
attachToElement: function (element) {
if(this.element) {
OpenLayers.Event.stopObservingElement(this.element);
}
this.element = element;
for (var i=0, len=this.BROWSER_EVENTS.length; i<len; i++) {
var eventType = this.BROWSER_EVENTS[i];
// every browser event has a corresponding application event
// (whether it's listened for or not).
this.addEventType(eventType);
// use Prototype to register the event cross-browser
OpenLayers.Event.observe(element, eventType, this.eventHandler);
}
// disable dragstart in IE so that mousedown/move/up works normally
OpenLayers.Event.observe(element, "dragstart", OpenLayers.Event.stop);
},
/**
* Method: on
* Convenience method for registering listeners with a common scope.
*
* Example use:
* (code)
* events.on({
* "loadstart": loadStartListener,
* "loadend": loadEndListener,
* scope: object
* });
* (end)
*/
on: function(object) {
for(var type in object) {
if(type != "scope") {
this.register(type, object.scope, object[type]);
}
}
},
/**
* APIMethod: register
* Register an event on the events object.
*
* When the event is triggered, the 'func' function will be called, in the
* context of 'obj'. Imagine we were to register an event, specifying an
* OpenLayers.Bounds Object as 'obj'. When the event is triggered, the
* context in the callback function will be our Bounds object. This means
* that within our callback function, we can access the properties and
* methods of the Bounds object through the "this" variable. So our
* callback could execute something like:
* : leftStr = "Left: " + this.left;
*
* or
*
* : centerStr = "Center: " + this.getCenterLonLat();
*
* Parameters:
* type - {String} Name of the event to register
* obj - {Object} The object to bind the context to for the callback#.
* If no object is specified, default is the Events's
* 'object' property.
* func - {Function} The callback function. If no callback is
* specified, this function does nothing.
*
*
*/
register: function (type, obj, func) {
if ( (func != null) &&
(OpenLayers.Util.indexOf(this.eventTypes, type) != -1) ) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
listeners.push( {obj: obj, func: func} );
}
},
/**
* APIMethod: registerPriority
* Same as register() but adds the new listener to the *front* of the
* events queue instead of to the end.
*
* TODO: get rid of this in 3.0 - Decide whether listeners should be
* called in the order they were registered or in reverse order.
*
*
* Parameters:
* type - {String} Name of the event to register
* obj - {Object} The object to bind the context to for the callback#.
* If no object is specified, default is the Events's
* 'object' property.
* func - {Function} The callback function. If no callback is
* specified, this function does nothing.
*/
registerPriority: function (type, obj, func) {
if (func != null) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
if (listeners != null) {
listeners.unshift( {obj: obj, func: func} );
}
}
},
/**
* Method: un
* Convenience method for unregistering listeners with a common scope.
*
* Example use:
* (code)
* events.un({
* "loadstart": loadStartListener,
* "loadend": loadEndListener,
* scope: object
* });
* (end)
*/
un: function(object) {
for(var type in object) {
if(type != "scope") {
this.unregister(type, object.scope, object[type]);
}
}
},
/**
* APIMethod: unregister
*
* Parameters:
* type - {String}
* obj - {Object} If none specified, defaults to this.object
* func - {Function}
*/
unregister: function (type, obj, func) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
if (listeners != null) {
for (var i=0, len=listeners.length; i<len; i++) {
if (listeners[i].obj == obj && listeners[i].func == func) {
listeners.splice(i, 1);
break;
}
}
}
},
/**
* Method: remove
* Remove all listeners for a given event type. If type is not registered,
* does nothing.
*
* Parameters:
* type - {String}
*/
remove: function(type) {
if (this.listeners[type] != null) {
this.listeners[type] = [];
}
},
/**
* APIMethod: triggerEvent
* Trigger a specified registered event.
*
* Parameters:
* type - {String}
* evt - {Event}
*
* Returns:
* {Boolean} The last listener return. If a listener returns false, the
* chain of listeners will stop getting called.
*/
triggerEvent: function (type, evt) {
var listeners = this.listeners[type];
// fast path
if(!listeners || listeners.length == 0) {
return;
}
// prep evt object with object & div references
if (evt == null) {
evt = {};
}
evt.object = this.object;
evt.element = this.element;
if(!evt.type) {
evt.type = type;
}
// execute all callbacks registered for specified type
// get a clone of the listeners array to
// allow for splicing during callbacks
var listeners = listeners.slice(), continueChain;
for (var i=0, len=listeners.length; i<len; i++) {
var callback = listeners[i];
// bind the context to callback.obj
continueChain = callback.func.apply(callback.obj, [evt]);
if ((continueChain != undefined) && (continueChain == false)) {
// if callback returns false, execute no more callbacks.
break;
}
}
// don't fall through to other DOM elements
if (!this.fallThrough) {
OpenLayers.Event.stop(evt, true);
}
return continueChain;
},
/**
* Method: handleBrowserEvent
* Basically just a wrapper to the triggerEvent() function, but takes
* care to set a property 'xy' on the event with the current mouse
* position.
*
* Parameters:
* evt - {Event}
*/
handleBrowserEvent: function (evt) {
if (this.includeXY) {
evt.xy = this.getMousePosition(evt);
}
this.triggerEvent(evt.type, evt);
},
/**
* APIMethod: clearMouseCache
* Clear cached data about the mouse position. This should be called any
* time the element that events are registered on changes position
* within the page.
*/
clearMouseCache: function() {
this.element.scrolls = null;
this.element.lefttop = null;
this.element.offsets = null;
},
/**
* Method: getMousePosition
*
* Parameters:
* evt - {Event}
*
* Returns:
* {<OpenLayers.Pixel>} The current xy coordinate of the mouse, adjusted
* for offsets
*/
getMousePosition: function (evt) {
if (!this.includeXY) {
this.clearMouseCache();
} else if (!this.element.hasScrollEvent) {
OpenLayers.Event.observe(window, "scroll", this.clearMouseListener);
this.element.hasScrollEvent = true;
}
if (!this.element.scrolls) {
this.element.scrolls = [
(document.documentElement.scrollLeft
|| document.body.scrollLeft),
(document.documentElement.scrollTop
|| document.body.scrollTop)
];
}
if (!this.element.lefttop) {
this.element.lefttop = [
(document.documentElement.clientLeft || 0),
(document.documentElement.clientTop || 0)
];
}
if (!this.element.offsets) {
this.element.offsets = OpenLayers.Util.pagePosition(this.element);
this.element.offsets[0] += this.element.scrolls[0];
this.element.offsets[1] += this.element.scrolls[1];
}
return new OpenLayers.Pixel(
(evt.clientX + this.element.scrolls[0]) - this.element.offsets[0]
- this.element.lefttop[0],
(evt.clientY + this.element.scrolls[1]) - this.element.offsets[1]
- this.element.lefttop[1]
);
},
CLASS_NAME: "OpenLayers.Events"
});

View File

@ -1,222 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Util.js
* @requires OpenLayers/Marker.js
* @requires OpenLayers/Popup/AnchoredBubble.js
*/
/**
* Class: OpenLayers.Feature
* Features are combinations of geography and attributes. The OpenLayers.Feature
* class specifically combines a marker and a lonlat.
*/
OpenLayers.Feature = OpenLayers.Class({
/**
* Property: layer
* {<OpenLayers.Layer>}
*/
layer: null,
/**
* Property: id
* {String}
*/
id: null,
/**
* Property: lonlat
* {<OpenLayers.LonLat>}
*/
lonlat: null,
/**
* Property: data
* {Object}
*/
data: null,
/**
* Property: marker
* {<OpenLayers.Marker>}
*/
marker: null,
/**
* APIProperty: popupClass
* {<OpenLayers.Class>} The class which will be used to instantiate
* a new Popup. Default is <OpenLayers.Popup.AnchoredBubble>.
*/
popupClass: OpenLayers.Popup.AnchoredBubble,
/**
* Property: popup
* {<OpenLayers.Popup>}
*/
popup: null,
/**
* Constructor: OpenLayers.Feature
* Constructor for features.
*
* Parameters:
* layer - {<OpenLayers.Layer>}
* lonlat - {<OpenLayers.LonLat>}
* data - {Object}
*
* Returns:
* {<OpenLayers.Feature>}
*/
initialize: function(layer, lonlat, data) {
this.layer = layer;
this.lonlat = lonlat;
this.data = (data != null) ? data : {};
this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
},
/**
* Method: destroy
* nullify references to prevent circular references and memory leaks
*/
destroy: function() {
//remove the popup from the map
if ((this.layer != null) && (this.layer.map != null)) {
if (this.popup != null) {
this.layer.map.removePopup(this.popup);
}
}
this.layer = null;
this.id = null;
this.lonlat = null;
this.data = null;
if (this.marker != null) {
this.destroyMarker(this.marker);
this.marker = null;
}
if (this.popup != null) {
this.destroyPopup(this.popup);
this.popup = null;
}
},
/**
* Method: onScreen
*
* Returns:
* {Boolean} Whether or not the feature is currently visible on screen
* (based on its 'lonlat' property)
*/
onScreen:function() {
var onScreen = false;
if ((this.layer != null) && (this.layer.map != null)) {
var screenBounds = this.layer.map.getExtent();
onScreen = screenBounds.containsLonLat(this.lonlat);
}
return onScreen;
},
/**
* Method: createMarker
* Based on the data associated with the Feature, create and return a marker object.
*
* Returns:
* {<OpenLayers.Marker>} A Marker Object created from the 'lonlat' and 'icon' properties
* set in this.data. If no 'lonlat' is set, returns null. If no
* 'icon' is set, OpenLayers.Marker() will load the default image.
*
* Note - this.marker is set to return value
*
*/
createMarker: function() {
if (this.lonlat != null) {
this.marker = new OpenLayers.Marker(this.lonlat, this.data.icon);
}
return this.marker;
},
/**
* Method: destroyMarker
* Destroys marker.
* If user overrides the createMarker() function, s/he should be able
* to also specify an alternative function for destroying it
*/
destroyMarker: function() {
this.marker.destroy();
},
/**
* Method: createPopup
* Creates a popup object created from the 'lonlat', 'popupSize',
* and 'popupContentHTML' properties set in this.data. It uses
* this.marker.icon as default anchor.
*
* If no 'lonlat' is set, returns null.
* If no this.marker has been created, no anchor is sent.
*
* Note - the returned popup object is 'owned' by the feature, so you
* cannot use the popup's destroy method to discard the popup.
* Instead, you must use the feature's destroyPopup
*
* Note - this.popup is set to return value
*
* Parameters:
* closeBox - {Boolean} create popup with closebox or not
*
* Returns:
* {<OpenLayers.Popup>} Returns the created popup, which is also set
* as 'popup' property of this feature. Will be of whatever type
* specified by this feature's 'popupClass' property, but must be
* of type <OpenLayers.Popup>.
*
*/
createPopup: function(closeBox) {
if (this.lonlat != null) {
var id = this.id + "_popup";
var anchor = (this.marker) ? this.marker.icon : null;
if (!this.popup) {
this.popup = new this.popupClass(id,
this.lonlat,
this.data.popupSize,
this.data.popupContentHTML,
anchor,
closeBox);
}
if (this.data.overflow != null) {
this.popup.contentDiv.style.overflow = this.data.overflow;
}
this.popup.feature = this;
}
return this.popup;
},
/**
* Method: destroyPopup
* Destroys the popup created via createPopup.
*
* As with the marker, if user overrides the createPopup() function, s/he
* should also be able to override the destruction
*/
destroyPopup: function() {
if (this.popup) {
this.popup.feature = null;
this.popup.destroy();
this.popup = null;
}
},
CLASS_NAME: "OpenLayers.Feature"
});

View File

@ -1,419 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
// TRASH THIS
OpenLayers.State = {
/** states */
UNKNOWN: 'Unknown',
INSERT: 'Insert',
UPDATE: 'Update',
DELETE: 'Delete'
};
/**
* @requires OpenLayers/Feature.js
* @requires OpenLayers/Util.js
*/
/**
* Class: OpenLayers.Feature.Vector
* Vector features use the OpenLayers.Geometry classes as geometry description.
* They have an 'attributes' property, which is the data object, and a 'style'
* property, the default values of which are defined in the
* <OpenLayers.Feature.Vector.style> objects.
*
* Inherits from:
* - <OpenLayers.Feature>
*/
OpenLayers.Feature.Vector = OpenLayers.Class(OpenLayers.Feature, {
/**
* Property: fid
* {String}
*/
fid: null,
/**
* APIProperty: geometry
* {<OpenLayers.Geometry>}
*/
geometry: null,
/**
* APIProperty: attributes
* {Object} This object holds arbitrary properties that describe the
* feature.
*/
attributes: null,
/**
* Property: bounds
* {<OpenLayers.Bounds>} The box bounding that feature's geometry, that
* property can be set by an <OpenLayers.Format> object when
* deserializing the feature, so in most cases it represents an
* information set by the server.
*/
bounds: null,
/**
* Property: state
* {String}
*/
state: null,
/**
* APIProperty: style
* {Object}
*/
style: null,
/**
* Property: renderIntent
* {String} rendering intent currently being used
*/
renderIntent: "default",
/**
* Constructor: OpenLayers.Feature.Vector
* Create a vector feature.
*
* Parameters:
* geometry - {<OpenLayers.Geometry>} The geometry that this feature
* represents.
* attributes - {Object} An optional object that will be mapped to the
* <attributes> property.
* style - {Object} An optional style object.
*/
initialize: function(geometry, attributes, style) {
OpenLayers.Feature.prototype.initialize.apply(this,
[null, null, attributes]);
this.lonlat = null;
this.geometry = geometry ? geometry : null;
this.state = null;
this.attributes = {};
if (attributes) {
this.attributes = OpenLayers.Util.extend(this.attributes,
attributes);
}
this.style = style ? style : null;
},
/**
* Method: destroy
* nullify references to prevent circular references and memory leaks
*/
destroy: function() {
if (this.layer) {
this.layer.removeFeatures(this);
this.layer = null;
}
this.geometry = null;
OpenLayers.Feature.prototype.destroy.apply(this, arguments);
},
/**
* Method: clone
* Create a clone of this vector feature. Does not set any non-standard
* properties.
*
* Returns:
* {<OpenLayers.Feature.Vector>} An exact clone of this vector feature.
*/
clone: function () {
return new OpenLayers.Feature.Vector(
this.geometry ? this.geometry.clone() : null,
this.attributes,
this.style);
},
/**
* Method: onScreen
* Determine whether the feature is within the map viewport. This method
* tests for an intersection between the geometry and the viewport
* bounds. If a more effecient but less precise geometry bounds
* intersection is desired, call the method with the boundsOnly
* parameter true.
*
* Parameters:
* boundsOnly - {Boolean} Only test whether a feature's bounds intersects
* the viewport bounds. Default is false. If false, the feature's
* geometry must intersect the viewport for onScreen to return true.
*
* Returns:
* {Boolean} The feature is currently visible on screen (optionally
* based on its bounds if boundsOnly is true).
*/
onScreen:function(boundsOnly) {
var onScreen = false;
if(this.layer && this.layer.map) {
var screenBounds = this.layer.map.getExtent();
if(boundsOnly) {
var featureBounds = this.geometry.getBounds();
onScreen = screenBounds.intersectsBounds(featureBounds);
} else {
var screenPoly = screenBounds.toGeometry();
onScreen = screenPoly.intersects(this.geometry);
}
}
return onScreen;
},
/**
* Method: createMarker
* HACK - we need to decide if all vector features should be able to
* create markers
*
* Returns:
* {<OpenLayers.Marker>} For now just returns null
*/
createMarker: function() {
return null;
},
/**
* Method: destroyMarker
* HACK - we need to decide if all vector features should be able to
* delete markers
*
* If user overrides the createMarker() function, s/he should be able
* to also specify an alternative function for destroying it
*/
destroyMarker: function() {
// pass
},
/**
* Method: createPopup
* HACK - we need to decide if all vector features should be able to
* create popups
*
* Returns:
* {<OpenLayers.Popup>} For now just returns null
*/
createPopup: function() {
return null;
},
/**
* Method: atPoint
* Determins whether the feature intersects with the specified location.
*
* Parameters:
* lonlat - {<OpenLayers.LonLat>}
* toleranceLon - {float} Optional tolerance in Geometric Coords
* toleranceLat - {float} Optional tolerance in Geographic Coords
*
* Returns:
* {Boolean} Whether or not the feature is at the specified location
*/
atPoint: function(lonlat, toleranceLon, toleranceLat) {
var atPoint = false;
if(this.geometry) {
atPoint = this.geometry.atPoint(lonlat, toleranceLon,
toleranceLat);
}
return atPoint;
},
/**
* Method: destroyPopup
* HACK - we need to decide if all vector features should be able to
* delete popups
*/
destroyPopup: function() {
// pass
},
/**
* Method: move
* Moves the feature and redraws it at its new location
*
* Parameters:
* state - {OpenLayers.LonLat or OpenLayers.Pixel} the
* location to which to move the feature.
*/
move: function(location) {
if(!this.layer || !this.geometry.move){
//do nothing if no layer or immoveable geometry
return;
}
var pixel;
if (location.CLASS_NAME == "OpenLayers.LonLat") {
pixel = this.layer.getViewPortPxFromLonLat(location);
} else {
pixel = location;
}
var lastPixel = this.layer.getViewPortPxFromLonLat(this.geometry.getBounds().getCenterLonLat());
var res = this.layer.map.getResolution();
this.geometry.move(res * (pixel.x - lastPixel.x),
res * (lastPixel.y - pixel.y));
this.layer.drawFeature(this);
return lastPixel;
},
/**
* Method: toState
* Sets the new state
*
* Parameters:
* state - {String}
*/
toState: function(state) {
if (state == OpenLayers.State.UPDATE) {
switch (this.state) {
case OpenLayers.State.UNKNOWN:
case OpenLayers.State.DELETE:
this.state = state;
break;
case OpenLayers.State.UPDATE:
case OpenLayers.State.INSERT:
break;
}
} else if (state == OpenLayers.State.INSERT) {
switch (this.state) {
case OpenLayers.State.UNKNOWN:
break;
default:
this.state = state;
break;
}
} else if (state == OpenLayers.State.DELETE) {
switch (this.state) {
case OpenLayers.State.INSERT:
// the feature should be destroyed
break;
case OpenLayers.State.DELETE:
break;
case OpenLayers.State.UNKNOWN:
case OpenLayers.State.UPDATE:
this.state = state;
break;
}
} else if (state == OpenLayers.State.UNKNOWN) {
this.state = state;
}
},
CLASS_NAME: "OpenLayers.Feature.Vector"
});
/**
* Constant: OpenLayers.Feature.Vector.style
* OpenLayers features can have a number of style attributes. The 'default'
* style will typically be used if no other style is specified. These
* styles correspond for the most part, to the styling properties defined
* by the SVG standard.
* Information on fill properties: http://www.w3.org/TR/SVG/painting.html#FillProperties
* Information on stroke properties: http://www.w3.org/TR/SVG/painting.html#StrokeProperties
*
* Symbolizer properties:
* fill - {Boolean} Set to false if no fill is desired.
* fillColor - {String} Hex fill color. Default is "#ee9900".
* fillOpacity - {Number} Fill opacity (0-1). Default is 0.4
* stroke - {Boolean} Set to false if no stroke is desired.
* strokeColor - {String} Hex stroke color. Default is "#ee9900".
* strokeOpacity - {Number} Stroke opacity (0-1). Default is 1.
* strokeWidth - {Number} Pixel stroke width. Default is 1.
* strokeLinecap - {String} Stroke cap type. Default is "round". [butt | round | square]
* strokeDashstyle - {String} Stroke dash style. Default is "solid". [dot | dash | dashdot | longdash | longdashdot | solid]
* graphic - {Boolean} Set to false if no graphic is desired.
* pointRadius - {Number} Pixel point radius. Default is 6.
* pointerEvents - {String} Default is "visiblePainted".
* cursor - {String} Default is "".
* externalGraphic - {String} Url to an external graphic that will be used for rendering points.
* graphicWidth - {Number} Pixel width for sizing an external graphic.
* graphicHeight - {Number} Pixel height for sizing an external graphic.
* graphicOpacity - {Number} Opacity (0-1) for an external graphic.
* graphicXOffset - {Number} Pixel offset along the positive x axis for displacing an external graphic.
* graphicYOffset - {Number} Pixel offset along the positive y axis for displacing an external graphic.
* graphicZIndex - {Number} The integer z-index value to use in rendering.
* graphicName - {String} Named graphic to use when rendering points. Supported values include "circle" (default),
* "square", "star", "x", "cross", "triangle".
* graphicTitle - {String} Tooltip for an external graphic. Only supported in Firefox and Internet Explorer.
* backgroundGraphic - {String} Url to a graphic to be used as the background under an externalGraphic.
* backgroundGraphicZIndex - {Number} The integer z-index value to use in rendering the background graphic.
* backgroundXOffset - {Number} The x offset (in pixels) for the background graphic.
* backgroundYOffset - {Number} The y offset (in pixels) for the background graphic.
* backgroundHeight - {Number} The height of the background graphic. If not provided, the graphicHeight will be used.
* backgroundWidth - {Number} The width of the background width. If not provided, the graphicWidth will be used.
* label - {String} The text for an optional label. For browsers that use the canvas renderer, this requires either
* fillText or mozDrawText to be available.
* labelAlign - {String} Label alignment. This specifies the insertion point relative to the text. It is a string
* composed of two characters. The first character is for the horizontal alignment, the second for the vertical
* alignment. Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. Valid values for vertical
* alignment: "t"=top, "m"=middle, "b"=bottom. Example values: "lt", "cm", "rb". The canvas renderer does not
* support vertical alignment, it will always use "b".
* fontColor - {String} The font color for the label, to be provided like CSS.
* fontFamily - {String} The font family for the label, to be provided like in CSS.
* fontSize - {String} The font size for the label, to be provided like in CSS.
* fontWeight - {String} The font weight for the label, to be provided like in CSS.
* display - {String} Symbolizers will have no effect if display is set to "none". All other values have no effect.
*/
OpenLayers.Feature.Vector.style = {
'default': {
fillColor: "#ee9900",
fillOpacity: 0.4,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "#ee9900",
strokeOpacity: 1,
strokeWidth: 1,
strokeLinecap: "round",
strokeDashstyle: "solid",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "inherit"
},
'select': {
fillColor: "blue",
fillOpacity: 0.4,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "blue",
strokeOpacity: 1,
strokeWidth: 2,
strokeLinecap: "round",
strokeDashstyle: "solid",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "pointer"
},
'temporary': {
fillColor: "#66cccc",
fillOpacity: 0.2,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "#66cccc",
strokeOpacity: 1,
strokeLinecap: "round",
strokeWidth: 2,
strokeDashstyle: "solid",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "inherit"
},
'delete': {
display: "none"
}
};

View File

@ -1,79 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Feature.js
*/
/**
* Class: OpenLayers.Feature.WFS
* WFS handling class, for use as a featureClass on the WFS layer for handling
* 'point' WFS types. Good for subclassing when creating a custom WFS like
* XML application.
*
* Inherits from:
* - <OpenLayers.Feature>
*/
OpenLayers.Feature.WFS = OpenLayers.Class(OpenLayers.Feature, {
/**
* Constructor: OpenLayers.Feature.WFS
* Create a WFS feature.
*
* Parameters:
* layer - {<OpenLayers.Layer>}
* xmlNode - {XMLNode}
*/
initialize: function(layer, xmlNode) {
var newArguments = arguments;
var data = this.processXMLNode(xmlNode);
newArguments = new Array(layer, data.lonlat, data);
OpenLayers.Feature.prototype.initialize.apply(this, newArguments);
this.createMarker();
this.layer.addMarker(this.marker);
},
/**
* Method: destroy
* nullify references to prevent circular references and memory leaks
*/
destroy: function() {
if (this.marker != null) {
this.layer.removeMarker(this.marker);
}
OpenLayers.Feature.prototype.destroy.apply(this, arguments);
},
/**
* Method: processXMLNode
* When passed an xmlNode, parses it for a GML point, and passes
* back an object describing that point.
*
* For subclasses of Feature.WFS, this is the feature to change.
*
* Parameters:
* xmlNode - {XMLNode}
*
* Returns:
* {Object} Data Object with 'id', 'lonlat', and private properties set
*/
processXMLNode: function(xmlNode) {
//this should be overridden by subclasses
// must return an Object with 'id' and 'lonlat' values set
var point = OpenLayers.Ajax.getElementsByTagNameNS(xmlNode, "http://www.opengis.net/gml", "gml", "Point");
var text = OpenLayers.Util.getXmlNodeValue(OpenLayers.Ajax.getElementsByTagNameNS(point[0], "http://www.opengis.net/gml","gml", "coordinates")[0]);
var floats = text.split(",");
return {lonlat: new OpenLayers.LonLat(parseFloat(floats[0]),
parseFloat(floats[1])),
id: null};
},
CLASS_NAME: "OpenLayers.Feature.WFS"
});

View File

@ -1,66 +0,0 @@
/* Copyright (c) 2006 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/Util.js
* @requires OpenLayers/Style.js
*/
/**
* Class: OpenLayers.Filter
* This class represents an OGC Filter.
*/
OpenLayers.Filter = OpenLayers.Class({
/**
* Constructor: OpenLayers.Filter
* This is an abstract class. Create an instance of a filter subclass.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*
* Returns:
* {<OpenLayers.Filter>}
*/
initialize: function(options) {
OpenLayers.Util.extend(this, options);
},
/**
* APIMethod: destroy
* Remove reference to anything added.
*/
destroy: function() {
},
/**
* APIMethod: evaluate
* Evaluates this filter in a specific context. Should be implemented by
* subclasses.
*
* Parameters:
* context - {Object} Context to use in evaluating the filter.
*
* Returns:
* {Boolean} The filter applies.
*/
evaluate: function(context) {
return true;
},
/**
* APIMethod: clone
* Clones this filter. Should be implementted by subclasses.
*
* Returns:
* {<OpenLayers.Filter>} Clone of this filter.
*/
clone: function() {
return null;
},
CLASS_NAME: "OpenLayers.Filter"
});

View File

@ -1,255 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Filter.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Filter.Comparison
* This class represents a comparison filter.
*
* Inherits from
* - <OpenLayers.Filter>
*/
OpenLayers.Filter.Comparison = OpenLayers.Class(OpenLayers.Filter, {
/**
* APIProperty: type
* {String} type: type of the comparison. This is one of
* - OpenLayers.Filter.Comparison.EQUAL_TO = "==";
* - OpenLayers.Filter.Comparison.NOT_EQUAL_TO = "!=";
* - OpenLayers.Filter.Comparison.LESS_THAN = "<";
* - OpenLayers.Filter.Comparison.GREATER_THAN = ">";
* - OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO = "<=";
* - OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO = ">=";
* - OpenLayers.Filter.Comparison.BETWEEN = "..";
* - OpenLayers.Filter.Comparison.LIKE = "~";
*/
type: null,
/**
* APIProperty: property
* {String}
* name of the context property to compare
*/
property: null,
/**
* APIProperty: value
* {Number} or {String}
* comparison value for binary comparisons. In the case of a String, this
* can be a combination of text and propertyNames in the form
* "literal ${propertyName}"
*/
value: null,
/**
* Property: matchCase
* {Boolean} Force case sensitive searches for EQUAL_TO and NOT_EQUAL_TO
* comparisons. The Filter Encoding 1.1 specification added a matchCase
* attribute to ogc:PropertyIsEqualTo and ogc:PropertyIsNotEqualTo
* elements. This property will be serialized with those elements only
* if using the v1.1.0 filter format. However, when evaluating filters
* here, the matchCase property will always be respected (for EQUAL_TO
* and NOT_EQUAL_TO). Default is true.
*/
matchCase: true,
/**
* APIProperty: lowerBoundary
* {Number} or {String}
* lower boundary for between comparisons. In the case of a String, this
* can be a combination of text and propertyNames in the form
* "literal ${propertyName}"
*/
lowerBoundary: null,
/**
* APIProperty: upperBoundary
* {Number} or {String}
* upper boundary for between comparisons. In the case of a String, this
* can be a combination of text and propertyNames in the form
* "literal ${propertyName}"
*/
upperBoundary: null,
/**
* Constructor: OpenLayers.Filter.Comparison
* Creates a comparison rule.
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* rule
*
* Returns:
* {<OpenLayers.Filter.Comparison>}
*/
initialize: function(options) {
OpenLayers.Filter.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: evaluate
* Evaluates this filter in a specific context. Should be implemented by
* subclasses.
*
* Parameters:
* context - {Object} Context to use in evaluating the filter.
*
* Returns:
* {Boolean} The filter applies.
*/
evaluate: function(context) {
var result = false;
switch(this.type) {
case OpenLayers.Filter.Comparison.EQUAL_TO:
var got = context[this.property];
var exp = this.value;
if(!this.matchCase &&
typeof got == "string" && typeof exp == "string") {
result = (got.toUpperCase() == exp.toUpperCase());
} else {
result = (got == exp);
}
break;
case OpenLayers.Filter.Comparison.NOT_EQUAL_TO:
var got = context[this.property];
var exp = this.value;
if(!this.matchCase &&
typeof got == "string" && typeof exp == "string") {
result = (got.toUpperCase() != exp.toUpperCase());
} else {
result = (got != exp);
}
break;
case OpenLayers.Filter.Comparison.LESS_THAN:
result = context[this.property] < this.value;
break;
case OpenLayers.Filter.Comparison.GREATER_THAN:
result = context[this.property] > this.value;
break;
case OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO:
result = context[this.property] <= this.value;
break;
case OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO:
result = context[this.property] >= this.value;
break;
case OpenLayers.Filter.Comparison.BETWEEN:
result = (context[this.property] >= this.lowerBoundary) &&
(context[this.property] <= this.upperBoundary);
break;
case OpenLayers.Filter.Comparison.LIKE:
var regexp = new RegExp(this.value, "gi");
result = regexp.test(context[this.property]);
break;
}
return result;
},
/**
* APIMethod: value2regex
* Converts the value of this rule into a regular expression string,
* according to the wildcard characters specified. This method has to
* be called after instantiation of this class, if the value is not a
* regular expression already.
*
* Parameters:
* wildCard - {<Char>} wildcard character in the above value, default
* is "*"
* singleChar - {<Char>) single-character wildcard in the above value
* default is "."
* escape - {<Char>) escape character in the above value, default is
* "!"
*
* Returns:
* {String} regular expression string
*/
value2regex: function(wildCard, singleChar, escapeChar) {
if (wildCard == ".") {
var msg = "'.' is an unsupported wildCard character for "+
"OpenLayers.Filter.Comparison";
OpenLayers.Console.error(msg);
return null;
}
// set UMN MapServer defaults for unspecified parameters
wildCard = wildCard ? wildCard : "*";
singleChar = singleChar ? singleChar : ".";
escapeChar = escapeChar ? escapeChar : "!";
this.value = this.value.replace(
new RegExp("\\"+escapeChar+"(.|$)", "g"), "\\$1");
this.value = this.value.replace(
new RegExp("\\"+singleChar, "g"), ".");
this.value = this.value.replace(
new RegExp("\\"+wildCard, "g"), ".*");
this.value = this.value.replace(
new RegExp("\\\\.\\*", "g"), "\\"+wildCard);
this.value = this.value.replace(
new RegExp("\\\\\\.", "g"), "\\"+singleChar);
return this.value;
},
/**
* Method: regex2value
* Convert the value of this rule from a regular expression string into an
* ogc literal string using a wildCard of *, a singleChar of ., and an
* escape of !. Leaves the <value> property unmodified.
*
* Returns:
* {String} A string value.
*/
regex2value: function() {
var value = this.value;
// replace ! with !!
value = value.replace(/!/g, "!!");
// replace \. with !. (watching out for \\.)
value = value.replace(/(\\)?\\\./g, function($0, $1) {
return $1 ? $0 : "!.";
});
// replace \* with #* (watching out for \\*)
value = value.replace(/(\\)?\\\*/g, function($0, $1) {
return $1 ? $0 : "!*";
});
// replace \\ with \
value = value.replace(/\\\\/g, "\\");
// convert .* to * (the sequence #.* is not allowed)
value = value.replace(/\.\*/g, "*");
return value;
},
/**
* APIMethod: clone
* Clones this filter.
*
* Returns:
* {<OpenLayers.Filter.Comparison>} Clone of this filter.
*/
clone: function() {
return OpenLayers.Util.extend(new OpenLayers.Filter.Comparison(), this);
},
CLASS_NAME: "OpenLayers.Filter.Comparison"
});
OpenLayers.Filter.Comparison.EQUAL_TO = "==";
OpenLayers.Filter.Comparison.NOT_EQUAL_TO = "!=";
OpenLayers.Filter.Comparison.LESS_THAN = "<";
OpenLayers.Filter.Comparison.GREATER_THAN = ">";
OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO = "<=";
OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO = ">=";
OpenLayers.Filter.Comparison.BETWEEN = "..";
OpenLayers.Filter.Comparison.LIKE = "~";

View File

@ -1,80 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Filter.js
*/
/**
* Class: OpenLayers.Filter.FeatureId
* This class represents a ogc:FeatureId Filter, as being used for rule-based SLD
* styling
*
* Inherits from
* - <OpenLayers.Filter>
*/
OpenLayers.Filter.FeatureId = OpenLayers.Class(OpenLayers.Filter, {
/**
* APIProperty: fids
* {Array(String)} Feature Ids to evaluate this rule against. To be passed
* To be passed inside the params object.
*/
fids: null,
/**
* Constructor: OpenLayers.Filter.FeatureId
* Creates an ogc:FeatureId rule.
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* rule
*
* Returns:
* {<OpenLayers.Filter.FeatureId>}
*/
initialize: function(options) {
this.fids = [];
OpenLayers.Filter.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: evaluate
* evaluates this rule for a specific feature
*
* Parameters:
* feature - {<OpenLayers.Feature>} feature to apply the rule to.
* For vector features, the check is run against the fid,
* for plain features against the id.
*
* Returns:
* {Boolean} true if the rule applies, false if it does not
*/
evaluate: function(feature) {
for (var i=0, len=this.fids.length; i<len; i++) {
var fid = feature.fid || feature.id;
if (fid == this.fids[i]) {
return true;
}
}
return false;
},
/**
* APIMethod: clone
* Clones this filter.
*
* Returns:
* {<OpenLayers.Filter.FeatureId>} Clone of this filter.
*/
clone: function() {
var filter = new OpenLayers.Filter.FeatureId();
OpenLayers.Util.extend(filter, this);
filter.fids = this.fids.slice();
return filter;
},
CLASS_NAME: "OpenLayers.Filter.FeatureId"
});

View File

@ -1,117 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Filter.js
*/
/**
* Class: OpenLayers.Filter.Logical
* This class represents ogc:And, ogc:Or and ogc:Not rules.
*
* Inherits from
* - <OpenLayers.Filter>
*/
OpenLayers.Filter.Logical = OpenLayers.Class(OpenLayers.Filter, {
/**
* APIProperty: filters
* {Array(<OpenLayers.Filter>)} Child filters for this filter.
*/
filters: null,
/**
* APIProperty: type
* {String} type of logical operator. Available types are:
* - OpenLayers.Filter.Logical.AND = "&&";
* - OpenLayers.Filter.Logical.OR = "||";
* - OpenLayers.Filter.Logical.NOT = "!";
*/
type: null,
/**
* Constructor: OpenLayers.Filter.Logical
* Creates a logical filter (And, Or, Not).
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* filter.
*
* Returns:
* {<OpenLayers.Filter.Logical>}
*/
initialize: function(options) {
this.filters = [];
OpenLayers.Filter.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: destroy
* Remove reference to child filters.
*/
destroy: function() {
this.filters = null;
OpenLayers.Filter.prototype.destroy.apply(this);
},
/**
* APIMethod: evaluate
* Evaluates this filter in a specific context. Should be implemented by
* subclasses.
*
* Parameters:
* context - {Object} Context to use in evaluating the filter.
*
* Returns:
* {Boolean} The filter applies.
*/
evaluate: function(context) {
switch(this.type) {
case OpenLayers.Filter.Logical.AND:
for (var i=0, len=this.filters.length; i<len; i++) {
if (this.filters[i].evaluate(context) == false) {
return false;
}
}
return true;
case OpenLayers.Filter.Logical.OR:
for (var i=0, len=this.filters.length; i<len; i++) {
if (this.filters[i].evaluate(context) == true) {
return true;
}
}
return false;
case OpenLayers.Filter.Logical.NOT:
return (!this.filters[0].evaluate(context));
}
},
/**
* APIMethod: clone
* Clones this filter.
*
* Returns:
* {<OpenLayers.Filter.Logical>} Clone of this filter.
*/
clone: function() {
var filters = [];
for(var i=0, len=this.filters.length; i<len; ++i) {
filters.push(this.filters[i].clone());
}
return new OpenLayers.Filter.Logical({
type: this.type,
filters: filters
});
},
CLASS_NAME: "OpenLayers.Filter.Logical"
});
OpenLayers.Filter.Logical.AND = "&&";
OpenLayers.Filter.Logical.OR = "||";
OpenLayers.Filter.Logical.NOT = "!";

View File

@ -1,127 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Filter.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Filter.Spatial
* This class represents a spatial filter.
* Currently implemented: BBOX, DWithin and Intersects
*
* Inherits from
* - <OpenLayers.Filter>
*/
OpenLayers.Filter.Spatial = OpenLayers.Class(OpenLayers.Filter, {
/**
* APIProperty: type
* {String} Type of spatial filter.
*
* The type should be one of:
* - OpenLayers.Filter.Spatial.BBOX
* - OpenLayers.Filter.Spatial.INTERSECTS
* - OpenLayers.Filter.Spatial.DWITHIN
* - OpenLayers.Filter.Spatial.WITHIN
* - OpenLayers.Filter.Spatial.CONTAINS
*/
type: null,
/**
* APIProperty: property
* {String} Name of the context property to compare.
*/
property: null,
/**
* APIProperty: value
* {<OpenLayers.Bounds> || <OpenLayers.Geometry>} The bounds or geometry
* to be used by the filter. Use bounds for BBOX filters and geometry
* for INTERSECTS or DWITHIN filters.
*/
value: null,
/**
* APIProperty: distance
* {Number} The distance to use in a DWithin spatial filter.
*/
distance: null,
/**
* APIProperty: distanceUnits
* {String} The units to use for the distance, e.g. 'm'.
*/
distanceUnits: null,
/**
* Constructor: OpenLayers.Filter.Spatial
* Creates a spatial filter.
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* filter.
*
* Returns:
* {<OpenLayers.Filter.Spatial>}
*/
initialize: function(options) {
OpenLayers.Filter.prototype.initialize.apply(this, [options]);
},
/**
* Method: evaluate
* Evaluates this filter for a specific feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} feature to apply the filter to.
*
* Returns:
* {Boolean} The feature meets filter criteria.
*/
evaluate: function(feature) {
var intersect = false;
switch(this.type) {
case OpenLayers.Filter.Spatial.BBOX:
case OpenLayers.Filter.Spatial.INTERSECTS:
if(feature.geometry) {
var geom = this.value;
if(this.value.CLASS_NAME == "OpenLayers.Bounds") {
geom = this.value.toGeometry();
}
if(feature.geometry.intersects(geom)) {
intersect = true;
}
}
break;
default:
OpenLayers.Console.error(
OpenLayers.i18n("filterEvaluateNotImplemented"));
break;
}
return intersect;
},
/**
* APIMethod: clone
* Clones this filter.
*
* Returns:
* {<OpenLayers.Filter.Spatial>} Clone of this filter.
*/
clone: function() {
var options = OpenLayers.Util.applyDefaults({
value: this.value && this.value.clone && this.value.clone()
}, this);
return new OpenLayers.Filter.Spatial(options);
},
CLASS_NAME: "OpenLayers.Filter.Spatial"
});
OpenLayers.Filter.Spatial.BBOX = "BBOX";
OpenLayers.Filter.Spatial.INTERSECTS = "INTERSECTS";
OpenLayers.Filter.Spatial.DWITHIN = "DWITHIN";
OpenLayers.Filter.Spatial.WITHIN = "WITHIN";
OpenLayers.Filter.Spatial.CONTAINS = "CONTAINS";

View File

@ -1,122 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Util.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Format
* Base class for format reading/writing a variety of formats. Subclasses
* of OpenLayers.Format are expected to have read and write methods.
*/
OpenLayers.Format = OpenLayers.Class({
/**
* Property: options
* {Object} A reference to options passed to the constructor.
*/
options: null,
/**
* APIProperty: externalProjection
* {<OpenLayers.Projection>} When passed a externalProjection and
* internalProjection, the format will reproject the geometries it
* reads or writes. The externalProjection is the projection used by
* the content which is passed into read or which comes out of write.
* In order to reproject, a projection transformation function for the
* specified projections must be available. This support may be
* provided via proj4js or via a custom transformation function. See
* {<OpenLayers.Projection.addTransform>} for more information on
* custom transformations.
*/
externalProjection: null,
/**
* APIProperty: internalProjection
* {<OpenLayers.Projection>} When passed a externalProjection and
* internalProjection, the format will reproject the geometries it
* reads or writes. The internalProjection is the projection used by
* the geometries which are returned by read or which are passed into
* write. In order to reproject, a projection transformation function
* for the specified projections must be available. This support may be
* provided via proj4js or via a custom transformation function. See
* {<OpenLayers.Projection.addTransform>} for more information on
* custom transformations.
*/
internalProjection: null,
/**
* APIProperty: data
* {Object} When <keepData> is true, this is the parsed string sent to
* <read>.
*/
data: null,
/**
* APIProperty: keepData
* {Object} Maintain a reference (<data>) to the most recently read data.
* Default is false.
*/
keepData: false,
/**
* Constructor: OpenLayers.Format
* Instances of this class are not useful. See one of the subclasses.
*
* Parameters:
* options - {Object} An optional object with properties to set on the
* format
*
* Valid options:
* keepData - {Boolean} If true, upon <read>, the data property will be
* set to the parsed object (e.g. the json or xml object).
*
* Returns:
* An instance of OpenLayers.Format
*/
initialize: function(options) {
OpenLayers.Util.extend(this, options);
this.options = options;
},
/**
* APIMethod: destroy
* Clean up.
*/
destroy: function() {
},
/**
* Method: read
* Read data from a string, and return an object whose type depends on the
* subclass.
*
* Parameters:
* data - {string} Data to read/parse.
*
* Returns:
* Depends on the subclass
*/
read: function(data) {
OpenLayers.Console.userError(OpenLayers.i18n("readNotImplemented"));
},
/**
* Method: write
* Accept an object, and return a string.
*
* Parameters:
* object - {Object} Object to be serialized
*
* Returns:
* {String} A string representation of the object.
*/
write: function(object) {
OpenLayers.Console.userError(OpenLayers.i18n("writeNotImplemented"));
},
CLASS_NAME: "OpenLayers.Format"
});

View File

@ -1,48 +0,0 @@
/* Copyright (c) 2009 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/ArcXML.js
*/
/**
* Class: OpenLayers.Format.ArcXML.Features
* Read/Wite ArcXML features. Create a new instance with the
* <OpenLayers.Format.ArcXML.Features> constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.ArcXML.Features = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* Constructor: OpenLayers.Format.ArcXML.Features
* Create a new parser/writer for ArcXML Features. Create an instance of this class
* to get a set of features from an ArcXML response.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Read data from a string of ArcXML, and return a set of OpenLayers features.
*
* Parameters:
* data - {String} or {DOMElement} data to read/parse.
*
* Returns:
* {Array(<OpenLayers.Feature.Vector>)} A collection of features.
*/
read: function(data) {
var axl = new OpenLayers.Format.ArcXML();
var parsed = axl.read(data);
return parsed.features.feature;
}
});

View File

@ -1,114 +0,0 @@
/* Copyright (c) 2006 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/Format/XML.js
* @requires OpenLayers/Filter/FeatureId.js
* @requires OpenLayers/Filter/Logical.js
* @requires OpenLayers/Filter/Comparison.js
*/
/**
* Class: OpenLayers.Format.Filter
* Read/Wite ogc:Filter. Create a new instance with the <OpenLayers.Format.Filter>
* constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.Filter = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.0.0".
*/
defaultVersion: "1.0.0",
/**
* APIProperty: version
* {String} Specify a version string if one is known.
*/
version: null,
/**
* Property: parser
* {Object} Instance of the versioned parser. Cached for multiple read and
* write calls of the same version.
*/
parser: null,
/**
* Constructor: OpenLayers.Format.Filter
* Create a new parser for Filter.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: write
* Write an ogc:Filter given a filter object.
*
* Parameters:
* filter - {<OpenLayers.Filter>} An filter.
* options - {Object} Optional configuration object.
*
* Returns:
* {Elment} An ogc:Filter element node.
*/
write: function(filter, options) {
var version = (options && options.version) ||
this.version || this.defaultVersion;
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.Filter[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a Filter parser for version " +
version;
}
this.parser = new format(this.options);
}
return this.parser.write(filter);
//return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
},
/**
* APIMethod: read
* Read and Filter doc and return an object representing the Filter.
*
* Parameters:
* data - {String | DOMElement} Data to read.
*
* Returns:
* {<OpenLayers.Filter>} A filter object.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var version = this.version;
if(!version) {
version = this.defaultVersion;
}
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.Filter[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a Filter parser for version " +
version;
}
this.parser = new format(this.options);
}
var filter = this.parser.read(data);
return filter;
},
CLASS_NAME: "OpenLayers.Format.Filter"
});

View File

@ -1,449 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/Filter.js
* @requires OpenLayers/Format/XML.js
*/
/**
* Class: OpenLayers.Format.Filter.v1
* Superclass for Filter version 1 parsers.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.Filter.v1 = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* Property: namespaces
* {Object} Mapping of namespace aliases to namespace URIs.
*/
namespaces: {
ogc: "http://www.opengis.net/ogc",
gml: "http://www.opengis.net/gml",
xlink: "http://www.w3.org/1999/xlink",
xsi: "http://www.w3.org/2001/XMLSchema-instance"
},
/**
* Property: defaultPrefix
*/
defaultPrefix: "ogc",
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version.
*/
schemaLocation: null,
/**
* Constructor: OpenLayers.Format.Filter.v1
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.Filter> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* Method: read
*
* Parameters:
* data - {DOMElement} A Filter document element.
*
* Returns:
* {<OpenLayers.Filter>} A filter object.
*/
read: function(data) {
var obj = {};
this.readers.ogc["Filter"].apply(this, [data, obj]);
return obj.filter;
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"ogc": {
"Filter": function(node, parent) {
// Filters correspond to subclasses of OpenLayers.Filter.
// Since they contain information we don't persist, we
// create a temporary object and then pass on the filter
// (ogc:Filter) to the parent obj.
var obj = {
fids: [],
filters: []
};
this.readChildNodes(node, obj);
if(obj.fids.length > 0) {
parent.filter = new OpenLayers.Filter.FeatureId({
fids: obj.fids
});
} else if(obj.filters.length > 0) {
parent.filter = obj.filters[0];
}
},
"FeatureId": function(node, obj) {
var fid = node.getAttribute("fid");
if(fid) {
obj.fids.push(fid);
}
},
"And": function(node, obj) {
var filter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"Or": function(node, obj) {
var filter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.OR
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"Not": function(node, obj) {
var filter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.NOT
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsLessThan": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LESS_THAN
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsGreaterThan": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.GREATER_THAN
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsLessThanOrEqualTo": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsGreaterThanOrEqualTo": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsBetween": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsLike": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE
});
this.readChildNodes(node, filter);
var wildCard = node.getAttribute("wildCard");
var singleChar = node.getAttribute("singleChar");
var esc = node.getAttribute("escape");
filter.value2regex(wildCard, singleChar, esc);
obj.filters.push(filter);
},
"Literal": function(node, obj) {
obj.value = OpenLayers.String.numericIf(
this.getChildValue(node));
},
"PropertyName": function(node, filter) {
filter.property = this.getChildValue(node);
},
"LowerBoundary": function(node, filter) {
filter.lowerBoundary = OpenLayers.String.numericIf(
this.readOgcExpression(node));
},
"UpperBoundary": function(node, filter) {
filter.upperBoundary = OpenLayers.String.numericIf(
this.readOgcExpression(node));
},
"Intersects": function(node, obj) {
this.readSpatial(node, obj, OpenLayers.Filter.Spatial.INTERSECTS);
},
"Within": function(node, obj) {
this.readSpatial(node, obj, OpenLayers.Filter.Spatial.WITHIN);
},
"Contains": function(node, obj) {
this.readSpatial(node, obj, OpenLayers.Filter.Spatial.CONTAINS);
},
"DWithin": function(node, obj) {
this.readSpatial(node, obj, OpenLayers.Filter.Spatial.DWITHIN);
},
"Distance": function(node, obj) {
obj.distance = parseInt(this.getChildValue(node));
obj.distanceUnits = node.getAttribute("units");
}
}
},
/**
* Method: readSpatial
*
* Read a {<OpenLayers.Filter.Spatial>} filter.
*
* Parameters:
* node - {DOMElement} A DOM element that contains an ogc:expression.
* obj - {Object} The target object.
* type - {String} One of the OpenLayers.Filter.Spatial.* constants.
*
* Returns:
* {<OpenLayers.Filter.Spatial>} The created filter.
*/
readSpatial: function(node, obj, type) {
var filter = new OpenLayers.Filter.Spatial({
type: type
});
this.readChildNodes(node, filter);
filter.value = filter.components[0];
delete filter.components;
obj.filters.push(filter);
},
/**
* Method: readOgcExpression
* Limited support for OGC expressions.
*
* Parameters:
* node - {DOMElement} A DOM element that contains an ogc:expression.
*
* Returns:
* {String} A value to be used in a symbolizer.
*/
readOgcExpression: function(node) {
var obj = {};
this.readChildNodes(node, obj);
var value = obj.value;
if(!value) {
value = this.getChildValue(node);
}
return value;
},
/**
* Method: write
*
* Parameters:
* filter - {<OpenLayers.Filter>} A filter object.
*
* Returns:
* {DOMElement} An ogc:Filter element.
*/
write: function(filter) {
return this.writers.ogc["Filter"].apply(this, [filter]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"ogc": {
"Filter": function(filter) {
var node = this.createElementNSPlus("ogc:Filter");
var sub = filter.CLASS_NAME.split(".").pop();
if(sub == "FeatureId") {
for(var i=0; i<filter.fids.length; ++i) {
this.writeNode("FeatureId", filter.fids[i], node);
}
} else {
this.writeNode(this.getFilterType(filter), filter, node);
}
return node;
},
"FeatureId": function(fid) {
return this.createElementNSPlus("ogc:FeatureId", {
attributes: {fid: fid}
});
},
"And": function(filter) {
var node = this.createElementNSPlus("ogc:And");
var childFilter;
for(var i=0; i<filter.filters.length; ++i) {
childFilter = filter.filters[i];
this.writeNode(
this.getFilterType(childFilter), childFilter, node
);
}
return node;
},
"Or": function(filter) {
var node = this.createElementNSPlus("ogc:Or");
var childFilter;
for(var i=0; i<filter.filters.length; ++i) {
childFilter = filter.filters[i];
this.writeNode(
this.getFilterType(childFilter), childFilter, node
);
}
return node;
},
"Not": function(filter) {
var node = this.createElementNSPlus("ogc:Not");
var childFilter = filter.filters[0];
this.writeNode(
this.getFilterType(childFilter), childFilter, node
);
return node;
},
"PropertyIsLessThan": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsLessThan");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsGreaterThan": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsGreaterThan");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsLessThanOrEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsLessThanOrEqualTo");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsGreaterThanOrEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsGreaterThanOrEqualTo");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsBetween": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsBetween");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("LowerBoundary", filter, node);
this.writeNode("UpperBoundary", filter, node);
return node;
},
"PropertyIsLike": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsLike", {
attributes: {
wildCard: "*", singleChar: ".", escape: "!"
}
});
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
// convert regex string to ogc string
this.writeNode("Literal", filter.regex2value(), node);
return node;
},
"PropertyName": function(filter) {
// no ogc:expression handling for now
return this.createElementNSPlus("ogc:PropertyName", {
value: filter.property
});
},
"Literal": function(value) {
// no ogc:expression handling for now
return this.createElementNSPlus("ogc:Literal", {
value: value
});
},
"LowerBoundary": function(filter) {
// no ogc:expression handling for now
var node = this.createElementNSPlus("ogc:LowerBoundary");
this.writeNode("Literal", filter.lowerBoundary, node);
return node;
},
"UpperBoundary": function(filter) {
// no ogc:expression handling for now
var node = this.createElementNSPlus("ogc:UpperBoundary");
this.writeNode("Literal", filter.upperBoundary, node);
return node;
},
"INTERSECTS": function(filter) {
return this.writeSpatial(filter, "Intersects");
},
"WITHIN": function(filter) {
return this.writeSpatial(filter, "Within");
},
"CONTAINS": function(filter) {
return this.writeSpatial(filter, "Contains");
},
"DWITHIN": function(filter) {
var node = this.writeSpatial(filter, "DWithin");
this.writeNode("Distance", filter, node);
return node;
},
"Distance": function(filter) {
return this.createElementNSPlus("ogc:Distance", {
attributes: {
units: filter.distanceUnits
},
value: filter.distance
});
}
}
},
/**
* Method: getFilterType
*/
getFilterType: function(filter) {
var filterType = this.filterMap[filter.type];
if(!filterType) {
throw "Filter writing not supported for rule type: " + filter.type;
}
return filterType;
},
/**
* Property: filterMap
* {Object} Contains a member for each filter type. Values are node names
* for corresponding OGC Filter child elements.
*/
filterMap: {
"&&": "And",
"||": "Or",
"!": "Not",
"==": "PropertyIsEqualTo",
"!=": "PropertyIsNotEqualTo",
"<": "PropertyIsLessThan",
">": "PropertyIsGreaterThan",
"<=": "PropertyIsLessThanOrEqualTo",
">=": "PropertyIsGreaterThanOrEqualTo",
"..": "PropertyIsBetween",
"~": "PropertyIsLike",
"BBOX": "BBOX",
"DWITHIN": "DWITHIN",
"WITHIN": "WITHIN",
"CONTAINS": "CONTAINS",
"INTERSECTS": "INTERSECTS"
},
CLASS_NAME: "OpenLayers.Format.Filter.v1"
});

View File

@ -1,145 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/GML/v2.js
* @requires OpenLayers/Format/Filter/v1.js
*/
/**
* Class: OpenLayers.Format.Filter.v1_0_0
* Write ogc:Filter version 1.0.0.
*
* Inherits from:
* - <OpenLayers.Format.GML.v2>
* - <OpenLayers.Format.Filter.v1>
*/
OpenLayers.Format.Filter.v1_0_0 = OpenLayers.Class(
OpenLayers.Format.GML.v2, OpenLayers.Format.Filter.v1, {
/**
* Constant: VERSION
* {String} 1.0.0
*/
VERSION: "1.0.0",
/**
* Property: schemaLocation
* {String} http://www.opengis.net/ogc/filter/1.0.0/filter.xsd
*/
schemaLocation: "http://www.opengis.net/ogc/filter/1.0.0/filter.xsd",
/**
* Constructor: OpenLayers.Format.Filter.v1_0_0
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.Filter> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.GML.v2.prototype.initialize.apply(
this, [options]
);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"ogc": OpenLayers.Util.applyDefaults({
"PropertyIsEqualTo": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsNotEqualTo": function(node, obj) {
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
}
}, OpenLayers.Format.Filter.v1.prototype.readers["ogc"]),
"gml": OpenLayers.Format.GML.v2.prototype.readers["gml"],
"feature": OpenLayers.Format.GML.v2.prototype.readers["feature"]
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"ogc": OpenLayers.Util.applyDefaults({
"PropertyIsEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsEqualTo");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsNotEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsNotEqualTo");
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"BBOX": function(filter) {
var node = this.createElementNSPlus("ogc:BBOX");
this.writeNode("PropertyName", filter, node);
var box = this.writeNode("gml:Box", filter.value, node);
if(filter.projection) {
box.setAttribute("srsName", filter.projection);
}
return node;
}}, OpenLayers.Format.Filter.v1.prototype.writers["ogc"]),
"gml": OpenLayers.Format.GML.v2.prototype.writers["gml"],
"feature": OpenLayers.Format.GML.v2.prototype.writers["feature"]
},
/**
* Method: writeSpatial
*
* Read a {<OpenLayers.Filter.Spatial>} filter and converts it into XML.
*
* Parameters:
* filter - {<OpenLayers.Filter.Spatial>} The filter.
* name - {String} Name of the generated XML element.
*
* Returns:
* {DOMElement} The created XML element.
*/
writeSpatial: function(filter, name) {
var node = this.createElementNSPlus("ogc:"+name);
this.writeNode("PropertyName", filter, node);
var child;
if(filter.value instanceof OpenLayers.Geometry) {
child = this.writeNode("feature:_geometry", filter.value).firstChild;
} else {
child = this.writeNode("gml:Box", filter.value);
}
if(filter.projection) {
child.setAttribute("srsName", filter.projection);
}
node.appendChild(child);
return node;
},
CLASS_NAME: "OpenLayers.Format.Filter.v1_0_0"
});

View File

@ -1,158 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/Filter/v1.js
* @requires OpenLayers/Format/GML/v3.js
*/
/**
* Class: OpenLayers.Format.Filter.v1_1_0
* Write ogc:Filter version 1.1.0.
*
* Differences from the v1.0.0 parser:
* - uses GML v3 instead of GML v2
* - reads matchCase attribute on ogc:PropertyIsEqual and
* ogc:PropertyIsNotEqualelements.
* - writes matchCase attribute from comparison filters of type EQUAL_TO and
* type NOT_EQUAL_TO.
*
* Inherits from:
* - <OpenLayers.Format.Filter.v1>
*/
OpenLayers.Format.Filter.v1_1_0 = OpenLayers.Class(
OpenLayers.Format.GML.v3, OpenLayers.Format.Filter.v1, {
/**
* Constant: VERSION
* {String} 1.1.0
*/
VERSION: "1.1.0",
/**
* Property: schemaLocation
* {String} http://www.opengis.net/ogc/filter/1.1.0/filter.xsd
*/
schemaLocation: "http://www.opengis.net/ogc/filter/1.1.0/filter.xsd",
/**
* Constructor: OpenLayers.Format.Filter.v1_1_0
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.Filter> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.GML.v3.prototype.initialize.apply(
this, [options]
);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"ogc": OpenLayers.Util.applyDefaults({
"PropertyIsEqualTo": function(node, obj) {
var matchCase = node.getAttribute("matchCase");
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
matchCase: !(matchCase === "false" || matchCase === "0")
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
},
"PropertyIsNotEqualTo": function(node, obj) {
var matchCase = node.getAttribute("matchCase");
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
matchCase: !(matchCase === "false" || matchCase === "0")
});
this.readChildNodes(node, filter);
obj.filters.push(filter);
}
}, OpenLayers.Format.Filter.v1.prototype.readers["ogc"]),
"gml": OpenLayers.Format.GML.v3.prototype.readers["gml"],
"feature": OpenLayers.Format.GML.v3.prototype.readers["feature"]
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"ogc": OpenLayers.Util.applyDefaults({
"PropertyIsEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsEqualTo", {
attributes: {matchCase: filter.matchCase}
});
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"PropertyIsNotEqualTo": function(filter) {
var node = this.createElementNSPlus("ogc:PropertyIsNotEqualTo", {
attributes: {matchCase: filter.matchCase}
});
// no ogc:expression handling for now
this.writeNode("PropertyName", filter, node);
this.writeNode("Literal", filter.value, node);
return node;
},
"BBOX": function(filter) {
var node = this.createElementNSPlus("ogc:BBOX");
this.writeNode("PropertyName", filter, node);
var box = this.writeNode("gml:Envelope", filter.value);
if(filter.projection) {
box.setAttribute("srsName", filter.projection);
}
node.appendChild(box);
return node;
}}, OpenLayers.Format.Filter.v1.prototype.writers["ogc"]),
"gml": OpenLayers.Format.GML.v3.prototype.writers["gml"],
"feature": OpenLayers.Format.GML.v3.prototype.writers["feature"]
},
/**
* Method: writeSpatial
*
* Read a {<OpenLayers.Filter.Spatial>} filter and converts it into XML.
*
* Parameters:
* filter - {<OpenLayers.Filter.Spatial>} The filter.
* name - {String} Name of the generated XML element.
*
* Returns:
* {DOMElement} The created XML element.
*/
writeSpatial: function(filter, name) {
var node = this.createElementNSPlus("ogc:"+name);
this.writeNode("PropertyName", filter, node);
var child;
if(filter.value instanceof OpenLayers.Geometry) {
child = this.writeNode("feature:_geometry", filter.value).firstChild;
} else {
child = this.writeNode("gml:Envelope", filter.value);
}
if(filter.projection) {
child.setAttribute("srsName", filter.projection);
}
node.appendChild(child);
return node;
},
CLASS_NAME: "OpenLayers.Format.Filter.v1_1_0"
});

View File

@ -1,872 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
* @requires OpenLayers/Geometry/MultiPoint.js
* @requires OpenLayers/Geometry/LineString.js
* @requires OpenLayers/Geometry/MultiLineString.js
* @requires OpenLayers/Geometry/Polygon.js
* @requires OpenLayers/Geometry/MultiPolygon.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Format.GML
* Read/Wite GML. Create a new instance with the <OpenLayers.Format.GML>
* constructor. Supports the GML simple features profile.
*
* Inherits from:
* - <OpenLayers.Format>
*/
OpenLayers.Format.GML = OpenLayers.Class(OpenLayers.Format.XML, {
/*
* APIProperty: featureNS
* {String} Namespace used for feature attributes. Default is
* "http://mapserver.gis.umn.edu/mapserver".
*/
featureNS: "http://mapserver.gis.umn.edu/mapserver",
/**
* APIProperty: featurePrefix
* {String} Namespace alias (or prefix) for feature nodes. Default is
* "feature".
*/
featurePrefix: "feature",
/*
* APIProperty: featureName
* {String} Element name for features. Default is "featureMember".
*/
featureName: "featureMember",
/*
* APIProperty: layerName
* {String} Name of data layer. Default is "features".
*/
layerName: "features",
/**
* APIProperty: geometryName
* {String} Name of geometry element. Defaults to "geometry".
*/
geometryName: "geometry",
/**
* APIProperty: collectionName
* {String} Name of featureCollection element.
*/
collectionName: "FeatureCollection",
/**
* APIProperty: gmlns
* {String} GML Namespace.
*/
gmlns: "http://www.opengis.net/gml",
/**
* APIProperty: extractAttributes
* {Boolean} Extract attributes from GML.
*/
extractAttributes: true,
/**
* APIProperty: xy
* {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x)
* Changing is not recommended, a new Format should be instantiated.
*/
xy: true,
/**
* Constructor: OpenLayers.Format.GML
* Create a new parser for GML.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
// compile regular expressions once instead of every time they are used
this.regExes = {
trimSpace: (/^\s*|\s*$/g),
removeSpace: (/\s*/g),
splitSpace: (/\s+/),
trimComma: (/\s*,\s*/g)
};
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Read data from a string, and return a list of features.
*
* Parameters:
* data - {String} or {DOMElement} data to read/parse.
*
* Returns:
* {Array(<OpenLayers.Feature.Vector>)} An array of features.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var featureNodes = this.getElementsByTagNameNS(data.documentElement,
this.gmlns,
this.featureName);
var features = [];
for(var i=0; i<featureNodes.length; i++) {
var feature = this.parseFeature(featureNodes[i]);
if(feature) {
features.push(feature);
}
}
return features;
},
/**
* Method: parseFeature
* This function is the core of the GML parsing code in OpenLayers.
* It creates the geometries that are then attached to the returned
* feature, and calls parseAttributes() to get attribute data out.
*
* Parameters:
* node - {DOMElement} A GML feature node.
*/
parseFeature: function(node) {
// only accept one geometry per feature - look for highest "order"
var order = ["MultiPolygon", "Polygon",
"MultiLineString", "LineString",
"MultiPoint", "Point", "Envelope", "Box"];
var type, nodeList, geometry, parser;
for(var i=0; i<order.length; ++i) {
type = order[i];
nodeList = this.getElementsByTagNameNS(node, this.gmlns, type);
if(nodeList.length > 0) {
// only deal with first geometry of this type
var parser = this.parseGeometry[type.toLowerCase()];
if(parser) {
geometry = parser.apply(this, [nodeList[0]]);
if (this.internalProjection && this.externalProjection) {
geometry.transform(this.externalProjection,
this.internalProjection);
}
} else {
OpenLayers.Console.error(OpenLayers.i18n(
"unsupportedGeometryType", {'geomType':type}));
}
// stop looking for different geometry types
break;
}
}
// construct feature (optionally with attributes)
var attributes;
if(this.extractAttributes) {
attributes = this.parseAttributes(node);
}
var feature = new OpenLayers.Feature.Vector(geometry, attributes);
feature.gml = {
featureType: node.firstChild.nodeName.split(":")[1],
featureNS: node.firstChild.namespaceURI,
featureNSPrefix: node.firstChild.prefix
};
// assign fid - this can come from a "fid" or "id" attribute
var childNode = node.firstChild;
var fid;
while(childNode) {
if(childNode.nodeType == 1) {
fid = childNode.getAttribute("fid") ||
childNode.getAttribute("id");
if(fid) {
break;
}
}
childNode = childNode.nextSibling;
}
feature.fid = fid;
return feature;
},
/**
* Property: parseGeometry
* Properties of this object are the functions that parse geometries based
* on their type.
*/
parseGeometry: {
/**
* Method: parseGeometry.point
* Given a GML node representing a point geometry, create an OpenLayers
* point geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.Point>} A point geometry.
*/
point: function(node) {
/**
* Three coordinate variations to consider:
* 1) <gml:pos>x y z</gml:pos>
* 2) <gml:coordinates>x, y, z</gml:coordinates>
* 3) <gml:coord><gml:X>x</gml:X><gml:Y>y</gml:Y></gml:coord>
*/
var nodeList, coordString;
var coords = [];
// look for <gml:pos>
var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "pos");
if(nodeList.length > 0) {
coordString = nodeList[0].firstChild.nodeValue;
coordString = coordString.replace(this.regExes.trimSpace, "");
coords = coordString.split(this.regExes.splitSpace);
}
// look for <gml:coordinates>
if(coords.length == 0) {
nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"coordinates");
if(nodeList.length > 0) {
coordString = nodeList[0].firstChild.nodeValue;
coordString = coordString.replace(this.regExes.removeSpace,
"");
coords = coordString.split(",");
}
}
// look for <gml:coord>
if(coords.length == 0) {
nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"coord");
if(nodeList.length > 0) {
var xList = this.getElementsByTagNameNS(nodeList[0],
this.gmlns, "X");
var yList = this.getElementsByTagNameNS(nodeList[0],
this.gmlns, "Y");
if(xList.length > 0 && yList.length > 0) {
coords = [xList[0].firstChild.nodeValue,
yList[0].firstChild.nodeValue];
}
}
}
// preserve third dimension
if(coords.length == 2) {
coords[2] = null;
}
if (this.xy) {
return new OpenLayers.Geometry.Point(coords[0], coords[1],
coords[2]);
}
else{
return new OpenLayers.Geometry.Point(coords[1], coords[0],
coords[2]);
}
},
/**
* Method: parseGeometry.multipoint
* Given a GML node representing a multipoint geometry, create an
* OpenLayers multipoint geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.MultiPoint>} A multipoint geometry.
*/
multipoint: function(node) {
var nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"Point");
var components = [];
if(nodeList.length > 0) {
var point;
for(var i=0; i<nodeList.length; ++i) {
point = this.parseGeometry.point.apply(this, [nodeList[i]]);
if(point) {
components.push(point);
}
}
}
return new OpenLayers.Geometry.MultiPoint(components);
},
/**
* Method: parseGeometry.linestring
* Given a GML node representing a linestring geometry, create an
* OpenLayers linestring geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.LineString>} A linestring geometry.
*/
linestring: function(node, ring) {
/**
* Two coordinate variations to consider:
* 1) <gml:posList dimension="d">x0 y0 z0 x1 y1 z1</gml:posList>
* 2) <gml:coordinates>x0, y0, z0 x1, y1, z1</gml:coordinates>
*/
var nodeList, coordString;
var coords = [];
var points = [];
// look for <gml:posList>
nodeList = this.getElementsByTagNameNS(node, this.gmlns, "posList");
if(nodeList.length > 0) {
coordString = this.getChildValue(nodeList[0]);
coordString = coordString.replace(this.regExes.trimSpace, "");
coords = coordString.split(this.regExes.splitSpace);
var dim = parseInt(nodeList[0].getAttribute("dimension"));
var j, x, y, z;
for(var i=0; i<coords.length/dim; ++i) {
j = i * dim;
x = coords[j];
y = coords[j+1];
z = (dim == 2) ? null : coords[j+2];
if (this.xy) {
points.push(new OpenLayers.Geometry.Point(x, y, z));
} else {
points.push(new OpenLayers.Geometry.Point(y, x, z));
}
}
}
// look for <gml:coordinates>
if(coords.length == 0) {
nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"coordinates");
if(nodeList.length > 0) {
coordString = this.getChildValue(nodeList[0]);
coordString = coordString.replace(this.regExes.trimSpace,
"");
coordString = coordString.replace(this.regExes.trimComma,
",");
var pointList = coordString.split(this.regExes.splitSpace);
for(var i=0; i<pointList.length; ++i) {
coords = pointList[i].split(",");
if(coords.length == 2) {
coords[2] = null;
}
if (this.xy) {
points.push(new OpenLayers.Geometry.Point(coords[0],
coords[1],
coords[2]));
} else {
points.push(new OpenLayers.Geometry.Point(coords[1],
coords[0],
coords[2]));
}
}
}
}
var line = null;
if(points.length != 0) {
if(ring) {
line = new OpenLayers.Geometry.LinearRing(points);
} else {
line = new OpenLayers.Geometry.LineString(points);
}
}
return line;
},
/**
* Method: parseGeometry.multilinestring
* Given a GML node representing a multilinestring geometry, create an
* OpenLayers multilinestring geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.MultiLineString>} A multilinestring geometry.
*/
multilinestring: function(node) {
var nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"LineString");
var components = [];
if(nodeList.length > 0) {
var line;
for(var i=0; i<nodeList.length; ++i) {
line = this.parseGeometry.linestring.apply(this,
[nodeList[i]]);
if(line) {
components.push(line);
}
}
}
return new OpenLayers.Geometry.MultiLineString(components);
},
/**
* Method: parseGeometry.polygon
* Given a GML node representing a polygon geometry, create an
* OpenLayers polygon geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.Polygon>} A polygon geometry.
*/
polygon: function(node) {
var nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"LinearRing");
var components = [];
if(nodeList.length > 0) {
// this assumes exterior ring first, inner rings after
var ring;
for(var i=0; i<nodeList.length; ++i) {
ring = this.parseGeometry.linestring.apply(this,
[nodeList[i], true]);
if(ring) {
components.push(ring);
}
}
}
return new OpenLayers.Geometry.Polygon(components);
},
/**
* Method: parseGeometry.multipolygon
* Given a GML node representing a multipolygon geometry, create an
* OpenLayers multipolygon geometry.
*
* Parameters:
* node - {DOMElement} A GML node.
*
* Returns:
* {<OpenLayers.Geometry.MultiPolygon>} A multipolygon geometry.
*/
multipolygon: function(node) {
var nodeList = this.getElementsByTagNameNS(node, this.gmlns,
"Polygon");
var components = [];
if(nodeList.length > 0) {
var polygon;
for(var i=0; i<nodeList.length; ++i) {
polygon = this.parseGeometry.polygon.apply(this,
[nodeList[i]]);
if(polygon) {
components.push(polygon);
}
}
}
return new OpenLayers.Geometry.MultiPolygon(components);
},
envelope: function(node) {
var components = [];
var coordString;
var envelope;
var lpoint = this.getElementsByTagNameNS(node, this.gmlns, "lowerCorner");
if (lpoint.length > 0) {
var coords = [];
if(lpoint.length > 0) {
coordString = lpoint[0].firstChild.nodeValue;
coordString = coordString.replace(this.regExes.trimSpace, "");
coords = coordString.split(this.regExes.splitSpace);
}
if(coords.length == 2) {
coords[2] = null;
}
if (this.xy) {
var lowerPoint = new OpenLayers.Geometry.Point(coords[0], coords[1],coords[2]);
} else {
var lowerPoint = new OpenLayers.Geometry.Point(coords[1], coords[0],coords[2]);
}
}
var upoint = this.getElementsByTagNameNS(node, this.gmlns, "upperCorner");
if (upoint.length > 0) {
var coords = [];
if(upoint.length > 0) {
coordString = upoint[0].firstChild.nodeValue;
coordString = coordString.replace(this.regExes.trimSpace, "");
coords = coordString.split(this.regExes.splitSpace);
}
if(coords.length == 2) {
coords[2] = null;
}
if (this.xy) {
var upperPoint = new OpenLayers.Geometry.Point(coords[0], coords[1],coords[2]);
} else {
var upperPoint = new OpenLayers.Geometry.Point(coords[1], coords[0],coords[2]);
}
}
if (lowerPoint && upperPoint) {
components.push(new OpenLayers.Geometry.Point(lowerPoint.x, lowerPoint.y));
components.push(new OpenLayers.Geometry.Point(upperPoint.x, lowerPoint.y));
components.push(new OpenLayers.Geometry.Point(upperPoint.x, upperPoint.y));
components.push(new OpenLayers.Geometry.Point(lowerPoint.x, upperPoint.y));
components.push(new OpenLayers.Geometry.Point(lowerPoint.x, lowerPoint.y));
var ring = new OpenLayers.Geometry.LinearRing(components);
envelope = new OpenLayers.Geometry.Polygon([ring]);
}
return envelope;
}
},
/**
* Method: parseAttributes
*
* Parameters:
* node - {<DOMElement>}
*
* Returns:
* {Object} An attributes object.
*/
parseAttributes: function(node) {
var attributes = {};
// assume attributes are children of the first type 1 child
var childNode = node.firstChild;
var children, i, child, grandchildren, grandchild, name, value;
while(childNode) {
if(childNode.nodeType == 1) {
// attributes are type 1 children with one type 3 child
children = childNode.childNodes;
for(i=0; i<children.length; ++i) {
child = children[i];
if(child.nodeType == 1) {
grandchildren = child.childNodes;
if(grandchildren.length == 1) {
grandchild = grandchildren[0];
if(grandchild.nodeType == 3 ||
grandchild.nodeType == 4) {
name = (child.prefix) ?
child.nodeName.split(":")[1] :
child.nodeName;
value = grandchild.nodeValue.replace(
this.regExes.trimSpace, "");
attributes[name] = value;
}
} else {
// If child has no childNodes (grandchildren),
// set an attribute with null value.
// e.g. <prefix:fieldname/> becomes
// {fieldname: null}
attributes[child.nodeName.split(":").pop()] = null;
}
}
}
break;
}
childNode = childNode.nextSibling;
}
return attributes;
},
/**
* APIMethod: write
* Generate a GML document string given a list of features.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)} List of features to
* serialize into a string.
*
* Returns:
* {String} A string representing the GML document.
*/
write: function(features) {
if(!(features instanceof Array)) {
features = [features];
}
var gml = this.createElementNS("http://www.opengis.net/wfs",
"wfs:" + this.collectionName);
for(var i=0; i<features.length; i++) {
gml.appendChild(this.createFeatureXML(features[i]));
}
return OpenLayers.Format.XML.prototype.write.apply(this, [gml]);
},
/**
* Method: createFeatureXML
* Accept an OpenLayers.Feature.Vector, and build a GML node for it.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>} The feature to be built as GML.
*
* Returns:
* {DOMElement} A node reprensting the feature in GML.
*/
createFeatureXML: function(feature) {
var geometry = feature.geometry;
var geometryNode = this.buildGeometryNode(geometry);
var geomContainer = this.createElementNS(this.featureNS,
this.featurePrefix + ":" +
this.geometryName);
geomContainer.appendChild(geometryNode);
var featureNode = this.createElementNS(this.gmlns,
"gml:" + this.featureName);
var featureContainer = this.createElementNS(this.featureNS,
this.featurePrefix + ":" +
this.layerName);
var fid = feature.fid || feature.id;
featureContainer.setAttribute("fid", fid);
featureContainer.appendChild(geomContainer);
for(var attr in feature.attributes) {
var attrText = this.createTextNode(feature.attributes[attr]);
var nodename = attr.substring(attr.lastIndexOf(":") + 1);
var attrContainer = this.createElementNS(this.featureNS,
this.featurePrefix + ":" +
nodename);
attrContainer.appendChild(attrText);
featureContainer.appendChild(attrContainer);
}
featureNode.appendChild(featureContainer);
return featureNode;
},
/**
* APIMethod: buildGeometryNode
*/
buildGeometryNode: function(geometry) {
if (this.externalProjection && this.internalProjection) {
geometry = geometry.clone();
geometry.transform(this.internalProjection,
this.externalProjection);
}
var className = geometry.CLASS_NAME;
var type = className.substring(className.lastIndexOf(".") + 1);
var builder = this.buildGeometry[type.toLowerCase()];
return builder.apply(this, [geometry]);
},
/**
* Property: buildGeometry
* Object containing methods to do the actual geometry node building
* based on geometry type.
*/
buildGeometry: {
// TBD retrieve the srs from layer
// srsName is non-standard, so not including it until it's right.
// gml.setAttribute("srsName",
// "http://www.opengis.net/gml/srs/epsg.xml#4326");
/**
* Method: buildGeometry.point
* Given an OpenLayers point geometry, create a GML point.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.Point>} A point geometry.
*
* Returns:
* {DOMElement} A GML point node.
*/
point: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:Point");
gml.appendChild(this.buildCoordinatesNode(geometry));
return gml;
},
/**
* Method: buildGeometry.multipoint
* Given an OpenLayers multipoint geometry, create a GML multipoint.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.MultiPoint>} A multipoint geometry.
*
* Returns:
* {DOMElement} A GML multipoint node.
*/
multipoint: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:MultiPoint");
var points = geometry.components;
var pointMember, pointGeom;
for(var i=0; i<points.length; i++) {
pointMember = this.createElementNS(this.gmlns,
"gml:pointMember");
pointGeom = this.buildGeometry.point.apply(this,
[points[i]]);
pointMember.appendChild(pointGeom);
gml.appendChild(pointMember);
}
return gml;
},
/**
* Method: buildGeometry.linestring
* Given an OpenLayers linestring geometry, create a GML linestring.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.LineString>} A linestring geometry.
*
* Returns:
* {DOMElement} A GML linestring node.
*/
linestring: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:LineString");
gml.appendChild(this.buildCoordinatesNode(geometry));
return gml;
},
/**
* Method: buildGeometry.multilinestring
* Given an OpenLayers multilinestring geometry, create a GML
* multilinestring.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.MultiLineString>} A multilinestring
* geometry.
*
* Returns:
* {DOMElement} A GML multilinestring node.
*/
multilinestring: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:MultiLineString");
var lines = geometry.components;
var lineMember, lineGeom;
for(var i=0; i<lines.length; ++i) {
lineMember = this.createElementNS(this.gmlns,
"gml:lineStringMember");
lineGeom = this.buildGeometry.linestring.apply(this,
[lines[i]]);
lineMember.appendChild(lineGeom);
gml.appendChild(lineMember);
}
return gml;
},
/**
* Method: buildGeometry.linearring
* Given an OpenLayers linearring geometry, create a GML linearring.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.LinearRing>} A linearring geometry.
*
* Returns:
* {DOMElement} A GML linearring node.
*/
linearring: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:LinearRing");
gml.appendChild(this.buildCoordinatesNode(geometry));
return gml;
},
/**
* Method: buildGeometry.polygon
* Given an OpenLayers polygon geometry, create a GML polygon.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.Polygon>} A polygon geometry.
*
* Returns:
* {DOMElement} A GML polygon node.
*/
polygon: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:Polygon");
var rings = geometry.components;
var ringMember, ringGeom, type;
for(var i=0; i<rings.length; ++i) {
type = (i==0) ? "outerBoundaryIs" : "innerBoundaryIs";
ringMember = this.createElementNS(this.gmlns,
"gml:" + type);
ringGeom = this.buildGeometry.linearring.apply(this,
[rings[i]]);
ringMember.appendChild(ringGeom);
gml.appendChild(ringMember);
}
return gml;
},
/**
* Method: buildGeometry.multipolygon
* Given an OpenLayers multipolygon geometry, create a GML multipolygon.
*
* Parameters:
* geometry - {<OpenLayers.Geometry.MultiPolygon>} A multipolygon
* geometry.
*
* Returns:
* {DOMElement} A GML multipolygon node.
*/
multipolygon: function(geometry) {
var gml = this.createElementNS(this.gmlns, "gml:MultiPolygon");
var polys = geometry.components;
var polyMember, polyGeom;
for(var i=0; i<polys.length; ++i) {
polyMember = this.createElementNS(this.gmlns,
"gml:polygonMember");
polyGeom = this.buildGeometry.polygon.apply(this,
[polys[i]]);
polyMember.appendChild(polyGeom);
gml.appendChild(polyMember);
}
return gml;
},
/**
* Method: buildGeometry.bounds
* Given an OpenLayers bounds, create a GML box.
*
* Parameters:
* bounds - {<OpenLayers.Geometry.Bounds>} A bounds object.
*
* Returns:
* {DOMElement} A GML box node.
*/
bounds: function(bounds) {
var gml = this.createElementNS(this.gmlns, "gml:Box");
gml.appendChild(this.buildCoordinatesNode(bounds));
return gml;
}
},
/**
* Method: buildCoordinates
* builds the coordinates XmlNode
* (code)
* <gml:coordinates decimal="." cs="," ts=" ">...</gml:coordinates>
* (end)
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {XmlNode} created xmlNode
*/
buildCoordinatesNode: function(geometry) {
var coordinatesNode = this.createElementNS(this.gmlns,
"gml:coordinates");
coordinatesNode.setAttribute("decimal", ".");
coordinatesNode.setAttribute("cs", ",");
coordinatesNode.setAttribute("ts", " ");
var parts = [];
if(geometry instanceof OpenLayers.Bounds){
parts.push(geometry.left + "," + geometry.bottom);
parts.push(geometry.right + "," + geometry.top);
} else {
var points = (geometry.components) ? geometry.components : [geometry];
for(var i=0; i<points.length; i++) {
parts.push(points[i].x + "," + points[i].y);
}
}
var txtNode = this.createTextNode(parts.join(" "));
coordinatesNode.appendChild(txtNode);
return coordinatesNode;
},
CLASS_NAME: "OpenLayers.Format.GML"
});

View File

@ -1,572 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML.js
* @requires OpenLayers/Format/GML.js
*/
/**
* Though required in the full build, if the GML format is excluded, we set
* the namespace here.
*/
if(!OpenLayers.Format.GML) {
OpenLayers.Format.GML = {};
}
/**
* Class: OpenLayers.Format.GML.Base
* Superclass for GML parsers.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.GML.Base = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* Property: namespaces
* {Object} Mapping of namespace aliases to namespace URIs.
*/
namespaces: {
gml: "http://www.opengis.net/gml",
xlink: "http://www.w3.org/1999/xlink",
xsi: "http://www.w3.org/2001/XMLSchema-instance",
wfs: "http://www.opengis.net/wfs" // this is a convenience for reading wfs:FeatureCollection
},
/**
* Property: defaultPrefix
*/
defaultPrefix: "gml",
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version.
*/
schemaLocation: null,
/**
* APIProperty: featureType
* {Array(String) or String} The local (without prefix) feature typeName(s).
*/
featureType: null,
/**
* APIProperty: featureNS
* {String} The feature namespace. Must be set in the options at
* construction.
*/
featureNS: null,
/**
* APIProperty: geometry
* {String} Name of geometry element. Defaults to "geometry".
*/
geometryName: "geometry",
/**
* APIProperty: extractAttributes
* {Boolean} Extract attributes from GML. Default is true.
*/
extractAttributes: true,
/**
* APIProperty: srsName
* {String} URI for spatial reference system. This is optional for
* single part geometries and mandatory for collections and multis.
* If set, the srsName attribute will be written for all geometries.
* Default is null.
*/
srsName: null,
/**
* APIProperty: xy
* {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x)
* Changing is not recommended, a new Format should be instantiated.
*/
xy: true,
/**
* Property: geometryTypes
* {Object} Maps OpenLayers geometry class names to GML element names.
* Use <setGeometryTypes> before accessing this property.
*/
geometryTypes: null,
/**
* Property: singleFeatureType
* {Boolean} True if there is only 1 featureType, and not an array
* of featuretypes.
*/
singleFeatureType: null,
/**
* Property: regExes
* Compiled regular expressions for manipulating strings.
*/
regExes: {
trimSpace: (/^\s*|\s*$/g),
removeSpace: (/\s*/g),
splitSpace: (/\s+/),
trimComma: (/\s*,\s*/g)
},
/**
* Constructor: OpenLayers.Format.GML.Base
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.GML.v2> or <OpenLayers.Format.GML.v3> constructor
* instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*
* Valid options properties:
* featureType - {Array(String) or String} Local (without prefix) feature
* typeName(s) (required).
* featureNS - {String} Feature namespace (required).
* geometryName - {String} Geometry element name.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
this.setGeometryTypes();
if(options && options.featureNS) {
this.setNamespace("feature", options.featureNS);
}
this.singleFeatureType = !options || (typeof options.featureType === "string");
},
/**
* Method: read
*
* Parameters:
* data - {DOMElement} A gml:featureMember element, a gml:featureMembers
* element, or an element containing either of the above at any level.
*
* Returns:
* {Array(<OpenLayers.Feature.Vector>)} An array of features.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
if(data && data.nodeType == 9) {
data = data.documentElement;
}
var features = [];
this.readNode(data, {features: features});
if(features.length == 0) {
// look for gml:featureMember elements
var elements = this.getElementsByTagNameNS(
data, this.namespaces.gml, "featureMember"
);
if(elements.length) {
for(var i=0, len=elements.length; i<len; ++i) {
this.readNode(elements[i], {features: features});
}
} else {
// look for gml:featureMembers elements (this is v3, but does no harm here)
var elements = this.getElementsByTagNameNS(
data, this.namespaces.gml, "featureMembers"
);
if(elements.length) {
// there can be only one
this.readNode(elements[0], {features: features});
}
}
}
return features;
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"gml": {
"featureMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"featureMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"name": function(node, obj) {
obj.name = this.getChildValue(node);
},
"boundedBy": function(node, obj) {
var container = {};
this.readChildNodes(node, container);
if(container.components && container.components.length > 0) {
obj.bounds = container.components[0];
}
},
"Point": function(node, container) {
var obj = {points: []};
this.readChildNodes(node, obj);
if(!container.components) {
container.components = [];
}
container.components.push(obj.points[0]);
},
"coordinates": function(node, obj) {
var str = this.getChildValue(node).replace(
this.regExes.trimSpace, ""
);
str = str.replace(this.regExes.trimComma, ",");
var pointList = str.split(this.regExes.splitSpace);
var coords;
var numPoints = pointList.length;
var points = new Array(numPoints);
for(var i=0; i<numPoints; ++i) {
coords = pointList[i].split(",");
if (this.xy) {
points[i] = new OpenLayers.Geometry.Point(
coords[0], coords[1], coords[2]
);
} else {
points[i] = new OpenLayers.Geometry.Point(
coords[1], coords[0], coords[2]
);
}
}
obj.points = points;
},
"coord": function(node, obj) {
var coord = {};
this.readChildNodes(node, coord);
if(!obj.points) {
obj.points = [];
}
obj.points.push(new OpenLayers.Geometry.Point(
coord.x, coord.y, coord.z
));
},
"X": function(node, coord) {
coord.x = this.getChildValue(node);
},
"Y": function(node, coord) {
coord.y = this.getChildValue(node);
},
"Z": function(node, coord) {
coord.z = this.getChildValue(node);
},
"MultiPoint": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
container.components = [
new OpenLayers.Geometry.MultiPoint(obj.components)
];
},
"pointMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"LineString": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
if(!container.components) {
container.components = [];
}
container.components.push(
new OpenLayers.Geometry.LineString(obj.points)
);
},
"MultiLineString": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
container.components = [
new OpenLayers.Geometry.MultiLineString(obj.components)
];
},
"lineStringMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"Polygon": function(node, container) {
var obj = {outer: null, inner: []};
this.readChildNodes(node, obj);
obj.inner.unshift(obj.outer);
if(!container.components) {
container.components = [];
}
container.components.push(
new OpenLayers.Geometry.Polygon(obj.inner)
);
},
"LinearRing": function(node, obj) {
var container = {};
this.readChildNodes(node, container);
obj.components = [new OpenLayers.Geometry.LinearRing(
container.points
)];
},
"MultiPolygon": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
container.components = [
new OpenLayers.Geometry.MultiPolygon(obj.components)
];
},
"polygonMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"GeometryCollection": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
container.components = [
new OpenLayers.Geometry.Collection(obj.components)
];
},
"geometryMember": function(node, obj) {
this.readChildNodes(node, obj);
}
},
"feature": {
"*": function(node, obj) {
// The node can either be named like the featureType, or it
// can be a child of the feature:featureType. Children can be
// geometry or attributes.
var name;
var local = node.localName || node.nodeName.split(":").pop();
if (!this.singleFeatureType &&
(OpenLayers.Util.indexOf(this.featureType, local) != -1)) {
name = "_typeName";
}
else if(local == this.featureType) {
name = "_typeName";
} else {
// Assume attribute elements have one child node and that the child
// is a text node. Otherwise assume it is a geometry node.
if(node.childNodes.length == 0 ||
(node.childNodes.length == 1 && node.firstChild.nodeType == 3)) {
if(this.extractAttributes) {
name = "_attribute";
}
} else {
name = "_geometry";
}
}
if(name) {
this.readers.feature[name].apply(this, [node, obj]);
}
},
"_typeName": function(node, obj) {
var container = {components: [], attributes: {}};
this.readChildNodes(node, container);
// look for common gml namespaced elements
if(container.name) {
container.attributes.name = container.name;
}
var feature = new OpenLayers.Feature.Vector(
container.components[0], container.attributes
);
if (!this.singleFeatureType) {
feature.type = node.nodeName.split(":").pop();
feature.namespace = node.namespaceURI;
}
var fid = node.getAttribute("fid") ||
this.getAttributeNS(node, this.namespaces["gml"], "id");
if(fid) {
feature.fid = fid;
}
if(this.internalProjection && this.externalProjection &&
feature.geometry) {
feature.geometry.transform(
this.externalProjection, this.internalProjection
);
}
if(container.bounds) {
feature.geometry.bounds = container.bounds;
}
obj.features.push(feature);
},
"_geometry": function(node, obj) {
this.readChildNodes(node, obj);
},
"_attribute": function(node, obj) {
var local = node.localName || node.nodeName.split(":").pop();
var value = this.getChildValue(node);
obj.attributes[local] = value;
}
},
"wfs": {
"FeatureCollection": function(node, obj) {
this.readChildNodes(node, obj);
}
}
},
/**
* Method: write
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>) | OpenLayers.Feature.Vector}
* An array of features or a single feature.
*
* Returns:
* {String} Given an array of features, a doc with a gml:featureMembers
* element will be returned. Given a single feature, a doc with a
* gml:featureMember element will be returned.
*/
write: function(features) {
var name;
if(features instanceof Array) {
name = "featureMembers";
} else {
name = "featureMember";
}
var root = this.writeNode("gml:" + name, features);
this.setAttributeNS(
root, this.namespaces["xsi"],
"xsi:schemaLocation", this.schemaLocation
);
return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"gml": {
"featureMember": function(feature) {
var node = this.createElementNSPlus("gml:featureMember");
this.writeNode("feature:_typeName", feature, node);
return node;
},
"MultiPoint": function(geometry) {
var node = this.createElementNSPlus("gml:MultiPoint");
for(var i=0; i<geometry.components.length; ++i) {
this.writeNode("pointMember", geometry.components[i], node);
}
return node;
},
"pointMember": function(geometry) {
var node = this.createElementNSPlus("gml:pointMember");
this.writeNode("Point", geometry, node);
return node;
},
"MultiLineString": function(geometry) {
var node = this.createElementNSPlus("gml:MultiLineString");
for(var i=0; i<geometry.components.length; ++i) {
this.writeNode("lineStringMember", geometry.components[i], node);
}
return node;
},
"lineStringMember": function(geometry) {
var node = this.createElementNSPlus("gml:lineStringMember");
this.writeNode("LineString", geometry, node);
return node;
},
"MultiPolygon": function(geometry) {
var node = this.createElementNSPlus("gml:MultiPolygon");
for(var i=0; i<geometry.components.length; ++i) {
this.writeNode(
"polygonMember", geometry.components[i], node
);
}
return node;
},
"polygonMember": function(geometry) {
var node = this.createElementNSPlus("gml:polygonMember");
this.writeNode("Polygon", geometry, node);
return node;
},
"GeometryCollection": function(geometry) {
var node = this.createElementNSPlus("gml:GeometryCollection");
for(var i=0, len=geometry.components.length; i<len; ++i) {
this.writeNode("geometryMember", geometry.components[i], node);
}
return node;
},
"geometryMember": function(geometry) {
var node = this.createElementNSPlus("gml:geometryMember");
var child = this.writeNode("feature:_geometry", geometry);
node.appendChild(child.firstChild);
return node;
}
},
"feature": {
"_typeName": function(feature) {
var node = this.createElementNSPlus("feature:" + this.featureType, {
attributes: {fid: feature.fid}
});
if(feature.geometry) {
this.writeNode("feature:_geometry", feature.geometry, node);
}
for(var name in feature.attributes) {
var value = feature.attributes[name];
if(value != null) {
this.writeNode(
"feature:_attribute",
{name: name, value: value}, node
);
}
}
return node;
},
"_geometry": function(geometry) {
if(this.externalProjection && this.internalProjection) {
geometry = geometry.clone().transform(
this.internalProjection, this.externalProjection
);
}
var node = this.createElementNSPlus(
"feature:" + this.geometryName
);
var type = this.geometryTypes[geometry.CLASS_NAME];
var child = this.writeNode("gml:" + type, geometry, node);
if(this.srsName) {
child.setAttribute("srsName", this.srsName);
}
return node;
},
"_attribute": function(obj) {
return this.createElementNSPlus("feature:" + obj.name, {
value: obj.value
});
}
},
"wfs": {
"FeatureCollection": function(features) {
/**
* This is only here because GML2 only describes abstract
* feature collections. Typically, you would not be using
* the GML format to write wfs elements. This just provides
* some way to write out lists of features. GML3 defines the
* featureMembers element, so that is used by default instead.
*/
var node = this.createElementNSPlus("wfs:FeatureCollection");
for(var i=0, len=features.length; i<len; ++i) {
this.writeNode("gml:featureMember", features[i], node);
}
return node;
}
}
},
/**
* Function: setGeometryTypes
* Sets the <geometryTypes> mapping.
*/
setGeometryTypes: function() {
this.geometryTypes = {
"OpenLayers.Geometry.Point": "Point",
"OpenLayers.Geometry.MultiPoint": "MultiPoint",
"OpenLayers.Geometry.LineString": "LineString",
"OpenLayers.Geometry.MultiLineString": "MultiLineString",
"OpenLayers.Geometry.Polygon": "Polygon",
"OpenLayers.Geometry.MultiPolygon": "MultiPolygon",
"OpenLayers.Geometry.Collection": "GeometryCollection"
};
},
CLASS_NAME: "OpenLayers.Format.GML.Base"
});

View File

@ -1,192 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/GML/Base.js
*/
/**
* Class: OpenLayers.Format.GML.v2
* Parses GML version 2.
*
* Inherits from:
* - <OpenLayers.Format.GML.Base>
*/
OpenLayers.Format.GML.v2 = OpenLayers.Class(OpenLayers.Format.GML.Base, {
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version.
*/
schemaLocation: "http://www.opengis.net/gml http://schemas.opengis.net/gml/2.1.2/feature.xsd",
/**
* Constructor: OpenLayers.Format.GML.v2
* Create a parser for GML v2.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*
* Valid options properties:
* featureType - {String} Local (without prefix) feature typeName (required).
* featureNS - {String} Feature namespace (required).
* geometryName - {String} Geometry element name.
*/
initialize: function(options) {
OpenLayers.Format.GML.Base.prototype.initialize.apply(this, [options]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"gml": OpenLayers.Util.applyDefaults({
"outerBoundaryIs": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
container.outer = obj.components[0];
},
"innerBoundaryIs": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
container.inner.push(obj.components[0]);
},
"Box": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
if(!container.components) {
container.components = [];
}
var min = obj.points[0];
var max = obj.points[1];
container.components.push(
new OpenLayers.Bounds(min.x, min.y, max.x, max.y)
);
}
}, OpenLayers.Format.GML.Base.prototype.readers["gml"]),
"feature": OpenLayers.Format.GML.Base.prototype.readers["feature"],
"wfs": OpenLayers.Format.GML.Base.prototype.readers["wfs"]
},
/**
* Method: write
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>) | OpenLayers.Feature.Vector}
* An array of features or a single feature.
*
* Returns:
* {String} Given an array of features, a doc with a gml:featureMembers
* element will be returned. Given a single feature, a doc with a
* gml:featureMember element will be returned.
*/
write: function(features) {
var name;
if(features instanceof Array) {
// GML2 only has abstract feature collections
// wfs provides a feature collection from a well-known schema
name = "wfs:FeatureCollection";
} else {
name = "gml:featureMember";
}
var root = this.writeNode(name, features);
this.setAttributeNS(
root, this.namespaces["xsi"],
"xsi:schemaLocation", this.schemaLocation
);
return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"gml": OpenLayers.Util.applyDefaults({
"Point": function(geometry) {
var node = this.createElementNSPlus("gml:Point");
this.writeNode("coordinates", [geometry], node);
return node;
},
"coordinates": function(points) {
var numPoints = points.length;
var parts = new Array(numPoints);
var point;
for(var i=0; i<numPoints; ++i) {
point = points[i];
if(this.xy) {
parts[i] = point.x + "," + point.y;
} else {
parts[i] = point.y + "," + point.x;
}
if(point.z != undefined) { // allow null or undefined
parts[i] += "," + point.z;
}
}
return this.createElementNSPlus("gml:coordinates", {
attributes: {
decimal: ".", cs: ",", ts: " "
},
value: (numPoints == 1) ? parts[0] : parts.join(" ")
});
},
"LineString": function(geometry) {
var node = this.createElementNSPlus("gml:LineString");
this.writeNode("coordinates", geometry.components, node);
return node;
},
"Polygon": function(geometry) {
var node = this.createElementNSPlus("gml:Polygon");
this.writeNode("outerBoundaryIs", geometry.components[0], node);
for(var i=1; i<geometry.components.length; ++i) {
this.writeNode(
"innerBoundaryIs", geometry.components[i], node
);
}
return node;
},
"outerBoundaryIs": function(ring) {
var node = this.createElementNSPlus("gml:outerBoundaryIs");
this.writeNode("LinearRing", ring, node);
return node;
},
"innerBoundaryIs": function(ring) {
var node = this.createElementNSPlus("gml:innerBoundaryIs");
this.writeNode("LinearRing", ring, node);
return node;
},
"LinearRing": function(ring) {
var node = this.createElementNSPlus("gml:LinearRing");
this.writeNode("coordinates", ring.components, node);
return node;
},
"Box": function(bounds) {
var node = this.createElementNSPlus("gml:Box");
this.writeNode("coordinates", [
{x: bounds.left, y: bounds.bottom},
{x: bounds.right, y: bounds.top}
], node);
// srsName attribute is optional for gml:Box
if(this.srsName) {
node.setAttribute("srsName", this.srsName);
}
return node;
}
}, OpenLayers.Format.GML.Base.prototype.writers["gml"]),
"feature": OpenLayers.Format.GML.Base.prototype.writers["feature"],
"wfs": OpenLayers.Format.GML.Base.prototype.writers["wfs"]
},
CLASS_NAME: "OpenLayers.Format.GML.v2"
});

View File

@ -1,461 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/GML/Base.js
*/
/**
* Class: OpenLayers.Format.GML.v3
* Parses GML version 3.
*
* Inherits from:
* - <OpenLayers.Format.GML.Base>
*/
OpenLayers.Format.GML.v3 = OpenLayers.Class(OpenLayers.Format.GML.Base, {
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version. The writers
* conform with the Simple Features Profile for GML.
*/
schemaLocation: "http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd",
/**
* Property: curve
* {Boolean} Write gml:Curve instead of gml:LineString elements. This also
* affects the elements in multi-part geometries. Default is false.
* To write gml:Curve elements instead of gml:LineString, set curve
* to true in the options to the contstructor (cannot be changed after
* instantiation).
*/
curve: false,
/**
* Property: multiCurve
* {Boolean} Write gml:MultiCurve instead of gml:MultiLineString. Since
* the latter is deprecated in GML 3, the default is true. To write
* gml:MultiLineString instead of gml:MultiCurve, set multiCurve to
* false in the options to the constructor (cannot be changed after
* instantiation).
*/
multiCurve: true,
/**
* Property: surface
* {Boolean} Write gml:Surface instead of gml:Polygon elements. This also
* affects the elements in multi-part geometries. Default is false.
* To write gml:Surface elements instead of gml:Polygon, set surface
* to true in the options to the contstructor (cannot be changed after
* instantiation).
*/
surface: false,
/**
* Property: multiSurface
* {Boolean} Write gml:multiSurface instead of gml:MultiPolygon. Since
* the latter is deprecated in GML 3, the default is true. To write
* gml:MultiPolygon instead of gml:multiSurface, set multiSurface to
* false in the options to the constructor (cannot be changed after
* instantiation).
*/
multiSurface: true,
/**
* Constructor: OpenLayers.Format.GML.v3
* Create a parser for GML v3.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*
* Valid options properties:
* featureType - {String} Local (without prefix) feature typeName (required).
* featureNS - {String} Feature namespace (required).
* geometryName - {String} Geometry element name.
*/
initialize: function(options) {
OpenLayers.Format.GML.Base.prototype.initialize.apply(this, [options]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"gml": OpenLayers.Util.applyDefaults({
"featureMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"Curve": function(node, container) {
var obj = {points: []};
this.readChildNodes(node, obj);
if(!container.components) {
container.components = [];
}
container.components.push(
new OpenLayers.Geometry.LineString(obj.points)
);
},
"segments": function(node, obj) {
this.readChildNodes(node, obj);
},
"LineStringSegment": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
if(obj.points) {
Array.prototype.push.apply(container.points, obj.points);
}
},
"pos": function(node, obj) {
var str = this.getChildValue(node).replace(
this.regExes.trimSpace, ""
);
var coords = str.split(this.regExes.splitSpace);
var point;
if(this.xy) {
point = new OpenLayers.Geometry.Point(
coords[0], coords[1], coords[2]
);
} else {
point = new OpenLayers.Geometry.Point(
coords[1], coords[0], coords[2]
);
}
obj.points = [point];
},
"posList": function(node, obj) {
var str = this.getChildValue(node).replace(
this.regExes.trimSpace, ""
);
var coords = str.split(this.regExes.splitSpace);
var dim = parseInt(node.getAttribute("dimension")) || 2;
var j, x, y, z;
var numPoints = coords.length / dim;
var points = new Array(numPoints);
for(var i=0, len=coords.length; i<len; i += dim) {
x = coords[i];
y = coords[i+1];
z = (dim == 2) ? undefined : coords[i+2];
if (this.xy) {
points[i/dim] = new OpenLayers.Geometry.Point(x, y, z);
} else {
points[i/dim] = new OpenLayers.Geometry.Point(y, x, z);
}
}
obj.points = points;
},
"Surface": function(node, obj) {
this.readChildNodes(node, obj);
},
"patches": function(node, obj) {
this.readChildNodes(node, obj);
},
"PolygonPatch": function(node, obj) {
this.readers.gml.Polygon.apply(this, [node, obj]);
},
"exterior": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
container.outer = obj.components[0];
},
"interior": function(node, container) {
var obj = {};
this.readChildNodes(node, obj);
container.inner.push(obj.components[0]);
},
"MultiCurve": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
if(obj.components.length > 0) {
container.components = [
new OpenLayers.Geometry.MultiLineString(obj.components)
];
}
},
"curveMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"MultiSurface": function(node, container) {
var obj = {components: []};
this.readChildNodes(node, obj);
if(obj.components.length > 0) {
container.components = [
new OpenLayers.Geometry.MultiPolygon(obj.components)
];
}
},
"surfaceMember": function(node, obj) {
this.readChildNodes(node, obj);
},
"surfaceMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"pointMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"lineStringMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"polygonMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"geometryMembers": function(node, obj) {
this.readChildNodes(node, obj);
},
"Envelope": function(node, container) {
var obj = {points: new Array(2)};
this.readChildNodes(node, obj);
if(!container.components) {
container.components = [];
}
var min = obj.points[0];
var max = obj.points[1];
container.components.push(
new OpenLayers.Bounds(min.x, min.y, max.x, max.y)
);
},
"lowerCorner": function(node, container) {
var obj = {};
this.readers.gml.pos.apply(this, [node, obj]);
container.points[0] = obj.points[0];
},
"upperCorner": function(node, container) {
var obj = {};
this.readers.gml.pos.apply(this, [node, obj]);
container.points[1] = obj.points[0];
}
}, OpenLayers.Format.GML.Base.prototype.readers["gml"]),
"feature": OpenLayers.Format.GML.Base.prototype.readers["feature"],
"wfs": OpenLayers.Format.GML.Base.prototype.readers["wfs"]
},
/**
* Method: write
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>) | OpenLayers.Feature.Vector}
* An array of features or a single feature.
*
* Returns:
* {String} Given an array of features, a doc with a gml:featureMembers
* element will be returned. Given a single feature, a doc with a
* gml:featureMember element will be returned.
*/
write: function(features) {
var name;
if(features instanceof Array) {
name = "featureMembers";
} else {
name = "featureMember";
}
var root = this.writeNode("gml:" + name, features);
this.setAttributeNS(
root, this.namespaces["xsi"],
"xsi:schemaLocation", this.schemaLocation
);
return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"gml": OpenLayers.Util.applyDefaults({
"featureMembers": function(features) {
var node = this.createElementNSPlus("gml:featureMembers");
for(var i=0, len=features.length; i<len; ++i) {
this.writeNode("feature:_typeName", features[i], node);
}
return node;
},
"Point": function(geometry) {
var node = this.createElementNSPlus("gml:Point");
this.writeNode("pos", geometry, node);
return node;
},
"pos": function(point) {
// only 2d for simple features profile
var pos = (this.xy) ?
(point.x + " " + point.y) : (point.y + " " + point.x);
return this.createElementNSPlus("gml:pos", {
value: pos
});
},
"LineString": function(geometry) {
var node = this.createElementNSPlus("gml:LineString");
this.writeNode("posList", geometry.components, node);
return node;
},
"Curve": function(geometry) {
var node = this.createElementNSPlus("gml:Curve");
this.writeNode("segments", geometry, node);
return node;
},
"segments": function(geometry) {
var node = this.createElementNSPlus("gml:segments");
this.writeNode("LineStringSegment", geometry, node);
return node;
},
"LineStringSegment": function(geometry) {
var node = this.createElementNSPlus("gml:LineStringSegment");
this.writeNode("posList", geometry.components, node);
return node;
},
"posList": function(points) {
// only 2d for simple features profile
var len = points.length;
var parts = new Array(len);
var point;
for(var i=0; i<len; ++i) {
point = points[i];
if(this.xy) {
parts[i] = point.x + " " + point.y;
} else {
parts[i] = point.y + " " + point.x;
}
}
return this.createElementNSPlus("gml:posList", {
value: parts.join(" ")
});
},
"Surface": function(geometry) {
var node = this.createElementNSPlus("gml:Surface");
this.writeNode("patches", geometry, node);
return node;
},
"patches": function(geometry) {
var node = this.createElementNSPlus("gml:patches");
this.writeNode("PolygonPatch", geometry, node);
return node;
},
"PolygonPatch": function(geometry) {
var node = this.createElementNSPlus("gml:PolygonPatch", {
attributes: {interpolation: "planar"}
});
this.writeNode("exterior", geometry.components[0], node);
for(var i=1, len=geometry.components.length; i<len; ++i) {
this.writeNode(
"interior", geometry.components[i], node
);
}
return node;
},
"Polygon": function(geometry) {
var node = this.createElementNSPlus("gml:Polygon");
this.writeNode("exterior", geometry.components[0], node);
for(var i=1, len=geometry.components.length; i<len; ++i) {
this.writeNode(
"interior", geometry.components[i], node
);
}
return node;
},
"exterior": function(ring) {
var node = this.createElementNSPlus("gml:exterior");
this.writeNode("LinearRing", ring, node);
return node;
},
"interior": function(ring) {
var node = this.createElementNSPlus("gml:interior");
this.writeNode("LinearRing", ring, node);
return node;
},
"LinearRing": function(ring) {
var node = this.createElementNSPlus("gml:LinearRing");
this.writeNode("posList", ring.components, node);
return node;
},
"MultiCurve": function(geometry) {
var node = this.createElementNSPlus("gml:MultiCurve");
for(var i=0, len=geometry.components.length; i<len; ++i) {
this.writeNode("curveMember", geometry.components[i], node);
}
return node;
},
"curveMember": function(geometry) {
var node = this.createElementNSPlus("gml:curveMember");
if(this.curve) {
this.writeNode("Curve", geometry, node);
} else {
this.writeNode("LineString", geometry, node);
}
return node;
},
"MultiSurface": function(geometry) {
var node = this.createElementNSPlus("gml:MultiSurface");
for(var i=0, len=geometry.components.length; i<len; ++i) {
this.writeNode("surfaceMember", geometry.components[i], node);
}
return node;
},
"surfaceMember": function(polygon) {
var node = this.createElementNSPlus("gml:surfaceMember");
if(this.surface) {
this.writeNode("Surface", polygon, node);
} else {
this.writeNode("Polygon", polygon, node);
}
return node;
},
"Envelope": function(bounds) {
var node = this.createElementNSPlus("gml:Envelope");
this.writeNode("lowerCorner", bounds, node);
this.writeNode("upperCorner", bounds, node);
// srsName attribute is required for gml:Envelope
if(this.srsName) {
node.setAttribute("srsName", this.srsName);
}
return node;
},
"lowerCorner": function(bounds) {
// only 2d for simple features profile
var pos = (this.xy) ?
(bounds.left + " " + bounds.bottom) :
(bounds.bottom + " " + bounds.left);
return this.createElementNSPlus("gml:lowerCorner", {
value: pos
});
},
"upperCorner": function(bounds) {
// only 2d for simple features profile
var pos = (this.xy) ?
(bounds.right + " " + bounds.top) :
(bounds.top + " " + bounds.right);
return this.createElementNSPlus("gml:upperCorner", {
value: pos
});
}
}, OpenLayers.Format.GML.Base.prototype.writers["gml"]),
"feature": OpenLayers.Format.GML.Base.prototype.writers["feature"],
"wfs": OpenLayers.Format.GML.Base.prototype.writers["wfs"]
},
/**
* Function: setGeometryTypes
* Sets the <geometryTypes> mapping.
*/
setGeometryTypes: function() {
this.geometryTypes = {
"OpenLayers.Geometry.Point": "Point",
"OpenLayers.Geometry.MultiPoint": "MultiPoint",
"OpenLayers.Geometry.LineString": (this.curve === true) ? "Curve": "LineString",
"OpenLayers.Geometry.MultiLineString": (this.multiCurve === false) ? "MultiLineString" : "MultiCurve",
"OpenLayers.Geometry.Polygon": (this.surface === true) ? "Surface" : "Polygon",
"OpenLayers.Geometry.MultiPolygon": (this.multiSurface === false) ? "MultiPolygon" : "MultiSurface",
"OpenLayers.Geometry.Collection": "GeometryCollection"
};
},
CLASS_NAME: "OpenLayers.Format.GML.v3"
});

View File

@ -1,179 +0,0 @@
/* Copyright (c) 2006-2007 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/Format/XML.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
* @requires OpenLayers/Geometry/LineString.js
*/
/**
* Class: OpenLayers.Format.GPX
* Read/write GPX parser. Create a new instance with the
* <OpenLayers.Format.GPX> constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.GPX = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: extractWaypoints
* {Boolean} Extract waypoints from GPX. (default: true)
*/
extractWaypoints: true,
/**
* APIProperty: extractTracks
* {Boolean} Extract tracks from GPX. (default: true)
*/
extractTracks: true,
/**
* APIProperty: extractRoutes
* {Boolean} Extract routes from GPX. (default: true)
*/
extractRoutes: true,
/**
* APIProperty: extractAttributes
* {Boolean} Extract feature attributes from GPX. (default: true)
* NOTE: Attributes as part of extensions to the GPX standard may not
* be extracted.
*/
extractAttributes: true,
/**
* Constructor: OpenLayers.Format.GPX
* Create a new parser for GPX.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Return a list of features from a GPX doc
*
* Parameters:
* doc - {Element}
*
* Returns:
* An Array of <OpenLayers.Feature.Vector>s
*/
read: function(doc) {
if (typeof doc == "string") {
doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]);
}
var features = [];
if(this.extractTracks) {
var tracks = doc.getElementsByTagName("trk");
for (var i=0, len=tracks.length; i<len; i++) {
// Attributes are only in trk nodes, not trkseg nodes
var attrs = {};
if(this.extractAttributes) {
attrs = this.parseAttributes(tracks[i]);
}
var segs = this.getElementsByTagNameNS(tracks[i], tracks[i].namespaceURI, "trkseg");
for (var j = 0, seglen = segs.length; j < seglen; j++) {
// We don't yet support extraction of trkpt attributes
// All trksegs of a trk get that trk's attributes
var track = this.extractSegment(segs[j], "trkpt");
features.push(new OpenLayers.Feature.Vector(track, attrs));
}
}
}
if(this.extractRoutes) {
var routes = doc.getElementsByTagName("rte");
for (var k=0, klen=routes.length; k<klen; k++) {
var attrs = {};
if(this.extractAttributes) {
attrs = this.parseAttributes(routes[k]);
}
var route = this.extractSegment(routes[k], "rtept");
features.push(new OpenLayers.Feature.Vector(route, attrs));
}
}
if(this.extractWaypoints) {
var waypoints = doc.getElementsByTagName("wpt");
for (var l = 0, len = waypoints.length; l < len; l++) {
var attrs = {};
if(this.extractAttributes) {
attrs = this.parseAttributes(waypoints[l]);
}
var wpt = new OpenLayers.Geometry.Point(waypoints[l].getAttribute("lon"), waypoints[l].getAttribute("lat"));
features.push(new OpenLayers.Feature.Vector(wpt, attrs));
}
}
if (this.internalProjection && this.externalProjection) {
for (var g = 0, featLength = features.length; g < featLength; g++) {
features[g].geometry.transform(this.externalProjection,
this.internalProjection);
}
}
return features;
},
/**
* Method: extractSegment
*
* Parameters:
* segment - {<DOMElement>} a trkseg or rte node to parse
* segmentType - {String} nodeName of waypoints that form the line
*
* Returns:
* {<OpenLayers.Geometry.LineString>} A linestring geometry
*/
extractSegment: function(segment, segmentType) {
var points = this.getElementsByTagNameNS(segment, segment.namespaceURI, segmentType);
var point_features = [];
for (var i = 0, len = points.length; i < len; i++) {
point_features.push(new OpenLayers.Geometry.Point(points[i].getAttribute("lon"), points[i].getAttribute("lat")));
}
return new OpenLayers.Geometry.LineString(point_features);
},
/**
* Method: parseAttributes
*
* Parameters:
* node - {<DOMElement>}
*
* Returns:
* {Object} An attributes object.
*/
parseAttributes: function(node) {
// node is either a wpt, trk or rte
// attributes are children of the form <attr>value</attr>
var attributes = {};
var attrNode = node.firstChild;
while(attrNode) {
if(attrNode.nodeType == 1) {
var value = attrNode.firstChild;
if(value.nodeType == 3 || value.nodeType == 4) {
name = (attrNode.prefix) ?
attrNode.nodeName.split(":")[1] :
attrNode.nodeName;
if(name != "trkseg" && name != "rtept") {
attributes[name] = value.nodeValue;
}
}
}
attrNode = attrNode.nextSibling;
}
return attributes;
},
CLASS_NAME: "OpenLayers.Format.GPX"
});

View File

@ -1,707 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/JSON.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
* @requires OpenLayers/Geometry/MultiPoint.js
* @requires OpenLayers/Geometry/LineString.js
* @requires OpenLayers/Geometry/MultiLineString.js
* @requires OpenLayers/Geometry/Polygon.js
* @requires OpenLayers/Geometry/MultiPolygon.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Format.GeoJSON
* Read and write GeoJSON. Create a new parser with the
* <OpenLayers.Format.GeoJSON> constructor.
*
* Inherits from:
* - <OpenLayers.Format.JSON>
*/
OpenLayers.Format.GeoJSON = OpenLayers.Class(OpenLayers.Format.JSON, {
/**
* Constructor: OpenLayers.Format.GeoJSON
* Create a new parser for GeoJSON.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.JSON.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Deserialize a GeoJSON string.
*
* Parameters:
* json - {String} A GeoJSON string
* type - {String} Optional string that determines the structure of
* the output. Supported values are "Geometry", "Feature", and
* "FeatureCollection". If absent or null, a default of
* "FeatureCollection" is assumed.
* filter - {Function} A function which will be called for every key and
* value at every level of the final result. Each value will be
* replaced by the result of the filter function. This can be used to
* reform generic objects into instances of classes, or to transform
* date strings into Date objects.
*
* Returns:
* {Object} The return depends on the value of the type argument. If type
* is "FeatureCollection" (the default), the return will be an array
* of <OpenLayers.Feature.Vector>. If type is "Geometry", the input json
* must represent a single geometry, and the return will be an
* <OpenLayers.Geometry>. If type is "Feature", the input json must
* represent a single feature, and the return will be an
* <OpenLayers.Feature.Vector>.
*/
read: function(json, type, filter) {
type = (type) ? type : "FeatureCollection";
var results = null;
var obj = null;
if (typeof json == "string") {
obj = OpenLayers.Format.JSON.prototype.read.apply(this,
[json, filter]);
} else {
obj = json;
}
if(!obj) {
OpenLayers.Console.error("Bad JSON: " + json);
} else if(typeof(obj.type) != "string") {
OpenLayers.Console.error("Bad GeoJSON - no type: " + json);
} else if(this.isValidType(obj, type)) {
switch(type) {
case "Geometry":
try {
results = this.parseGeometry(obj);
} catch(err) {
OpenLayers.Console.error(err);
}
break;
case "Feature":
try {
results = this.parseFeature(obj);
results.type = "Feature";
} catch(err) {
OpenLayers.Console.error(err);
}
break;
case "FeatureCollection":
// for type FeatureCollection, we allow input to be any type
results = [];
switch(obj.type) {
case "Feature":
try {
results.push(this.parseFeature(obj));
} catch(err) {
results = null;
OpenLayers.Console.error(err);
}
break;
case "FeatureCollection":
for(var i=0, len=obj.features.length; i<len; ++i) {
try {
results.push(this.parseFeature(obj.features[i]));
} catch(err) {
results = null;
OpenLayers.Console.error(err);
}
}
break;
default:
try {
var geom = this.parseGeometry(obj);
results.push(new OpenLayers.Feature.Vector(geom));
} catch(err) {
results = null;
OpenLayers.Console.error(err);
}
}
break;
}
}
return results;
},
/**
* Method: isValidType
* Check if a GeoJSON object is a valid representative of the given type.
*
* Returns:
* {Boolean} The object is valid GeoJSON object of the given type.
*/
isValidType: function(obj, type) {
var valid = false;
switch(type) {
case "Geometry":
if(OpenLayers.Util.indexOf(
["Point", "MultiPoint", "LineString", "MultiLineString",
"Polygon", "MultiPolygon", "Box", "GeometryCollection"],
obj.type) == -1) {
// unsupported geometry type
OpenLayers.Console.error("Unsupported geometry type: " +
obj.type);
} else {
valid = true;
}
break;
case "FeatureCollection":
// allow for any type to be converted to a feature collection
valid = true;
break;
default:
// for Feature types must match
if(obj.type == type) {
valid = true;
} else {
OpenLayers.Console.error("Cannot convert types from " +
obj.type + " to " + type);
}
}
return valid;
},
/**
* Method: parseFeature
* Convert a feature object from GeoJSON into an
* <OpenLayers.Feature.Vector>.
*
* Parameters:
* obj - {Object} An object created from a GeoJSON object
*
* Returns:
* {<OpenLayers.Feature.Vector>} A feature.
*/
parseFeature: function(obj) {
var feature, geometry, attributes, bbox;
attributes = (obj.properties) ? obj.properties : {};
bbox = (obj.geometry && obj.geometry.bbox) || obj.bbox;
try {
geometry = this.parseGeometry(obj.geometry);
} catch(err) {
// deal with bad geometries
throw err;
}
feature = new OpenLayers.Feature.Vector(geometry, attributes);
if(bbox) {
feature.bounds = OpenLayers.Bounds.fromArray(bbox);
}
if(obj.id) {
feature.fid = obj.id;
}
return feature;
},
/**
* Method: parseGeometry
* Convert a geometry object from GeoJSON into an <OpenLayers.Geometry>.
*
* Parameters:
* obj - {Object} An object created from a GeoJSON object
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
parseGeometry: function(obj) {
if (obj == null) {
return null;
}
var geometry, collection = false;
if(obj.type == "GeometryCollection") {
if(!(obj.geometries instanceof Array)) {
throw "GeometryCollection must have geometries array: " + obj;
}
var numGeom = obj.geometries.length;
var components = new Array(numGeom);
for(var i=0; i<numGeom; ++i) {
components[i] = this.parseGeometry.apply(
this, [obj.geometries[i]]
);
}
geometry = new OpenLayers.Geometry.Collection(components);
collection = true;
} else {
if(!(obj.coordinates instanceof Array)) {
throw "Geometry must have coordinates array: " + obj;
}
if(!this.parseCoords[obj.type.toLowerCase()]) {
throw "Unsupported geometry type: " + obj.type;
}
try {
geometry = this.parseCoords[obj.type.toLowerCase()].apply(
this, [obj.coordinates]
);
} catch(err) {
// deal with bad coordinates
throw err;
}
}
// We don't reproject collections because the children are reprojected
// for us when they are created.
if (this.internalProjection && this.externalProjection && !collection) {
geometry.transform(this.externalProjection,
this.internalProjection);
}
return geometry;
},
/**
* Property: parseCoords
* Object with properties corresponding to the GeoJSON geometry types.
* Property values are functions that do the actual parsing.
*/
parseCoords: {
/**
* Method: parseCoords.point
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array - {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"point": function(array) {
if(array.length != 2) {
throw "Only 2D points are supported: " + array;
}
return new OpenLayers.Geometry.Point(array[0], array[1]);
},
/**
* Method: parseCoords.multipoint
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"multipoint": function(array) {
var points = [];
var p = null;
for(var i=0, len=array.length; i<len; ++i) {
try {
p = this.parseCoords["point"].apply(this, [array[i]]);
} catch(err) {
throw err;
}
points.push(p);
}
return new OpenLayers.Geometry.MultiPoint(points);
},
/**
* Method: parseCoords.linestring
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array - {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"linestring": function(array) {
var points = [];
var p = null;
for(var i=0, len=array.length; i<len; ++i) {
try {
p = this.parseCoords["point"].apply(this, [array[i]]);
} catch(err) {
throw err;
}
points.push(p);
}
return new OpenLayers.Geometry.LineString(points);
},
/**
* Method: parseCoords.multilinestring
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array - {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"multilinestring": function(array) {
var lines = [];
var l = null;
for(var i=0, len=array.length; i<len; ++i) {
try {
l = this.parseCoords["linestring"].apply(this, [array[i]]);
} catch(err) {
throw err;
}
lines.push(l);
}
return new OpenLayers.Geometry.MultiLineString(lines);
},
/**
* Method: parseCoords.polygon
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"polygon": function(array) {
var rings = [];
var r, l;
for(var i=0, len=array.length; i<len; ++i) {
try {
l = this.parseCoords["linestring"].apply(this, [array[i]]);
} catch(err) {
throw err;
}
r = new OpenLayers.Geometry.LinearRing(l.components);
rings.push(r);
}
return new OpenLayers.Geometry.Polygon(rings);
},
/**
* Method: parseCoords.multipolygon
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array - {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"multipolygon": function(array) {
var polys = [];
var p = null;
for(var i=0, len=array.length; i<len; ++i) {
try {
p = this.parseCoords["polygon"].apply(this, [array[i]]);
} catch(err) {
throw err;
}
polys.push(p);
}
return new OpenLayers.Geometry.MultiPolygon(polys);
},
/**
* Method: parseCoords.box
* Convert a coordinate array from GeoJSON into an
* <OpenLayers.Geometry>.
*
* Parameters:
* array - {Object} The coordinates array from the GeoJSON fragment.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry.
*/
"box": function(array) {
if(array.length != 2) {
throw "GeoJSON box coordinates must have 2 elements";
}
return new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(array[0][0], array[0][1]),
new OpenLayers.Geometry.Point(array[1][0], array[0][1]),
new OpenLayers.Geometry.Point(array[1][0], array[1][1]),
new OpenLayers.Geometry.Point(array[0][0], array[1][1]),
new OpenLayers.Geometry.Point(array[0][0], array[0][1])
])
]);
}
},
/**
* APIMethod: write
* Serialize a feature, geometry, array of features into a GeoJSON string.
*
* Parameters:
* obj - {Object} An <OpenLayers.Feature.Vector>, <OpenLayers.Geometry>,
* or an array of features.
* pretty - {Boolean} Structure the output with newlines and indentation.
* Default is false.
*
* Returns:
* {String} The GeoJSON string representation of the input geometry,
* features, or array of features.
*/
write: function(obj, pretty) {
var geojson = {
"type": null
};
if(obj instanceof Array) {
geojson.type = "FeatureCollection";
var numFeatures = obj.length;
geojson.features = new Array(numFeatures);
for(var i=0; i<numFeatures; ++i) {
var element = obj[i];
if(!element instanceof OpenLayers.Feature.Vector) {
var msg = "FeatureCollection only supports collections " +
"of features: " + element;
throw msg;
}
geojson.features[i] = this.extract.feature.apply(
this, [element]
);
}
} else if (obj.CLASS_NAME.indexOf("OpenLayers.Geometry") == 0) {
geojson = this.extract.geometry.apply(this, [obj]);
} else if (obj instanceof OpenLayers.Feature.Vector) {
geojson = this.extract.feature.apply(this, [obj]);
if(obj.layer && obj.layer.projection) {
geojson.crs = this.createCRSObject(obj);
}
}
return OpenLayers.Format.JSON.prototype.write.apply(this,
[geojson, pretty]);
},
/**
* Method: createCRSObject
* Create the CRS object for an object.
*
* Parameters:
* object - {<OpenLayers.Feature.Vector>}
*
* Returns:
* {Object} An object which can be assigned to the crs property
* of a GeoJSON object.
*/
createCRSObject: function(object) {
var proj = object.layer.projection.toString();
var crs = {};
if (proj.match(/epsg:/i)) {
var code = parseInt(proj.substring(proj.indexOf(":") + 1));
if (code == 4326) {
crs = {
"type": "OGC",
"properties": {
"urn": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
};
} else {
crs = {
"type": "EPSG",
"properties": {
"code": code
}
};
}
}
return crs;
},
/**
* Property: extract
* Object with properties corresponding to the GeoJSON types.
* Property values are functions that do the actual value extraction.
*/
extract: {
/**
* Method: extract.feature
* Return a partial GeoJSON object representing a single feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*
* Returns:
* {Object} An object representing the point.
*/
'feature': function(feature) {
var geom = this.extract.geometry.apply(this, [feature.geometry]);
return {
"type": "Feature",
"id": feature.fid == null ? feature.id : feature.fid,
"properties": feature.attributes,
"geometry": geom
};
},
/**
* Method: extract.geometry
* Return a GeoJSON object representing a single geometry.
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {Object} An object representing the geometry.
*/
'geometry': function(geometry) {
if (geometry == null) {
return null;
}
if (this.internalProjection && this.externalProjection) {
geometry = geometry.clone();
geometry.transform(this.internalProjection,
this.externalProjection);
}
var geometryType = geometry.CLASS_NAME.split('.')[2];
var data = this.extract[geometryType.toLowerCase()].apply(this, [geometry]);
var json;
if(geometryType == "Collection") {
json = {
"type": "GeometryCollection",
"geometries": data
};
} else {
json = {
"type": geometryType,
"coordinates": data
};
}
return json;
},
/**
* Method: extract.point
* Return an array of coordinates from a point.
*
* Parameters:
* point - {<OpenLayers.Geometry.Point>}
*
* Returns:
* {Array} An array of coordinates representing the point.
*/
'point': function(point) {
return [point.x, point.y];
},
/**
* Method: extract.multipoint
* Return an array of point coordinates from a multipoint.
*
* Parameters:
* multipoint - {<OpenLayers.Geometry.MultiPoint>}
*
* Returns:
* {Array} An array of point coordinate arrays representing
* the multipoint.
*/
'multipoint': function(multipoint) {
var array = [];
for(var i=0, len=multipoint.components.length; i<len; ++i) {
array.push(this.extract.point.apply(this, [multipoint.components[i]]));
}
return array;
},
/**
* Method: extract.linestring
* Return an array of coordinate arrays from a linestring.
*
* Parameters:
* linestring - {<OpenLayers.Geometry.LineString>}
*
* Returns:
* {Array} An array of coordinate arrays representing
* the linestring.
*/
'linestring': function(linestring) {
var array = [];
for(var i=0, len=linestring.components.length; i<len; ++i) {
array.push(this.extract.point.apply(this, [linestring.components[i]]));
}
return array;
},
/**
* Method: extract.multilinestring
* Return an array of linestring arrays from a linestring.
*
* Parameters:
* linestring - {<OpenLayers.Geometry.MultiLineString>}
*
* Returns:
* {Array} An array of linestring arrays representing
* the multilinestring.
*/
'multilinestring': function(multilinestring) {
var array = [];
for(var i=0, len=multilinestring.components.length; i<len; ++i) {
array.push(this.extract.linestring.apply(this, [multilinestring.components[i]]));
}
return array;
},
/**
* Method: extract.polygon
* Return an array of linear ring arrays from a polygon.
*
* Parameters:
* polygon - {<OpenLayers.Geometry.Polygon>}
*
* Returns:
* {Array} An array of linear ring arrays representing the polygon.
*/
'polygon': function(polygon) {
var array = [];
for(var i=0, len=polygon.components.length; i<len; ++i) {
array.push(this.extract.linestring.apply(this, [polygon.components[i]]));
}
return array;
},
/**
* Method: extract.multipolygon
* Return an array of polygon arrays from a multipolygon.
*
* Parameters:
* multipolygon - {<OpenLayers.Geometry.MultiPolygon>}
*
* Returns:
* {Array} An array of polygon arrays representing
* the multipolygon
*/
'multipolygon': function(multipolygon) {
var array = [];
for(var i=0, len=multipolygon.components.length; i<len; ++i) {
array.push(this.extract.polygon.apply(this, [multipolygon.components[i]]));
}
return array;
},
/**
* Method: extract.collection
* Return an array of geometries from a geometry collection.
*
* Parameters:
* collection - {<OpenLayers.Geometry.Collection>}
*
* Returns:
* {Array} An array of geometry objects representing the geometry
* collection.
*/
'collection': function(collection) {
var len = collection.components.length;
var array = new Array(len);
for(var i=0; i<len; ++i) {
array[i] = this.extract.geometry.apply(
this, [collection.components[i]]
);
}
return array;
}
},
CLASS_NAME: "OpenLayers.Format.GeoJSON"
});

View File

@ -1,419 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
* @requires OpenLayers/Geometry/LineString.js
* @requires OpenLayers/Geometry/Polygon.js
*/
/**
* Class: OpenLayers.Format.GeoRSS
* Read/write GeoRSS parser. Create a new instance with the
* <OpenLayers.Format.GeoRSS> constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.GeoRSS = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: rssns
* {String} RSS namespace to use. Defaults to
* "http://backend.userland.com/rss2"
*/
rssns: "http://backend.userland.com/rss2",
/**
* APIProperty: featurens
* {String} Feature Attributes namespace. Defaults to
* "http://mapserver.gis.umn.edu/mapserver"
*/
featureNS: "http://mapserver.gis.umn.edu/mapserver",
/**
* APIProperty: georssns
* {String} GeoRSS namespace to use. Defaults to
* "http://www.georss.org/georss"
*/
georssns: "http://www.georss.org/georss",
/**
* APIProperty: geons
* {String} W3C Geo namespace to use. Defaults to
* "http://www.w3.org/2003/01/geo/wgs84_pos#"
*/
geons: "http://www.w3.org/2003/01/geo/wgs84_pos#",
/**
* APIProperty: featureTitle
* {String} Default title for features. Defaults to "Untitled"
*/
featureTitle: "Untitled",
/**
* APIProperty: featureDescription
* {String} Default description for features. Defaults to "No Description"
*/
featureDescription: "No Description",
/**
* Property: gmlParse
* {Object} GML Format object for parsing features
* Non-API and only created if necessary
*/
gmlParser: null,
/**
* APIProperty: xy
* {Boolean} Order of the GML coordinate: true:(x,y) or false:(y,x)
* For GeoRSS the default is (y,x), therefore: false
*/
xy: false,
/**
* Constructor: OpenLayers.Format.GeoRSS
* Create a new parser for GeoRSS.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* Method: createGeometryFromItem
* Return a geometry from a GeoRSS Item.
*
* Parameters:
* item - {DOMElement} A GeoRSS item node.
*
* Returns:
* {<OpenLayers.Geometry>} A geometry representing the node.
*/
createGeometryFromItem: function(item) {
var point = this.getElementsByTagNameNS(item, this.georssns, "point");
var lat = this.getElementsByTagNameNS(item, this.geons, 'lat');
var lon = this.getElementsByTagNameNS(item, this.geons, 'long');
var line = this.getElementsByTagNameNS(item,
this.georssns,
"line");
var polygon = this.getElementsByTagNameNS(item,
this.georssns,
"polygon");
var where = this.getElementsByTagNameNS(item,
this.georssns,
"where");
var box = this.getElementsByTagNameNS(item,
this.georssns,
"box");
if (point.length > 0 || (lat.length > 0 && lon.length > 0)) {
var location;
if (point.length > 0) {
location = OpenLayers.String.trim(
point[0].firstChild.nodeValue).split(/\s+/);
if (location.length !=2) {
location = OpenLayers.String.trim(
point[0].firstChild.nodeValue).split(/\s*,\s*/);
}
} else {
location = [parseFloat(lat[0].firstChild.nodeValue),
parseFloat(lon[0].firstChild.nodeValue)];
}
var geometry = new OpenLayers.Geometry.Point(parseFloat(location[1]),
parseFloat(location[0]));
} else if (line.length > 0) {
var coords = OpenLayers.String.trim(this.concatChildValues(line[0])).split(/\s+/);
var components = [];
var point;
for (var i=0, len=coords.length; i<len; i+=2) {
point = new OpenLayers.Geometry.Point(parseFloat(coords[i+1]),
parseFloat(coords[i]));
components.push(point);
}
geometry = new OpenLayers.Geometry.LineString(components);
} else if (polygon.length > 0) {
var coords = OpenLayers.String.trim(this.concatChildValues(polygon[0])).split(/\s+/);
var components = [];
var point;
for (var i=0, len=coords.length; i<len; i+=2) {
point = new OpenLayers.Geometry.Point(parseFloat(coords[i+1]),
parseFloat(coords[i]));
components.push(point);
}
geometry = new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(components)]);
} else if (where.length > 0) {
if (!this.gmlParser) {
this.gmlParser = new OpenLayers.Format.GML({'xy': this.xy});
}
var feature = this.gmlParser.parseFeature(where[0]);
geometry = feature.geometry;
} else if (box.length > 0) {
var coords = OpenLayers.String.trim(box[0].firstChild.nodeValue).split(/\s+/);
var components = [];
var point;
if (coords.length > 3) {
point = new OpenLayers.Geometry.Point(parseFloat(coords[1]),
parseFloat(coords[0]));
components.push(point);
point = new OpenLayers.Geometry.Point(parseFloat(coords[1]),
parseFloat(coords[2]));
components.push(point);
point = new OpenLayers.Geometry.Point(parseFloat(coords[3]),
parseFloat(coords[2]));
components.push(point);
point = new OpenLayers.Geometry.Point(parseFloat(coords[3]),
parseFloat(coords[0]));
components.push(point);
point = new OpenLayers.Geometry.Point(parseFloat(coords[1]),
parseFloat(coords[0]));
components.push(point);
}
geometry = new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(components)]);
}
if (geometry && this.internalProjection && this.externalProjection) {
geometry.transform(this.externalProjection,
this.internalProjection);
}
return geometry;
},
/**
* Method: createFeatureFromItem
* Return a feature from a GeoRSS Item.
*
* Parameters:
* item - {DOMElement} A GeoRSS item node.
*
* Returns:
* {<OpenLayers.Feature.Vector>} A feature representing the item.
*/
createFeatureFromItem: function(item) {
var geometry = this.createGeometryFromItem(item);
/* Provide defaults for title and description */
var title = this.getChildValue(item, "*", "title", this.featureTitle);
/* First try RSS descriptions, then Atom summaries */
var description = this.getChildValue(
item, "*", "description",
this.getChildValue(item, "*", "content",
this.getChildValue(item, "*", "summary", this.featureDescription)));
/* If no link URL is found in the first child node, try the
href attribute */
var link = this.getChildValue(item, "*", "link");
if(!link) {
try {
link = this.getElementsByTagNameNS(item, "*", "link")[0].getAttribute("href");
} catch(e) {
link = null;
}
}
var id = this.getChildValue(item, "*", "id", null);
var data = {
"title": title,
"description": description,
"link": link
};
var feature = new OpenLayers.Feature.Vector(geometry, data);
feature.fid = id;
return feature;
},
/**
* Method: getChildValue
*
* Parameters:
* node - {DOMElement}
* nsuri - {String} Child node namespace uri ("*" for any).
* name - {String} Child node name.
* def - {String} Optional string default to return if no child found.
*
* Returns:
* {String} The value of the first child with the given tag name. Returns
* default value or empty string if none found.
*/
getChildValue: function(node, nsuri, name, def) {
var value;
var eles = this.getElementsByTagNameNS(node, nsuri, name);
if(eles && eles[0] && eles[0].firstChild
&& eles[0].firstChild.nodeValue) {
value = eles[0].firstChild.nodeValue;
} else {
value = (def == undefined) ? "" : def;
}
return value;
},
/**
* APIMethod: read
* Return a list of features from a GeoRSS doc
* Parameters:
* data - {Element}
*
* Returns:
* An Array of <OpenLayers.Feature.Vector>s
*/
read: function(doc) {
if (typeof doc == "string") {
doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]);
}
/* Try RSS items first, then Atom entries */
var itemlist = null;
itemlist = this.getElementsByTagNameNS(doc, '*', 'item');
if (itemlist.length == 0) {
itemlist = this.getElementsByTagNameNS(doc, '*', 'entry');
}
var numItems = itemlist.length;
var features = new Array(numItems);
for(var i=0; i<numItems; i++) {
features[i] = this.createFeatureFromItem(itemlist[i]);
}
return features;
},
/**
* APIMethod: write
* Accept Feature Collection, and return a string.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)} List of features to serialize into a string.
*/
write: function(features) {
var georss;
if(features instanceof Array) {
georss = this.createElementNS(this.rssns, "rss");
for(var i=0, len=features.length; i<len; i++) {
georss.appendChild(this.createFeatureXML(features[i]));
}
} else {
georss = this.createFeatureXML(features);
}
return OpenLayers.Format.XML.prototype.write.apply(this, [georss]);
},
/**
* Method: createFeatureXML
* Accept an <OpenLayers.Feature.Vector>, and build a geometry for it.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*
* Returns:
* {DOMElement}
*/
createFeatureXML: function(feature) {
var geometryNode = this.buildGeometryNode(feature.geometry);
var featureNode = this.createElementNS(this.rssns, "item");
var titleNode = this.createElementNS(this.rssns, "title");
titleNode.appendChild(this.createTextNode(feature.attributes.title ? feature.attributes.title : ""));
var descNode = this.createElementNS(this.rssns, "description");
descNode.appendChild(this.createTextNode(feature.attributes.description ? feature.attributes.description : ""));
featureNode.appendChild(titleNode);
featureNode.appendChild(descNode);
if (feature.attributes.link) {
var linkNode = this.createElementNS(this.rssns, "link");
linkNode.appendChild(this.createTextNode(feature.attributes.link));
featureNode.appendChild(linkNode);
}
for(var attr in feature.attributes) {
if (attr == "link" || attr == "title" || attr == "description") { continue; }
var attrText = this.createTextNode(feature.attributes[attr]);
var nodename = attr;
if (attr.search(":") != -1) {
nodename = attr.split(":")[1];
}
var attrContainer = this.createElementNS(this.featureNS, "feature:"+nodename);
attrContainer.appendChild(attrText);
featureNode.appendChild(attrContainer);
}
featureNode.appendChild(geometryNode);
return featureNode;
},
/**
* Method: buildGeometryNode
* builds a GeoRSS node with a given geometry
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement} A gml node.
*/
buildGeometryNode: function(geometry) {
if (this.internalProjection && this.externalProjection) {
geometry = geometry.clone();
geometry.transform(this.internalProjection,
this.externalProjection);
}
var node;
// match Polygon
if (geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") {
node = this.createElementNS(this.georssns, 'georss:polygon');
node.appendChild(this.buildCoordinatesNode(geometry.components[0]));
}
// match LineString
else if (geometry.CLASS_NAME == "OpenLayers.Geometry.LineString") {
node = this.createElementNS(this.georssns, 'georss:line');
node.appendChild(this.buildCoordinatesNode(geometry));
}
// match Point
else if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
node = this.createElementNS(this.georssns, 'georss:point');
node.appendChild(this.buildCoordinatesNode(geometry));
} else {
throw "Couldn't parse " + geometry.CLASS_NAME;
}
return node;
},
/**
* Method: buildCoordinatesNode
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
*/
buildCoordinatesNode: function(geometry) {
var points = null;
if (geometry.components) {
points = geometry.components;
}
var path;
if (points) {
var numPoints = points.length;
var parts = new Array(numPoints);
for (var i = 0; i < numPoints; i++) {
parts[i] = points[i].y + " " + points[i].x;
}
path = parts.join(" ");
} else {
path = geometry.y + " " + geometry.x;
}
return this.createTextNode(path);
},
CLASS_NAME: "OpenLayers.Format.GeoRSS"
});

View File

@ -1,388 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Note:
* This work draws heavily from the public domain JSON serializer/deserializer
* at http://www.json.org/json.js. Rewritten so that it doesn't modify
* basic data prototypes.
*/
/**
* @requires OpenLayers/Format.js
*/
/**
* Class: OpenLayers.Format.JSON
* A parser to read/write JSON safely. Create a new instance with the
* <OpenLayers.Format.JSON> constructor.
*
* Inherits from:
* - <OpenLayers.Format>
*/
OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, {
/**
* APIProperty: indent
* {String} For "pretty" printing, the indent string will be used once for
* each indentation level.
*/
indent: " ",
/**
* APIProperty: space
* {String} For "pretty" printing, the space string will be used after
* the ":" separating a name/value pair.
*/
space: " ",
/**
* APIProperty: newline
* {String} For "pretty" printing, the newline string will be used at the
* end of each name/value pair or array item.
*/
newline: "\n",
/**
* Property: level
* {Integer} For "pretty" printing, this is incremented/decremented during
* serialization.
*/
level: 0,
/**
* Property: pretty
* {Boolean} Serialize with extra whitespace for structure. This is set
* by the <write> method.
*/
pretty: false,
/**
* Constructor: OpenLayers.Format.JSON
* Create a new parser for JSON.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Deserialize a json string.
*
* Parameters:
* json - {String} A JSON string
* filter - {Function} A function which will be called for every key and
* value at every level of the final result. Each value will be
* replaced by the result of the filter function. This can be used to
* reform generic objects into instances of classes, or to transform
* date strings into Date objects.
*
* Returns:
* {Object} An object, array, string, or number .
*/
read: function(json, filter) {
/**
* Parsing happens in three stages. In the first stage, we run the text
* against a regular expression which looks for non-JSON
* characters. We are especially concerned with '()' and 'new'
* because they can cause invocation, and '=' because it can cause
* mutation. But just to be safe, we will reject all unexpected
* characters.
*/
try {
if (/^[\],:{}\s]*$/.test(json.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
/**
* In the second stage we use the eval function to compile the
* text into a JavaScript structure. The '{' operator is
* subject to a syntactic ambiguity in JavaScript - it can
* begin a block or an object literal. We wrap the text in
* parens to eliminate the ambiguity.
*/
var object = eval('(' + json + ')');
/**
* In the optional third stage, we recursively walk the new
* structure, passing each name/value pair to a filter
* function for possible transformation.
*/
if(typeof filter === 'function') {
function walk(k, v) {
if(v && typeof v === 'object') {
for(var i in v) {
if(v.hasOwnProperty(i)) {
v[i] = walk(i, v[i]);
}
}
}
return filter(k, v);
}
object = walk('', object);
}
if(this.keepData) {
this.data = object;
}
return object;
}
} catch(e) {
// Fall through if the regexp test fails.
}
return null;
},
/**
* APIMethod: write
* Serialize an object into a JSON string.
*
* Parameters:
* value - {String} The object, array, string, number, boolean or date
* to be serialized.
* pretty - {Boolean} Structure the output with newlines and indentation.
* Default is false.
*
* Returns:
* {String} The JSON string representation of the input value.
*/
write: function(value, pretty) {
this.pretty = !!pretty;
var json = null;
var type = typeof value;
if(this.serialize[type]) {
try {
json = this.serialize[type].apply(this, [value]);
} catch(err) {
OpenLayers.Console.error("Trouble serializing: " + err);
}
}
return json;
},
/**
* Method: writeIndent
* Output an indentation string depending on the indentation level.
*
* Returns:
* {String} An appropriate indentation string.
*/
writeIndent: function() {
var pieces = [];
if(this.pretty) {
for(var i=0; i<this.level; ++i) {
pieces.push(this.indent);
}
}
return pieces.join('');
},
/**
* Method: writeNewline
* Output a string representing a newline if in pretty printing mode.
*
* Returns:
* {String} A string representing a new line.
*/
writeNewline: function() {
return (this.pretty) ? this.newline : '';
},
/**
* Method: writeSpace
* Output a string representing a space if in pretty printing mode.
*
* Returns:
* {String} A space.
*/
writeSpace: function() {
return (this.pretty) ? this.space : '';
},
/**
* Property: serialize
* Object with properties corresponding to the serializable data types.
* Property values are functions that do the actual serializing.
*/
serialize: {
/**
* Method: serialize.object
* Transform an object into a JSON string.
*
* Parameters:
* object - {Object} The object to be serialized.
*
* Returns:
* {String} A JSON string representing the object.
*/
'object': function(object) {
// three special objects that we want to treat differently
if(object == null) {
return "null";
}
if(object.constructor == Date) {
return this.serialize.date.apply(this, [object]);
}
if(object.constructor == Array) {
return this.serialize.array.apply(this, [object]);
}
var pieces = ['{'];
this.level += 1;
var key, keyJSON, valueJSON;
var addComma = false;
for(key in object) {
if(object.hasOwnProperty(key)) {
// recursive calls need to allow for sub-classing
keyJSON = OpenLayers.Format.JSON.prototype.write.apply(this,
[key, this.pretty]);
valueJSON = OpenLayers.Format.JSON.prototype.write.apply(this,
[object[key], this.pretty]);
if(keyJSON != null && valueJSON != null) {
if(addComma) {
pieces.push(',');
}
pieces.push(this.writeNewline(), this.writeIndent(),
keyJSON, ':', this.writeSpace(), valueJSON);
addComma = true;
}
}
}
this.level -= 1;
pieces.push(this.writeNewline(), this.writeIndent(), '}');
return pieces.join('');
},
/**
* Method: serialize.array
* Transform an array into a JSON string.
*
* Parameters:
* array - {Array} The array to be serialized
*
* Returns:
* {String} A JSON string representing the array.
*/
'array': function(array) {
var json;
var pieces = ['['];
this.level += 1;
for(var i=0, len=array.length; i<len; ++i) {
// recursive calls need to allow for sub-classing
json = OpenLayers.Format.JSON.prototype.write.apply(this,
[array[i], this.pretty]);
if(json != null) {
if(i > 0) {
pieces.push(',');
}
pieces.push(this.writeNewline(), this.writeIndent(), json);
}
}
this.level -= 1;
pieces.push(this.writeNewline(), this.writeIndent(), ']');
return pieces.join('');
},
/**
* Method: serialize.string
* Transform a string into a JSON string.
*
* Parameters:
* string - {String} The string to be serialized
*
* Returns:
* {String} A JSON string representing the string.
*/
'string': function(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
if(/["\\\x00-\x1f]/.test(string)) {
return '"' + string.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
},
/**
* Method: serialize.number
* Transform a number into a JSON string.
*
* Parameters:
* number - {Number} The number to be serialized.
*
* Returns:
* {String} A JSON string representing the number.
*/
'number': function(number) {
return isFinite(number) ? String(number) : "null";
},
/**
* Method: serialize.boolean
* Transform a boolean into a JSON string.
*
* Parameters:
* bool - {Boolean} The boolean to be serialized.
*
* Returns:
* {String} A JSON string representing the boolean.
*/
'boolean': function(bool) {
return String(bool);
},
/**
* Method: serialize.object
* Transform a date into a JSON string.
*
* Parameters:
* date - {Date} The date to be serialized.
*
* Returns:
* {String} A JSON string representing the date.
*/
'date': function(date) {
function format(number) {
// Format integers to have at least two digits.
return (number < 10) ? '0' + number : number;
}
return '"' + date.getFullYear() + '-' +
format(date.getMonth() + 1) + '-' +
format(date.getDate()) + 'T' +
format(date.getHours()) + ':' +
format(date.getMinutes()) + ':' +
format(date.getSeconds()) + '"';
}
},
CLASS_NAME: "OpenLayers.Format.JSON"
});

View File

@ -1,452 +0,0 @@
/* Copyright (c) 2006-2007 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/Format/XML.js
* @requires OpenLayers/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
* @requires OpenLayers/Geometry/LineString.js
* @requires OpenLayers/Geometry/Polygon.js
*/
/**
* Class: OpenLayers.Format.OSM
* OSM parser. Create a new instance with the
* <OpenLayers.Format.OSM> constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.OSM = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: checkTags
* {Boolean} Should tags be checked to determine whether something
* should be treated as a seperate node. Will slow down parsing.
* Default is false.
*/
checkTags: false,
/**
* Property: interestingTagsExclude
* {Array} List of tags to exclude from 'interesting' checks on nodes.
* Must be set when creating the format. Will only be used if checkTags
* is set.
*/
interestingTagsExclude: null,
/**
* APIProperty: areaTags
* {Array} List of tags indicating that something is an area.
* Must be set when creating the format. Will only be used if
* checkTags is true.
*/
areaTags: null,
/**
* Constructor: OpenLayers.Format.OSM
* Create a new parser for OSM.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
var layer_defaults = {
'interestingTagsExclude': ['source', 'source_ref',
'source:ref', 'history', 'attribution', 'created_by'],
'areaTags': ['area', 'building', 'leisure', 'tourism', 'ruins',
'historic', 'landuse', 'military', 'natural', 'sport']
};
layer_defaults = OpenLayers.Util.extend(layer_defaults, options);
var interesting = {};
for (var i = 0; i < layer_defaults.interestingTagsExclude.length; i++) {
interesting[layer_defaults.interestingTagsExclude[i]] = true;
}
layer_defaults.interestingTagsExclude = interesting;
var area = {};
for (var i = 0; i < layer_defaults.areaTags.length; i++) {
area[layer_defaults.areaTags[i]] = true;
}
layer_defaults.areaTags = area;
OpenLayers.Format.XML.prototype.initialize.apply(this, [layer_defaults]);
},
/**
* APIMethod: read
* Return a list of features from a OSM doc
* Parameters:
* data - {Element}
*
* Returns:
* An Array of <OpenLayers.Feature.Vector>s
*/
read: function(doc) {
if (typeof doc == "string") {
doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]);
}
var nodes = this.getNodes(doc);
var ways = this.getWays(doc);
// Geoms will contain at least ways.length entries.
var feat_list = new Array(ways.length);
for (var i = 0; i < ways.length; i++) {
// We know the minimal of this one ahead of time. (Could be -1
// due to areas/polygons)
var point_list = new Array(ways[i].nodes.length);
var poly = this.isWayArea(ways[i]) ? 1 : 0;
for (var j = 0; j < ways[i].nodes.length; j++) {
var node = nodes[ways[i].nodes[j]];
var point = new OpenLayers.Geometry.Point(node.lon, node.lat);
// Since OSM is topological, we stash the node ID internally.
point.osm_id = parseInt(ways[i].nodes[j]);
point_list[j] = point;
// We don't display nodes if they're used inside other
// elements.
node.used = true;
}
var geometry = null;
if (poly) {
geometry = new OpenLayers.Geometry.Polygon(
new OpenLayers.Geometry.LinearRing(point_list));
} else {
geometry = new OpenLayers.Geometry.LineString(point_list);
}
if (this.internalProjection && this.externalProjection) {
geometry.transform(this.externalProjection,
this.internalProjection);
}
var feat = new OpenLayers.Feature.Vector(geometry,
ways[i].tags);
feat.osm_id = parseInt(ways[i].id);
feat.fid = "way." + feat.osm_id;
feat_list[i] = feat;
}
for (var node_id in nodes) {
var node = nodes[node_id];
if (!node.used || this.checkTags) {
var tags = null;
if (this.checkTags) {
var result = this.getTags(node.node, true);
if (node.used && !result[1]) {
continue;
}
tags = result[0];
} else {
tags = this.getTags(node.node);
}
var feat = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(node['lon'], node['lat']),
tags);
if (this.internalProjection && this.externalProjection) {
feat.geometry.transform(this.externalProjection,
this.internalProjection);
}
feat.osm_id = parseInt(node_id);
feat.fid = "node." + feat.osm_id;
feat_list.push(feat);
}
// Memory cleanup
node.node = null;
}
return feat_list;
},
/**
* Method: getNodes
* Return the node items from a doc.
*
* Parameters:
* node - {DOMElement} node to parse tags from
*/
getNodes: function(doc) {
var node_list = doc.getElementsByTagName("node");
var nodes = {};
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
var id = node.getAttribute("id");
nodes[id] = {
'lat': node.getAttribute("lat"),
'lon': node.getAttribute("lon"),
'node': node
};
}
return nodes;
},
/**
* Method: getWays
* Return the way items from a doc.
*
* Parameters:
* node - {DOMElement} node to parse tags from
*/
getWays: function(doc) {
var way_list = doc.getElementsByTagName("way");
var return_ways = [];
for (var i = 0; i < way_list.length; i++) {
var way = way_list[i];
var way_object = {
id: way.getAttribute("id")
};
way_object.tags = this.getTags(way);
var node_list = way.getElementsByTagName("nd");
way_object.nodes = new Array(node_list.length);
for (var j = 0; j < node_list.length; j++) {
way_object.nodes[j] = node_list[j].getAttribute("ref");
}
return_ways.push(way_object);
}
return return_ways;
},
/**
* Method: getTags
* Return the tags list attached to a specific DOM element.
*
* Parameters:
* node - {DOMElement} node to parse tags from
* interesting_tags - {Boolean} whether the return from this function should
* return a boolean indicating that it has 'interesting tags' --
* tags like attribution and source are ignored. (To change the list
* of tags, see interestingTagsExclude)
*
* Returns:
* tags - {Object} hash of tags
* interesting - {Boolean} if interesting_tags is passed, returns
* whether there are any interesting tags on this element.
*/
getTags: function(dom_node, interesting_tags) {
var tag_list = dom_node.getElementsByTagName("tag");
var tags = {};
var interesting = false;
for (var j = 0; j < tag_list.length; j++) {
var key = tag_list[j].getAttribute("k");
tags[key] = tag_list[j].getAttribute("v");
if (interesting_tags) {
if (!this.interestingTagsExclude[key]) {
interesting = true;
}
}
}
return interesting_tags ? [tags, interesting] : tags;
},
/**
* Method: isWayArea
* Given a way object from getWays, check whether the tags and geometry
* indicate something is an area.
*
* Returns:
* {Boolean}
*/
isWayArea: function(way) {
var poly_shaped = false;
var poly_tags = false;
if (way.nodes[0] == way.nodes[way.nodes.length - 1]) {
poly_shaped = true;
}
if (this.checkTags) {
for(var key in way.tags) {
if (this.areaTags[key]) {
poly_tags = true;
break;
}
}
}
return poly_shaped && (this.checkTags ? poly_tags : true);
},
/**
* APIMethod: write
* Takes a list of features, returns a serialized OSM format file for use
* in tools like JOSM.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)}
*/
write: function(features) {
if (!(features instanceof Array)) {
features = [features];
}
this.osm_id = 1;
this.created_nodes = {};
var root_node = this.createElementNS(null, "osm");
root_node.setAttribute("version", "0.5");
root_node.setAttribute("generator", "OpenLayers "+ OpenLayers.VERSION_NUMBER);
// Loop backwards, because the deserializer puts nodes last, and
// we want them first if possible
for(var i = features.length - 1; i >= 0; i--) {
var nodes = this.createFeatureNodes(features[i]);
for (var j = 0; j < nodes.length; j++) {
root_node.appendChild(nodes[j]);
}
}
return OpenLayers.Format.XML.prototype.write.apply(this, [root_node]);
},
/**
* Method: createFeatureNodes
* Takes a feature, returns a list of nodes from size 0->n.
* Will include all pieces of the serialization that are required which
* have not already been created. Calls out to createXML based on geometry
* type.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
createFeatureNodes: function(feature) {
var nodes = [];
var className = feature.geometry.CLASS_NAME;
var type = className.substring(className.lastIndexOf(".") + 1);
type = type.toLowerCase();
var builder = this.createXML[type];
if (builder) {
nodes = builder.apply(this, [feature]);
}
return nodes;
},
/**
* Method: createXML
* Takes a feature, returns a list of nodes from size 0->n.
* Will include all pieces of the serialization that are required which
* have not already been created.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
createXML: {
'point': function(point) {
var id = null;
var geometry = point.geometry ? point.geometry : point;
var already_exists = false; // We don't return anything if the node
// has already been created
if (point.osm_id) {
id = point.osm_id;
if (this.created_nodes[id]) {
already_exists = true;
}
} else {
id = -this.osm_id;
this.osm_id++;
}
if (already_exists) {
node = this.created_nodes[id];
} else {
var node = this.createElementNS(null, "node");
}
this.created_nodes[id] = node;
node.setAttribute("id", id);
node.setAttribute("lon", geometry.x);
node.setAttribute("lat", geometry.y);
if (point.attributes) {
this.serializeTags(point, node);
}
this.setState(point, node);
return already_exists ? [] : [node];
},
linestring: function(feature) {
var nodes = [];
var geometry = feature.geometry;
if (feature.osm_id) {
id = feature.osm_id;
} else {
id = -this.osm_id;
this.osm_id++;
}
var way = this.createElementNS(null, "way");
way.setAttribute("id", id);
for (var i = 0; i < geometry.components.length; i++) {
var node = this.createXML['point'].apply(this, [geometry.components[i]]);
if (node.length) {
node = node[0];
var node_ref = node.getAttribute("id");
nodes.push(node);
} else {
node_ref = geometry.components[i].osm_id;
node = this.created_nodes[node_ref];
}
this.setState(feature, node);
var nd_dom = this.createElementNS(null, "nd");
nd_dom.setAttribute("ref", node_ref);
way.appendChild(nd_dom);
}
this.serializeTags(feature, way);
nodes.push(way);
return nodes;
},
polygon: function(feature) {
var attrs = OpenLayers.Util.extend({'area':'yes'}, feature.attributes);
var feat = new OpenLayers.Feature.Vector(feature.geometry.components[0], attrs);
feat.osm_id = feature.osm_id;
return this.createXML['linestring'].apply(this, [feat]);
}
},
/**
* Method: serializeTags
* Given a feature, serialize the attributes onto the given node.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
* node - {DOMNode}
*/
serializeTags: function(feature, node) {
for (var key in feature.attributes) {
var tag = this.createElementNS(null, "tag");
tag.setAttribute("k", key);
tag.setAttribute("v", feature.attributes[key]);
node.appendChild(tag);
}
},
/**
* Method: setState
* OpenStreetMap has a convention that 'state' is stored for modification or deletion.
* This allows the file to be uploaded via JOSM or the bulk uploader tool.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
* node - {DOMNode}
*/
setState: function(feature, node) {
if (feature.state) {
var state = null;
switch(feature.state) {
case OpenLayers.State.UPDATE:
state = "modify";
case OpenLayers.State.DELETE:
state = "delete";
}
if (state) {
node.setAttribute("action", state);
}
}
},
CLASS_NAME: "OpenLayers.Format.OSM"
});

View File

@ -1,130 +0,0 @@
/* Copyright (c) 2006 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/Format/XML.js
* @requires OpenLayers/Style.js
* @requires OpenLayers/Rule.js
* @requires OpenLayers/Filter/FeatureId.js
* @requires OpenLayers/Filter/Logical.js
* @requires OpenLayers/Filter/Comparison.js
* @requires OpenLayers/Filter/Spatial.js
*/
/**
* Class: OpenLayers.Format.SLD
* Read/Wite SLD. Create a new instance with the <OpenLayers.Format.SLD>
* constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.SLD = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.0.0".
*/
defaultVersion: "1.0.0",
/**
* APIProperty: version
* {String} Specify a version string if one is known.
*/
version: null,
/**
* APIProperty: namedLayersAsArray
* {Boolean} Generate a namedLayers array. If false, the namedLayers
* property value will be an object keyed by layer name. Default is
* false.
*/
namedLayersAsArray: false,
/**
* Property: parser
* {Object} Instance of the versioned parser. Cached for multiple read and
* write calls of the same version.
*/
parser: null,
/**
* Constructor: OpenLayers.Format.SLD
* Create a new parser for SLD.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: write
* Write a SLD document given a list of styles.
*
* Parameters:
* sld - {Object} An object representing the SLD.
* options - {Object} Optional configuration object.
*
* Returns:
* {String} An SLD document string.
*/
write: function(sld, options) {
var version = (options && options.version) ||
this.version || this.defaultVersion;
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.SLD[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a SLD parser for version " +
version;
}
this.parser = new format(this.options);
}
var root = this.parser.write(sld);
return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
},
/**
* APIMethod: read
* Read and SLD doc and return an object representing the SLD.
*
* Parameters:
* data - {String | DOMElement} Data to read.
* options - {Object} Options for the reader.
*
* Returns:
* {Object} An object representing the SLD.
*/
read: function(data, options) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var root = data.documentElement;
var version = this.version;
if(!version) {
version = root.getAttribute("version");
if(!version) {
version = this.defaultVersion;
}
}
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.SLD[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a SLD parser for version " +
version;
}
this.parser = new format(this.options);
}
var sld = this.parser.read(data, options);
return sld;
},
CLASS_NAME: "OpenLayers.Format.SLD"
});

View File

@ -1,883 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Rule.js
* @requires OpenLayers/Format/SLD.js
* @requires OpenLayers/Format/Filter/v1_0_0.js
*/
/**
* Class: OpenLayers.Format.SLD.v1
* Superclass for SLD version 1 parsers.
*
* Inherits from:
* - <OpenLayers.Format.Filter.v1_0_0>
*/
OpenLayers.Format.SLD.v1 = OpenLayers.Class(OpenLayers.Format.Filter.v1_0_0, {
/**
* Property: namespaces
* {Object} Mapping of namespace aliases to namespace URIs.
*/
namespaces: {
sld: "http://www.opengis.net/sld",
ogc: "http://www.opengis.net/ogc",
gml: "http://www.opengis.net/gml",
xlink: "http://www.w3.org/1999/xlink",
xsi: "http://www.w3.org/2001/XMLSchema-instance"
},
/**
* Property: defaultPrefix
*/
defaultPrefix: "sld",
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version.
*/
schemaLocation: null,
/**
* APIProperty: defaultSymbolizer.
* {Object} A symbolizer with the SLD defaults.
*/
defaultSymbolizer: {
fillColor: "#808080",
fillOpacity: 1,
strokeColor: "#000000",
strokeOpacity: 1,
strokeWidth: 1,
strokeDashstyle: "solid",
pointRadius: 3,
graphicName: "square"
},
/**
* Constructor: OpenLayers.Format.SLD.v1
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.SLD> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.Filter.v1_0_0.prototype.initialize.apply(this, [options]);
},
/**
* Method: read
*
* Parameters:
* data - {DOMElement} An SLD document element.
* options - {Object} Options for the reader.
*
* Valid options:
* namedLayersAsArray - {Boolean} Generate a namedLayers array. If false,
* the namedLayers property value will be an object keyed by layer name.
* Default is false.
*
* Returns:
* {Object} An object representing the SLD.
*/
read: function(data, options) {
options = OpenLayers.Util.applyDefaults(options, this.options);
var sld = {
namedLayers: options.namedLayersAsArray === true ? [] : {}
};
this.readChildNodes(data, sld);
return sld;
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: OpenLayers.Util.applyDefaults({
"sld": {
"StyledLayerDescriptor": function(node, sld) {
sld.version = node.getAttribute("version");
this.readChildNodes(node, sld);
},
"Name": function(node, obj) {
obj.name = this.getChildValue(node);
},
"Title": function(node, obj) {
obj.title = this.getChildValue(node);
},
"Abstract": function(node, obj) {
obj.description = this.getChildValue(node);
},
"NamedLayer": function(node, sld) {
var layer = {
userStyles: [],
namedStyles: []
};
this.readChildNodes(node, layer);
// give each of the user styles this layer name
for(var i=0, len=layer.userStyles.length; i<len; ++i) {
layer.userStyles[i].layerName = layer.name;
}
if(sld.namedLayers instanceof Array) {
sld.namedLayers.push(layer);
} else {
sld.namedLayers[layer.name] = layer;
}
},
"NamedStyle": function(node, layer) {
layer.namedStyles.push(
this.getChildName(node.firstChild)
);
},
"UserStyle": function(node, layer) {
var obj = {defaultsPerSymbolizer: true, rules: []};
this.readChildNodes(node, obj);
var style = new OpenLayers.Style(this.defaultSymbolizer, obj);
layer.userStyles.push(style);
},
"IsDefault": function(node, style) {
if(this.getChildValue(node) == "1") {
style.isDefault = true;
}
},
"FeatureTypeStyle": function(node, style) {
// OpenLayers doesn't have a place for FeatureTypeStyle
// Name, Title, Abstract, FeatureTypeName, or
// SemanticTypeIdentifier so, we make a temporary object
// and later just use the Rule(s).
var obj = {
rules: []
};
this.readChildNodes(node, obj);
style.rules = obj.rules;
},
"Rule": function(node, obj) {
var rule = new OpenLayers.Rule();
this.readChildNodes(node, rule);
obj.rules.push(rule);
},
"ElseFilter": function(node, rule) {
rule.elseFilter = true;
},
"MinScaleDenominator": function(node, rule) {
rule.minScaleDenominator = parseFloat(this.getChildValue(node));
},
"MaxScaleDenominator": function(node, rule) {
rule.maxScaleDenominator = parseFloat(this.getChildValue(node));
},
"TextSymbolizer": function(node, rule) {
// OpenLayers doens't do painter's order, instead we extend
var symbolizer = rule.symbolizer["Text"] || {};
this.readChildNodes(node, symbolizer);
// in case it didn't exist before
rule.symbolizer["Text"] = symbolizer;
},
"Label": function(node, symbolizer) {
// only supporting literal or property name
var obj = {};
this.readChildNodes(node, obj);
if(obj.property) {
symbolizer.label = "${" + obj.property + "}";
} else {
var value = this.readOgcExpression(node);
if(value) {
symbolizer.label = value;
}
}
},
"Font": function(node, symbolizer) {
this.readChildNodes(node, symbolizer);
},
"Halo": function(node, symbolizer) {
// halo has a fill, so send fresh object
var obj = {};
this.readChildNodes(node, obj);
symbolizer.haloRadius = obj.haloRadius;
symbolizer.haloColor = obj.fillColor;
symbolizer.haloOpacity = obj.fillOpacity;
},
"Radius": function(node, symbolizer) {
var radius = this.readOgcExpression(node);
if(radius != null) {
// radius is only used for halo
symbolizer.haloRadius = radius;
}
},
"LineSymbolizer": function(node, rule) {
// OpenLayers doesn't do painter's order, instead we extend
var symbolizer = rule.symbolizer["Line"] || {};
this.readChildNodes(node, symbolizer);
// in case it didn't exist before
rule.symbolizer["Line"] = symbolizer;
},
"PolygonSymbolizer": function(node, rule) {
// OpenLayers doens't do painter's order, instead we extend
var symbolizer = rule.symbolizer["Polygon"] || {};
this.readChildNodes(node, symbolizer);
// in case it didn't exist before
rule.symbolizer["Polygon"] = symbolizer;
},
"PointSymbolizer": function(node, rule) {
// OpenLayers doens't do painter's order, instead we extend
var symbolizer = rule.symbolizer["Point"] || {};
this.readChildNodes(node, symbolizer);
// in case it didn't exist before
rule.symbolizer["Point"] = symbolizer;
},
"Stroke": function(node, symbolizer) {
symbolizer.stroke = true;
this.readChildNodes(node, symbolizer);
},
"Fill": function(node, symbolizer) {
symbolizer.fill = true;
this.readChildNodes(node, symbolizer);
},
"CssParameter": function(node, symbolizer) {
var cssProperty = node.getAttribute("name");
var symProperty = this.cssMap[cssProperty];
if(symProperty) {
// Limited support for parsing of OGC expressions
var value = this.readOgcExpression(node);
// always string, could be an empty string
if(value) {
symbolizer[symProperty] = value;
}
}
},
"Graphic": function(node, symbolizer) {
symbolizer.graphic = true;
var graphic = {};
// painter's order not respected here, clobber previous with next
this.readChildNodes(node, graphic);
// directly properties with names that match symbolizer properties
var properties = [
"strokeColor", "strokeWidth", "strokeOpacity",
"strokeLinecap", "fillColor", "fillOpacity",
"graphicName", "rotation", "graphicFormat"
];
var prop, value;
for(var i=0, len=properties.length; i<len; ++i) {
prop = properties[i];
value = graphic[prop];
if(value != undefined) {
symbolizer[prop] = value;
}
}
// set other generic properties with specific graphic property names
if(graphic.opacity != undefined) {
symbolizer.graphicOpacity = graphic.opacity;
}
if(graphic.size != undefined) {
symbolizer.pointRadius = graphic.size / 2;
}
if(graphic.href != undefined) {
symbolizer.externalGraphic = graphic.href;
}
if(graphic.rotation != undefined) {
symbolizer.rotation = graphic.rotation;
}
},
"ExternalGraphic": function(node, graphic) {
this.readChildNodes(node, graphic);
},
"Mark": function(node, graphic) {
this.readChildNodes(node, graphic);
},
"WellKnownName": function(node, graphic) {
graphic.graphicName = this.getChildValue(node);
},
"Opacity": function(node, obj) {
var opacity = this.readOgcExpression(node);
// always string, could be empty string
if(opacity) {
obj.opacity = opacity;
}
},
"Size": function(node, obj) {
var size = this.readOgcExpression(node);
// always string, could be empty string
if(size) {
obj.size = size;
}
},
"Rotation": function(node, obj) {
var rotation = this.readOgcExpression(node);
// always string, could be empty string
if(rotation) {
obj.rotation = rotation;
}
},
"OnlineResource": function(node, obj) {
obj.href = this.getAttributeNS(
node, this.namespaces.xlink, "href"
);
},
"Format": function(node, graphic) {
graphic.graphicFormat = this.getChildValue(node);
}
}
}, OpenLayers.Format.Filter.v1_0_0.prototype.readers),
/**
* Property: cssMap
* {Object} Object mapping supported css property names to OpenLayers
* symbolizer property names.
*/
cssMap: {
"stroke": "strokeColor",
"stroke-opacity": "strokeOpacity",
"stroke-width": "strokeWidth",
"stroke-linecap": "strokeLinecap",
"stroke-dasharray": "strokeDashstyle",
"fill": "fillColor",
"fill-opacity": "fillOpacity",
"font-family": "fontFamily",
"font-size": "fontSize",
"font-weight": "fontWeight",
"font-style": "fontStyle"
},
/**
* Method: getCssProperty
* Given a symbolizer property, get the corresponding CSS property
* from the <cssMap>.
*
* Parameters:
* sym - {String} A symbolizer property name.
*
* Returns:
* {String} A CSS property name or null if none found.
*/
getCssProperty: function(sym) {
var css = null;
for(var prop in this.cssMap) {
if(this.cssMap[prop] == sym) {
css = prop;
break;
}
}
return css;
},
/**
* Method: getGraphicFormat
* Given a href for an external graphic, try to determine the mime-type.
* This method doesn't try too hard, and will fall back to
* <defautlGraphicFormat> if one of the known <graphicFormats> is not
* the file extension of the provided href.
*
* Parameters:
* href - {String}
*
* Returns:
* {String} The graphic format.
*/
getGraphicFormat: function(href) {
var format, regex;
for(var key in this.graphicFormats) {
if(this.graphicFormats[key].test(href)) {
format = key;
break;
}
}
return format || this.defautlGraphicFormat;
},
/**
* Property: defaultGraphicFormat
* {String} If none other can be determined from <getGraphicFormat>, this
* default will be returned.
*/
defaultGraphicFormat: "image/png",
/**
* Property: graphicFormats
* {Object} Mapping of image mime-types to regular extensions matching
* well-known file extensions.
*/
graphicFormats: {
"image/jpeg": /\.jpe?g$/i,
"image/gif": /\.gif$/i,
"image/png": /\.png$/i
},
/**
* Method: write
*
* Parameters:
* sld - {Object} An object representing the SLD.
*
* Returns:
* {DOMElement} The root of an SLD document.
*/
write: function(sld) {
return this.writers.sld.StyledLayerDescriptor.apply(this, [sld]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: OpenLayers.Util.applyDefaults({
"sld": {
"StyledLayerDescriptor": function(sld) {
var root = this.createElementNSPlus(
"StyledLayerDescriptor",
{attributes: {
"version": this.VERSION,
"xsi:schemaLocation": this.schemaLocation
}}
);
// add in optional name
if(sld.name) {
this.writeNode("Name", sld.name, root);
}
// add in optional title
if(sld.title) {
this.writeNode("Title", sld.title, root);
}
// add in optional description
if(sld.description) {
this.writeNode("Abstract", sld.description, root);
}
// add in named layers
// allow namedLayers to be an array
if(sld.namedLayers instanceof Array) {
for(var i=0, len=sld.namedLayers.length; i<len; ++i) {
this.writeNode("NamedLayer", sld.namedLayers[i], root);
}
} else {
for(var name in sld.namedLayers) {
this.writeNode("NamedLayer", sld.namedLayers[name], root);
}
}
return root;
},
"Name": function(name) {
return this.createElementNSPlus("Name", {value: name});
},
"Title": function(title) {
return this.createElementNSPlus("Title", {value: title});
},
"Abstract": function(description) {
return this.createElementNSPlus(
"Abstract", {value: description}
);
},
"NamedLayer": function(layer) {
var node = this.createElementNSPlus("NamedLayer");
// add in required name
this.writeNode("Name", layer.name, node);
// optional sld:LayerFeatureConstraints here
// add in named styles
if(layer.namedStyles) {
for(var i=0, len=layer.namedStyles.length; i<len; ++i) {
this.writeNode(
"NamedStyle", layer.namedStyles[i], node
);
}
}
// add in user styles
if(layer.userStyles) {
for(var i=0, len=layer.userStyles.length; i<len; ++i) {
this.writeNode(
"UserStyle", layer.userStyles[i], node
);
}
}
return node;
},
"NamedStyle": function(name) {
var node = this.createElementNSPlus("NamedStyle");
this.writeNode("Name", name, node);
return node;
},
"UserStyle": function(style) {
var node = this.createElementNSPlus("UserStyle");
// add in optional name
if(style.name) {
this.writeNode("Name", style.name, node);
}
// add in optional title
if(style.title) {
this.writeNode("Title", style.title, node);
}
// add in optional description
if(style.description) {
this.writeNode("Abstract", style.description, node);
}
// add isdefault
if(style.isDefault) {
this.writeNode("IsDefault", style.isDefault, node);
}
// add FeatureTypeStyles
this.writeNode("FeatureTypeStyle", style, node);
return node;
},
"IsDefault": function(bool) {
return this.createElementNSPlus(
"IsDefault", {value: (bool) ? "1" : "0"}
);
},
"FeatureTypeStyle": function(style) {
var node = this.createElementNSPlus("FeatureTypeStyle");
// OpenLayers currently stores no Name, Title, Abstract,
// FeatureTypeName, or SemanticTypeIdentifier information
// related to FeatureTypeStyle
// add in rules
for(var i=0, len=style.rules.length; i<len; ++i) {
this.writeNode("Rule", style.rules[i], node);
}
return node;
},
"Rule": function(rule) {
var node = this.createElementNSPlus("Rule");
// add in optional name
if(rule.name) {
this.writeNode("Name", rule.name, node);
}
// add in optional title
if(rule.title) {
this.writeNode("Title", rule.title, node);
}
// add in optional description
if(rule.description) {
this.writeNode("Abstract", rule.description, node);
}
// add in LegendGraphic here
// add in optional filters
if(rule.elseFilter) {
this.writeNode("ElseFilter", null, node);
} else if(rule.filter) {
this.writeNode("ogc:Filter", rule.filter, node);
}
// add in scale limits
if(rule.minScaleDenominator != undefined) {
this.writeNode(
"MinScaleDenominator", rule.minScaleDenominator, node
);
}
if(rule.maxScaleDenominator != undefined) {
this.writeNode(
"MaxScaleDenominator", rule.maxScaleDenominator, node
);
}
// add in symbolizers (relies on geometry type keys)
var types = OpenLayers.Style.SYMBOLIZER_PREFIXES;
var type, symbolizer;
for(var i=0, len=types.length; i<len; ++i) {
type = types[i];
symbolizer = rule.symbolizer[type];
if(symbolizer) {
this.writeNode(
type + "Symbolizer", symbolizer, node
);
}
}
return node;
},
"ElseFilter": function() {
return this.createElementNSPlus("ElseFilter");
},
"MinScaleDenominator": function(scale) {
return this.createElementNSPlus(
"MinScaleDenominator", {value: scale}
);
},
"MaxScaleDenominator": function(scale) {
return this.createElementNSPlus(
"MaxScaleDenominator", {value: scale}
);
},
"LineSymbolizer": function(symbolizer) {
var node = this.createElementNSPlus("LineSymbolizer");
this.writeNode("Stroke", symbolizer, node);
return node;
},
"Stroke": function(symbolizer) {
var node = this.createElementNSPlus("Stroke");
// GraphicFill here
// GraphicStroke here
// add in CssParameters
if(symbolizer.strokeColor != undefined) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "strokeColor"},
node
);
}
if(symbolizer.strokeOpacity != undefined) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "strokeOpacity"},
node
);
}
if(symbolizer.strokeWidth != undefined) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "strokeWidth"},
node
);
}
return node;
},
"CssParameter": function(obj) {
// not handling ogc:expressions for now
return this.createElementNSPlus("CssParameter", {
attributes: {name: this.getCssProperty(obj.key)},
value: obj.symbolizer[obj.key]
});
},
"TextSymbolizer": function(symbolizer) {
var node = this.createElementNSPlus("TextSymbolizer");
// add in optional Label
if(symbolizer.label != null) {
this.writeNode("Label", symbolizer.label, node);
}
// add in optional Font
if(symbolizer.fontFamily != null ||
symbolizer.fontSize != null ||
symbolizer.fontWeight != null ||
symbolizer.fontStyle != null) {
this.writeNode("Font", symbolizer, node);
}
// add in optional Halo
if(symbolizer.haloRadius != null ||
symbolizer.haloColor != null ||
symbolizer.haloOpacity != null) {
this.writeNode("Halo", symbolizer, node);
}
// add in optional Fill
if(symbolizer.fillColor != null ||
symbolizer.fillOpacity != null) {
this.writeNode("Fill", symbolizer, node);
}
return node;
},
"Font": function(symbolizer) {
var node = this.createElementNSPlus("Font");
// add in CssParameters
if(symbolizer.fontFamily) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fontFamily"},
node
);
}
if(symbolizer.fontSize) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fontSize"},
node
);
}
if(symbolizer.fontWeight) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fontWeight"},
node
);
}
if(symbolizer.fontStyle) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fontStyle"},
node
);
}
return node;
},
"Label": function(label) {
// only the simplest of ogc:expression handled
// {label: "some text and a ${propertyName}"}
var node = this.createElementNSPlus("Label");
var tokens = label.split("${");
node.appendChild(this.createTextNode(tokens[0]));
var item, last;
for(var i=1, len=tokens.length; i<len; i++) {
item = tokens[i];
last = item.indexOf("}");
if(last > 0) {
this.writeNode(
"ogc:PropertyName",
{property: item.substring(0, last)},
node
);
node.appendChild(
this.createTextNode(item.substring(++last))
);
} else {
// no ending }, so this is a literal ${
node.appendChild(
this.createTextNode("${" + item)
);
}
}
return node;
},
"Halo": function(symbolizer) {
var node = this.createElementNSPlus("Halo");
if(symbolizer.haloRadius) {
this.writeNode("Radius", symbolizer.haloRadius, node);
}
if(symbolizer.haloColor || symbolizer.haloOpacity) {
this.writeNode("Fill", {
fillColor: symbolizer.haloColor,
fillOpacity: symbolizer.haloOpacity
}, node);
}
return node;
},
"Radius": function(value) {
return node = this.createElementNSPlus("Radius", {
value: value
});
},
"PolygonSymbolizer": function(symbolizer) {
var node = this.createElementNSPlus("PolygonSymbolizer");
if(symbolizer.fillColor != undefined ||
symbolizer.fillOpacity != undefined) {
this.writeNode("Fill", symbolizer, node);
}
if(symbolizer.strokeWidth != undefined ||
symbolizer.strokeColor != undefined ||
symbolizer.strokeOpacity != undefined ||
symbolizer.strokeDashstyle != undefined) {
this.writeNode("Stroke", symbolizer, node);
}
return node;
},
"Fill": function(symbolizer) {
var node = this.createElementNSPlus("Fill");
// GraphicFill here
// add in CssParameters
if(symbolizer.fillColor) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fillColor"},
node
);
}
if(symbolizer.fillOpacity != null) {
this.writeNode(
"CssParameter",
{symbolizer: symbolizer, key: "fillOpacity"},
node
);
}
return node;
},
"PointSymbolizer": function(symbolizer) {
var node = this.createElementNSPlus("PointSymbolizer");
this.writeNode("Graphic", symbolizer, node);
return node;
},
"Graphic": function(symbolizer) {
var node = this.createElementNSPlus("Graphic");
if(symbolizer.externalGraphic != undefined) {
this.writeNode("ExternalGraphic", symbolizer, node);
} else {
this.writeNode("Mark", symbolizer, node);
}
if(symbolizer.graphicOpacity != undefined) {
this.writeNode("Opacity", symbolizer.graphicOpacity, node);
}
if(symbolizer.pointRadius != undefined) {
this.writeNode("Size", symbolizer.pointRadius * 2, node);
}
if(symbolizer.rotation != undefined) {
this.writeNode("Rotation", symbolizer.rotation, node);
}
return node;
},
"ExternalGraphic": function(symbolizer) {
var node = this.createElementNSPlus("ExternalGraphic");
this.writeNode(
"OnlineResource", symbolizer.externalGraphic, node
);
var format = symbolizer.graphicFormat ||
this.getGraphicFormat(symbolizer.externalGraphic);
this.writeNode("Format", format, node);
return node;
},
"Mark": function(symbolizer) {
var node = this.createElementNSPlus("Mark");
if(symbolizer.graphicName) {
this.writeNode("WellKnownName", symbolizer.graphicName, node);
}
this.writeNode("Fill", symbolizer, node);
this.writeNode("Stroke", symbolizer, node);
return node;
},
"WellKnownName": function(name) {
return this.createElementNSPlus("WellKnownName", {
value: name
});
},
"Opacity": function(value) {
return this.createElementNSPlus("Opacity", {
value: value
});
},
"Size": function(value) {
return this.createElementNSPlus("Size", {
value: value
});
},
"Rotation": function(value) {
return this.createElementNSPlus("Rotation", {
value: value
});
},
"OnlineResource": function(href) {
return this.createElementNSPlus("OnlineResource", {
attributes: {
"xlink:type": "simple",
"xlink:href": href
}
});
},
"Format": function(format) {
return this.createElementNSPlus("Format", {
value: format
});
}
}
}, OpenLayers.Format.Filter.v1_0_0.prototype.writers),
CLASS_NAME: "OpenLayers.Format.SLD.v1"
});

View File

@ -1,50 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/SLD/v1.js
* @requires OpenLayers/Format/Filter/v1_0_0.js
*/
/**
* Class: OpenLayers.Format.SLD.v1_0_0
* Write SLD version 1.0.0.
*
* Inherits from:
* - <OpenLayers.Format.SLD.v1>
*/
OpenLayers.Format.SLD.v1_0_0 = OpenLayers.Class(
OpenLayers.Format.SLD.v1, {
/**
* Constant: VERSION
* {String} 1.0.0
*/
VERSION: "1.0.0",
/**
* Property: schemaLocation
* {String} http://www.opengis.net/sld
* http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd
*/
schemaLocation: "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd",
/**
* Constructor: OpenLayers.Format.SLD.v1_0_0
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.SLD> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.SLD.v1.prototype.initialize.apply(
this, [options]
);
},
CLASS_NAME: "OpenLayers.Format.SLD.v1_0_0"
});

View File

@ -1,151 +0,0 @@
/* Copyright (c) 2006-2008 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/Feature/Vector.js
* @requires OpenLayers/Geometry/Point.js
*/
/**
* Class: OpenLayers.Format.Text
* Read Text format. Create a new instance with the <OpenLayers.Format.Text>
* constructor. This reads text which is formatted like CSV text, using
* tabs as the seperator by default. It provides parsing of data originally
* used in the MapViewerService, described on the wiki. This Format is used
* by the <OpenLayers.Layer.Text> class.
*
* Inherits from:
* - <OpenLayers.Format>
*/
OpenLayers.Format.Text = OpenLayers.Class(OpenLayers.Format, {
/**
* APIProperty: defaultStyle
* defaultStyle allows one to control the default styling of the features.
* It should be a symbolizer hash. By default, this is set to match the
* Layer.Text behavior, which is to use the default OpenLayers Icon.
*/
defaultStyle: null,
/**
* APIProperty: extractStyles
* set to true to extract styles from the TSV files, using information
* from the image or icon, iconSize and iconOffset fields. This will result
* in features with a symbolizer (style) property set, using the
* default symbolizer specified in <defaultStyle>. Set to false if you
* wish to use a styleMap or OpenLayers.Style options to style your
* layer instead.
*/
extractStyles: true,
/**
* Constructor: OpenLayers.Format.Text
* Create a new parser for TSV Text.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
options = options || {};
if(options.extractStyles !== false) {
options.defaultStyle = {
'externalGraphic': OpenLayers.Util.getImagesLocation() +
"marker.png",
'graphicWidth': 21,
'graphicHeight': 25,
'graphicXOffset': -10.5,
'graphicYOffset': -12.5
};
}
OpenLayers.Format.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: read
* Return a list of features from a Tab Seperated Values text string.
*
* Parameters:
* data - {String}
*
* Returns:
* An Array of <OpenLayers.Feature.Vector>s
*/
read: function(text) {
var lines = text.split('\n');
var columns;
var features = [];
// length - 1 to allow for trailing new line
for (var lcv = 0; lcv < (lines.length - 1); lcv++) {
var currLine = lines[lcv].replace(/^\s*/,'').replace(/\s*$/,'');
if (currLine.charAt(0) != '#') { /* not a comment */
if (!columns) {
//First line is columns
columns = currLine.split('\t');
} else {
var vals = currLine.split('\t');
var geometry = new OpenLayers.Geometry.Point(0,0);
var attributes = {};
var style = this.defaultStyle ?
OpenLayers.Util.applyDefaults({}, this.defaultStyle) :
null;
var icon, iconSize, iconOffset, overflow;
var set = false;
for (var valIndex = 0; valIndex < vals.length; valIndex++) {
if (vals[valIndex]) {
if (columns[valIndex] == 'point') {
var coords = vals[valIndex].split(',');
geometry.y = parseFloat(coords[0]);
geometry.x = parseFloat(coords[1]);
set = true;
} else if (columns[valIndex] == 'lat') {
geometry.y = parseFloat(vals[valIndex]);
set = true;
} else if (columns[valIndex] == 'lon') {
geometry.x = parseFloat(vals[valIndex]);
set = true;
} else if (columns[valIndex] == 'title')
attributes['title'] = vals[valIndex];
else if (columns[valIndex] == 'image' ||
columns[valIndex] == 'icon' && style) {
style['externalGraphic'] = vals[valIndex];
} else if (columns[valIndex] == 'iconSize' && style) {
var size = vals[valIndex].split(',');
style['graphicWidth'] = parseFloat(size[0]);
style['graphicHeight'] = parseFloat(size[1]);
} else if (columns[valIndex] == 'iconOffset' && style) {
var offset = vals[valIndex].split(',');
style['graphicXOffset'] = parseFloat(offset[0]);
style['graphicYOffset'] = parseFloat(offset[1]);
} else if (columns[valIndex] == 'description') {
attributes['description'] = vals[valIndex];
} else if (columns[valIndex] == 'overflow') {
attributes['overflow'] = vals[valIndex];
} else {
// For StyleMap filtering, allow additional
// columns to be stored as attributes.
attributes[columns[valIndex]] = vals[valIndex];
}
}
}
if (set) {
if (this.internalProjection && this.externalProjection) {
geometry.transform(this.externalProjection,
this.internalProjection);
}
var feature = new OpenLayers.Feature.Vector(geometry, attributes, style);
features.push(feature);
}
}
}
}
return features;
},
CLASS_NAME: "OpenLayers.Format.Text"
});

View File

@ -1,219 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/GML.js
* @requires OpenLayers/Console.js
*/
/**
* Class: OpenLayers.Format.WFS
* Read/Write WFS.
*
* Inherits from:
* - <OpenLayers.Format.GML>
*/
OpenLayers.Format.WFS = OpenLayers.Class(OpenLayers.Format.GML, {
/**
* Property: layer
*/
layer: null,
/**
* APIProperty: wfsns
*/
wfsns: "http://www.opengis.net/wfs",
/**
* Property: ogcns
*/
ogcns: "http://www.opengis.net/ogc",
/*
* Constructor: OpenLayers.Format.WFS
* Create a WFS-T formatter. This requires a layer: that layer should
* have two properties: geometry_column and typename. The parser
* for this format is subclassed entirely from GML: There is a writer
* only, which uses most of the code from the GML layer, and wraps
* it in transactional elements.
*
* Parameters:
* options - {Object}
* layer - {<OpenLayers.Layer>}
*/
initialize: function(options, layer) {
OpenLayers.Format.GML.prototype.initialize.apply(this, [options]);
this.layer = layer;
if (this.layer.featureNS) {
this.featureNS = this.layer.featureNS;
}
if (this.layer.options.geometry_column) {
this.geometryName = this.layer.options.geometry_column;
}
if (this.layer.options.typename) {
this.featureName = this.layer.options.typename;
}
},
/**
* Method: write
* Takes a feature list, and generates a WFS-T Transaction
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)}
*/
write: function(features) {
var transaction = this.createElementNS(this.wfsns, 'wfs:Transaction');
transaction.setAttribute("version","1.0.0");
transaction.setAttribute("service","WFS");
for (var i=0; i < features.length; i++) {
switch (features[i].state) {
case OpenLayers.State.INSERT:
transaction.appendChild(this.insert(features[i]));
break;
case OpenLayers.State.UPDATE:
transaction.appendChild(this.update(features[i]));
break;
case OpenLayers.State.DELETE:
transaction.appendChild(this.remove(features[i]));
break;
}
}
return OpenLayers.Format.XML.prototype.write.apply(this,[transaction]);
},
/**
* Method: createFeatureXML
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
createFeatureXML: function(feature) {
var geometryNode = this.buildGeometryNode(feature.geometry);
var geomContainer = this.createElementNS(this.featureNS, "feature:" + this.geometryName);
geomContainer.appendChild(geometryNode);
var featureContainer = this.createElementNS(this.featureNS, "feature:" + this.featureName);
featureContainer.appendChild(geomContainer);
for(var attr in feature.attributes) {
var attrText = this.createTextNode(feature.attributes[attr]);
var nodename = attr;
if (attr.search(":") != -1) {
nodename = attr.split(":")[1];
}
var attrContainer = this.createElementNS(this.featureNS, "feature:" + nodename);
attrContainer.appendChild(attrText);
featureContainer.appendChild(attrContainer);
}
return featureContainer;
},
/**
* Method: insert
* Takes a feature, and generates a WFS-T Transaction "Insert"
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
insert: function(feature) {
var insertNode = this.createElementNS(this.wfsns, 'wfs:Insert');
insertNode.appendChild(this.createFeatureXML(feature));
return insertNode;
},
/**
* Method: update
* Takes a feature, and generates a WFS-T Transaction "Update"
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
update: function(feature) {
if (!feature.fid) { OpenLayers.Console.userError(OpenLayers.i18n("noFID")); }
var updateNode = this.createElementNS(this.wfsns, 'wfs:Update');
updateNode.setAttribute("typeName", this.featurePrefix + ':' + this.featureName);
updateNode.setAttribute("xmlns:" + this.featurePrefix, this.featureNS);
var propertyNode = this.createElementNS(this.wfsns, 'wfs:Property');
var nameNode = this.createElementNS(this.wfsns, 'wfs:Name');
var txtNode = this.createTextNode(this.geometryName);
nameNode.appendChild(txtNode);
propertyNode.appendChild(nameNode);
var valueNode = this.createElementNS(this.wfsns, 'wfs:Value');
var geometryNode = this.buildGeometryNode(feature.geometry);
if(feature.layer){
geometryNode.setAttribute(
"srsName", feature.layer.projection.getCode()
);
}
valueNode.appendChild(geometryNode);
propertyNode.appendChild(valueNode);
updateNode.appendChild(propertyNode);
// add in attributes
for(var propName in feature.attributes) {
propertyNode = this.createElementNS(this.wfsns, 'wfs:Property');
nameNode = this.createElementNS(this.wfsns, 'wfs:Name');
nameNode.appendChild(this.createTextNode(propName));
propertyNode.appendChild(nameNode);
valueNode = this.createElementNS(this.wfsns, 'wfs:Value');
valueNode.appendChild(this.createTextNode(feature.attributes[propName]));
propertyNode.appendChild(valueNode);
updateNode.appendChild(propertyNode);
}
var filterNode = this.createElementNS(this.ogcns, 'ogc:Filter');
var filterIdNode = this.createElementNS(this.ogcns, 'ogc:FeatureId');
filterIdNode.setAttribute("fid", feature.fid);
filterNode.appendChild(filterIdNode);
updateNode.appendChild(filterNode);
return updateNode;
},
/**
* Method: remove
* Takes a feature, and generates a WFS-T Transaction "Delete"
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
*/
remove: function(feature) {
if (!feature.fid) {
OpenLayers.Console.userError(OpenLayers.i18n("noFID"));
return false;
}
var deleteNode = this.createElementNS(this.wfsns, 'wfs:Delete');
deleteNode.setAttribute("typeName", this.featurePrefix + ':' + this.featureName);
deleteNode.setAttribute("xmlns:" + this.featurePrefix, this.featureNS);
var filterNode = this.createElementNS(this.ogcns, 'ogc:Filter');
var filterIdNode = this.createElementNS(this.ogcns, 'ogc:FeatureId');
filterIdNode.setAttribute("fid", feature.fid);
filterNode.appendChild(filterIdNode);
deleteNode.appendChild(filterNode);
return deleteNode;
},
/**
* APIMethod: destroy
* Remove ciruclar ref to layer
*/
destroy: function() {
this.layer = null;
},
CLASS_NAME: "OpenLayers.Format.WFS"
});

View File

@ -1,75 +0,0 @@
/**
* @requires OpenLayers/Format/XML.js
*/
/**
* Class: OpenLayers.Format.WFSCapabilities
* Read WFS Capabilities.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.WFSCapabilities = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.1.0".
*/
defaultVersion: "1.1.0",
/**
* APIProperty: version
* {String} Specify a version string if one is known.
*/
version: null,
/**
* Constructor: OpenLayers.Format.WFSCapabilities
* Create a new parser for WFS capabilities.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
this.options = options;
},
/**
* APIMethod: read
* Read capabilities data from a string, and return a list of layers.
*
* Parameters:
* data - {String} or {DOMElement} data to read/parse.
*
* Returns:
* {Array} List of named layers.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var root = data.documentElement;
var version = this.version;
if(!version) {
version = root.getAttribute("version");
if(!version) {
version = this.defaultVersion;
}
}
var constr = OpenLayers.Format.WFSCapabilities[
"v" + version.replace(/\./g, "_")
];
if(!constr) {
throw "Can't find a WFS capabilities parser for version " + version;
}
var parser = new constr(this.options);
var capabilities = parser.read(data);
capabilities.version = version;
return capabilities;
},
CLASS_NAME: "OpenLayers.Format.WFSCapabilities"
});

View File

@ -1,117 +0,0 @@
/**
* @requires OpenLayers/Format/WFSCapabilities.js
*/
/**
* Class: OpenLayers.Format.WFSCapabilities.v1
* Abstract class not to be instantiated directly.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.WFSCapabilities.v1 = OpenLayers.Class(
OpenLayers.Format.WFSCapabilities, {
/**
* Constructor: OpenLayers.Format.WFSCapabilities.v1_1
* Create an instance of one of the subclasses.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
this.options = options;
},
/**
* APIMethod: read
* Read capabilities data from a string, and return a list of layers.
*
* Parameters:
* data - {String} or {DOMElement} data to read/parse.
*
* Returns:
* {Array} List of named layers.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var capabilities = {};
var root = data.documentElement;
this.runChildNodes(capabilities, root);
return capabilities;
},
/**
* Method: runChildNodes
*/
runChildNodes: function(obj, node) {
var children = node.childNodes;
var childNode, processor;
for(var i=0; i<children.length; ++i) {
childNode = children[i];
if(childNode.nodeType == 1) {
processor = this["read_cap_" + childNode.nodeName];
if(processor) {
processor.apply(this, [obj, childNode]);
}
}
}
},
/**
* Method: read_cap_FeatureTypeList
*/
read_cap_FeatureTypeList: function(request, node) {
var featureTypeList = {
featureTypes: []
};
this.runChildNodes(featureTypeList, node);
request.featureTypeList = featureTypeList;
},
/**
* Method: read_cap_FeatureType
*/
read_cap_FeatureType: function(featureTypeList, node, parentLayer) {
var featureType = {};
this.runChildNodes(featureType, node);
featureTypeList.featureTypes.push(featureType);
},
/**
* Method: read_cap_Name
*/
read_cap_Name: function(obj, node) {
var name = this.getChildValue(node);
if(name) {
obj.name = name;
}
},
/**
* Method: read_cap_Title
*/
read_cap_Title: function(obj, node) {
var title = this.getChildValue(node);
if(title) {
obj.title = title;
}
},
/**
* Method: read_cap_Abstract
*/
read_cap_Abstract: function(obj, node) {
var abst = this.getChildValue(node);
if(abst) {
obj["abstract"] = abst;
}
},
CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v1"
});

View File

@ -1,31 +0,0 @@
/**
* @requires OpenLayers/Format/WFSCapabilities/v1.js
*/
/**
* Class: OpenLayers.Format.WFSCapabilities/v1_0_0
* Read WMS Capabilities version 1.0.0.
*
* Inherits from:
* - <OpenLayers.Format.WFSCapabilities>
*/
OpenLayers.Format.WFSCapabilities.v1_0_0 = OpenLayers.Class(
OpenLayers.Format.WFSCapabilities.v1, {
/**
* Constructor: OpenLayers.Format.WFSCapabilities.v1_0_0
* Create a new parser for WFS capabilities version 1.0.0.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.WFSCapabilities.v1.prototype.initialize.apply(
this, [options]
);
},
CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v1_0_0"
});

View File

@ -1,31 +0,0 @@
/**
* @requires OpenLayers/Format/WFSCapabilities/v1.js
*/
/**
* Class: OpenLayers.Format.WFSCapabilities/v1_1_0
* Read WFS Capabilities version 1.1.0.
*
* Inherits from:
* - <OpenLayers.Format.WFSCapabilities>
*/
OpenLayers.Format.WFSCapabilities.v1_1_0 = OpenLayers.Class(
OpenLayers.Format.WFSCapabilities.v1, {
/**
* Constructor: OpenLayers.Format.WFSCapabilities.v1_1_0
* Create a new parser for WFS capabilities version 1.1.0.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.WFSCapabilities.v1.prototype.initialize.apply(
this, [options]
);
},
CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v1_1_0"
});

View File

@ -1,193 +0,0 @@
/**
* @requires OpenLayers/Format/XML.js
*
* Class: OpenLayers.Format.WFSDescribeFeatureType
* Read WFS DescribeFeatureType response
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.WFSDescribeFeatureType = OpenLayers.Class(
OpenLayers.Format.XML, {
/**
* Property: namespaces
* {Object} Mapping of namespace aliases to namespace URIs.
*/
namespaces: {
xsd: "http://www.w3.org/2001/XMLSchema"
},
/**
* Constructor: OpenLayers.Format.WFSDescribeFeatureType
* Create a new parser for WFS DescribeFeatureType responses.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"xsd": {
"schema": function(node, obj) {
var complexTypes = [];
var customTypes = {};
var schema = {
complexTypes: complexTypes,
customTypes: customTypes
};
this.readChildNodes(node, schema);
var attributes = node.attributes;
var attr, name;
for(var i=0, len=attributes.length; i<len; ++i) {
attr = attributes[i];
name = attr.name;
if(name.indexOf("xmlns") == 0) {
this.setNamespace(name.split(":")[1] || "", attr.value);
} else {
obj[name] = attr.value;
}
}
obj.featureTypes = complexTypes;
obj.targetPrefix = this.namespaceAlias[obj.targetNamespace];
// map complexTypes to names of customTypes
var complexType, customType;
for(var i=0, len=complexTypes.length; i<len; ++i) {
complexType = complexTypes[i];
customType = customTypes[complexType.typeName];
if(customTypes[complexType.typeName]) {
complexType.typeName = customType.name;
}
}
},
"complexType": function(node, obj) {
var complexType = {
// this is a temporary typeName, it will be overwritten by
// the schema reader with the metadata found in the
// customTypes hash
"typeName": node.getAttribute("name")
};
this.readChildNodes(node, complexType);
obj.complexTypes.push(complexType);
},
"complexContent": function(node, obj) {
this.readChildNodes(node, obj);
},
"extension": function(node, obj) {
this.readChildNodes(node, obj);
},
"sequence": function(node, obj) {
var sequence = {
elements: []
};
this.readChildNodes(node, sequence);
obj.properties = sequence.elements;
},
"element": function(node, obj) {
if(obj.elements) {
var element = {};
var attributes = node.attributes;
var attr;
for(var i=0, len=attributes.length; i<len; ++i) {
attr = attributes[i];
element[attr.name] = attr.value;
}
var type = element.type;
if(!type) {
type = {};
this.readChildNodes(node, type);
element.restriction = type;
element.type = type.base;
}
var fullType = type.base || type;
element.localType = fullType.split(":").pop();
obj.elements.push(element);
}
if(obj.complexTypes) {
var type = node.getAttribute("type");
var localType = type.split(":").pop();
obj.customTypes[localType] = {
"name": node.getAttribute("name"),
"type": type
};
}
},
"simpleType": function(node, obj) {
this.readChildNodes(node, obj);
},
"restriction": function(node, obj) {
obj.base = node.getAttribute("base");
this.readRestriction(node, obj);
}
}
},
/**
* Method: readRestriction
* Reads restriction defined in the child nodes of a restriction element
*
* Parameters:
* node {DOMElement} - the node to parse
* obj {Object} - the object that receives the read result
*/
readRestriction: function(node, obj) {
var children = node.childNodes;
var child, nodeName, value;
for(var i=0, len=children.length; i<len; ++i) {
child = children[i];
if(child.nodeType == 1) {
nodeName = child.nodeName.split(":").pop();
value = child.getAttribute("value");
if(!obj[nodeName]) {
obj[nodeName] = value;
} else {
if(typeof obj[nodeName] == "string") {
obj[nodeName] = [obj[nodeName]];
}
obj[nodeName].push(value);
}
}
}
},
/**
* Method: read
*
* Parameters:
* data - {DOMElement|String} A WFS DescribeFeatureType document.
*
* Returns:
* {Object} An object representing the WFS DescribeFeatureType response.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
if(data && data.nodeType == 9) {
data = data.documentElement;
}
var schema = {};
this.readNode(data, schema);
return schema;
},
CLASS_NAME: "OpenLayers.Format.WFSDescribeFeatureType"
});

View File

@ -1,33 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format.js
*/
/**
* Function: OpenLayers.Format.WFST
* Used to create a versioned WFS protocol. Default version is 1.0.0.
*
* Returns:
* {<OpenLayers.Format>} A WFST format of the given version.
*/
OpenLayers.Format.WFST = function(options) {
options = OpenLayers.Util.applyDefaults(
options, OpenLayers.Format.WFST.DEFAULTS
);
var cls = OpenLayers.Format.WFST["v"+options.version.replace(/\./g, "_")];
if(!cls) {
throw "Unsupported WFST version: " + options.version;
}
return new cls(options);
};
/**
* Constant: OpenLayers.Format.WFST.DEFAULTS
* {Object} Default properties for the WFST format.
*/
OpenLayers.Format.WFST.DEFAULTS = {
"version": "1.0.0"
};

View File

@ -1,358 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML.js
* @requires OpenLayers/Format/WFST.js
*/
/**
* Class: OpenLayers.Format.WFST.v1
* Superclass for WFST parsers.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.WFST.v1 = OpenLayers.Class(OpenLayers.Format.XML, {
/**
* Property: namespaces
* {Object} Mapping of namespace aliases to namespace URIs.
*/
namespaces: {
xlink: "http://www.w3.org/1999/xlink",
xsi: "http://www.w3.org/2001/XMLSchema-instance",
wfs: "http://www.opengis.net/wfs",
gml: "http://www.opengis.net/gml",
ogc: "http://www.opengis.net/ogc"
},
/**
* Property: defaultPrefix
*/
defaultPrefix: "wfs",
/**
* Property: version
* {String} WFS version number.
*/
version: null,
/**
* Property: schemaLocation
* {String} Schema location for a particular minor version.
*/
schemaLocations: null,
/**
* APIProperty: srsName
* {String} URI for spatial reference system.
*/
srsName: null,
/**
* APIProperty: extractAttributes
* {Boolean} Extract attributes from GML. Default is true.
*/
extractAttributes: true,
/**
* APIProperty: xy
* {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x)
* Changing is not recommended, a new Format should be instantiated.
*/
xy: true,
/**
* Property: stateName
* {Object} Maps feature states to node names.
*/
stateName: null,
/**
* Constructor: OpenLayers.Format.WFST.v1
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.WFST.v1_0_0> or <OpenLayers.Format.WFST.v1_1_0>
* constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
// set state name mapping
this.stateName = {};
this.stateName[OpenLayers.State.INSERT] = "wfs:Insert";
this.stateName[OpenLayers.State.UPDATE] = "wfs:Update";
this.stateName[OpenLayers.State.DELETE] = "wfs:Delete";
OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
},
/**
* Method: getSrsName
*/
getSrsName: function(feature, options) {
var srsName = options && options.srsName;
if(!srsName) {
if(feature && feature.layer) {
srsName = feature.layer.projection.getCode();
} else {
srsName = this.srsName;
}
}
return srsName;
},
/**
* Method: read
* Parse the response from a transaction. Because WFS is split into
* Transaction requests (create, update, and delete) and GetFeature
* requests (read), this method handles parsing of both types of
* responses.
*/
read: function(data) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
if(data && data.nodeType == 9) {
data = data.documentElement;
}
var obj = {};
this.readNode(data, obj);
if(obj.features) {
obj = obj.features;
}
return obj;
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"wfs": {
"FeatureCollection": function(node, obj) {
obj.features = [];
this.readChildNodes(node, obj);
}
}
},
/**
* Method: write
* Given an array of features, write a WFS transaction. This assumes
* the features have a state property that determines the operation
* type - insert, update, or delete.
*
* Parameters:
* features - {Array(<OpenLayers.Feature.Vector>)} A list of features.
*
* Returns:
* {String} A serialized WFS transaction.
*/
write: function(features) {
var node = this.writeNode("wfs:Transaction", features);
var value = this.schemaLocationAttr();
if(value) {
this.setAttributeNS(
node, this.namespaces["xsi"], "xsi:schemaLocation", value
)
}
return OpenLayers.Format.XML.prototype.write.apply(this, [node]);
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"wfs": {
"GetFeature": function(options) {
var node = this.createElementNSPlus("wfs:GetFeature", {
attributes: {
service: "WFS",
version: this.version,
maxFeatures: options && options.maxFeatures,
"xsi:schemaLocation": this.schemaLocationAttr(options)
}
});
this.writeNode("Query", options, node);
return node;
},
"Query": function(options) {
options = OpenLayers.Util.extend({
featureNS: this.featureNS,
featurePrefix: this.featurePrefix,
featureType: this.featureType,
srsName: this.srsName
}, options);
// TODO: this is still version specific and should be separated out
// v1.0.0 does not allow srsName on wfs:Query
var node = this.createElementNSPlus("wfs:Query", {
attributes: {
typeName: (options.featureNS ? options.featurePrefix + ":" : "") +
options.featureType,
srsName: options.srsName
}
});
if(options.featureNS) {
node.setAttribute("xmlns:" + options.featurePrefix, options.featureNS);
}
if(options.filter) {
this.setFilterProperty(options.filter);
this.writeNode("ogc:Filter", options.filter, node);
}
return node;
},
"Transaction": function(features) {
var node = this.createElementNSPlus("wfs:Transaction", {
attributes: {
service: "WFS",
version: this.version
}
});
if(features) {
var name, feature;
for(var i=0, len=features.length; i<len; ++i) {
feature = features[i];
name = this.stateName[feature.state];
if(name) {
this.writeNode(name, feature, node);
}
}
}
return node;
},
"Insert": function(feature) {
var node = this.createElementNSPlus("wfs:Insert");
this.srsName = this.getSrsName(feature);
this.writeNode("feature:_typeName", feature, node);
return node;
},
"Update": function(feature) {
var node = this.createElementNSPlus("wfs:Update", {
attributes: {
typeName: (this.featureNS ? this.featurePrefix + ":" : "") +
this.featureType
}
});
if(this.featureNS) {
node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS);
}
// add in geometry
this.writeNode(
"Property", {name: this.geometryName, value: feature}, node
);
// add in attributes
for(var key in feature.attributes) {
this.writeNode(
"Property", {name: key, value: feature.attributes[key]}, node
);
}
// add feature id filter
this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({
fids: [feature.fid]
}), node);
return node;
},
"Property": function(obj) {
var node = this.createElementNSPlus("wfs:Property");
this.writeNode("Name", obj.name, node);
this.writeNode("Value", obj.value, node);
return node;
},
"Name": function(name) {
return this.createElementNSPlus("wfs:Name", {value: name});
},
"Value": function(obj) {
var node;
if(obj instanceof OpenLayers.Feature.Vector) {
node = this.createElementNSPlus("wfs:Value");
this.srsName = this.getSrsName(obj);
var geom = this.writeNode("feature:_geometry", obj.geometry).firstChild;
node.appendChild(geom);
} else {
node = this.createElementNSPlus("wfs:Value", {value: obj});
}
return node;
},
"Delete": function(feature) {
var node = this.createElementNSPlus("wfs:Delete", {
attributes: {
typeName: (this.featureNS ? this.featurePrefix + ":" : "") +
this.featureType
}
});
if(this.featureNS) {
node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS);
}
this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({
fids: [feature.fid]
}), node);
return node;
}
}
},
/**
* Method: schemaLocationAttr
* Generate the xsi:schemaLocation attribute value.
*
* Returns:
* {String} The xsi:schemaLocation attribute or undefined if none.
*/
schemaLocationAttr: function(options) {
options = OpenLayers.Util.extend({
featurePrefix: this.featurePrefix,
schema: this.schema
}, options);
var schemaLocations = OpenLayers.Util.extend({}, this.schemaLocations);
if(options.schema) {
schemaLocations[options.featurePrefix] = options.schema;
}
var parts = [];
var uri;
for(var key in schemaLocations) {
uri = this.namespaces[key];
if(uri) {
parts.push(uri + " " + schemaLocations[key]);
}
}
var value = parts.join(" ") || undefined;
return value;
},
/**
* Method: setFilterProperty
* Set the property of each spatial filter.
*
* Parameters:
* filter - {<OpenLayers.Filter>}
*/
setFilterProperty: function(filter) {
if(filter.filters) {
for(var i=0, len=filter.filters.length; i<len; ++i) {
this.setFilterProperty(filter.filters[i]);
}
} else {
if(filter instanceof OpenLayers.Filter.Spatial) {
// got a spatial filter, set its property
filter.property = this.geometryName;
}
}
},
CLASS_NAME: "OpenLayers.Format.WFST.v1"
});

View File

@ -1,133 +0,0 @@
/**
* @requires OpenLayers/Format/WFST/v1.js
* @requires OpenLayers/Format/Filter/v1_0_0.js
*/
/**
* Class: OpenLayers.Format.WFST.v1_0_0
* A format for creating WFS v1.0.0 transactions. Create a new instance with the
* <OpenLayers.Format.WFST.v1_0_0> constructor.
*
* Inherits from:
* - <OpenLayers.Format.Filter.v1_0_0>
* - <OpenLayers.Format.WFST.v1>
*/
OpenLayers.Format.WFST.v1_0_0 = OpenLayers.Class(
OpenLayers.Format.Filter.v1_0_0, OpenLayers.Format.WFST.v1, {
/**
* Property: version
* {String} WFS version number.
*/
version: "1.0.0",
/**
* Property: schemaLocations
* {Object} Properties are namespace aliases, values are schema locations.
*/
schemaLocations: {
"wfs": "http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd"
},
/**
* Constructor: OpenLayers.Format.WFST.v1_0_0
* A class for parsing and generating WFS v1.0.0 transactions.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*
* Valid options properties:
* featureType - {String} Local (without prefix) feature typeName (required).
* featureNS - {String} Feature namespace (optional).
* featurePrefix - {String} Feature namespace alias (optional - only used
* if featureNS is provided). Default is 'feature'.
* geometryName - {String} Name of geometry attribute. Default is 'the_geom'.
*/
initialize: function(options) {
OpenLayers.Format.Filter.v1_0_0.prototype.initialize.apply(this, [options]);
OpenLayers.Format.WFST.v1.prototype.initialize.apply(this, [options]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"wfs": OpenLayers.Util.applyDefaults({
"WFS_TransactionResponse": function(node, obj) {
obj.insertIds = [];
obj.success = false;
this.readChildNodes(node, obj);
},
"InsertResult": function(node, container) {
var obj = {fids: []};
this.readChildNodes(node, obj);
container.insertIds.push(obj.fids[0]);
},
"TransactionResult": function(node, obj) {
this.readChildNodes(node, obj);
},
"Status": function(node, obj) {
this.readChildNodes(node, obj);
},
"SUCCESS": function(node, obj) {
obj.success = true;
}
}, OpenLayers.Format.WFST.v1.prototype.readers["wfs"]),
"gml": OpenLayers.Format.GML.v2.prototype.readers["gml"],
"feature": OpenLayers.Format.GML.v2.prototype.readers["feature"],
"ogc": OpenLayers.Format.Filter.v1_0_0.prototype.readers["ogc"]
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"wfs": OpenLayers.Util.applyDefaults({
"Query": function(options) {
options = OpenLayers.Util.extend({
featureNS: this.featureNS,
featurePrefix: this.featurePrefix,
featureType: this.featureType,
srsName: this.srsName
}, options);
var node = this.createElementNSPlus("wfs:Query", {
attributes: {
typeName: (options.featureNS ? options.featurePrefix + ":" : "") +
options.featureType
}
});
if(options.featureNS) {
node.setAttribute("xmlns:" + options.featurePrefix, options.featureNS);
}
if(options.propertyNames) {
for(var i=0,len = options.propertyNames.length; i<len; i++) {
this.writeNode(
"ogc:PropertyName",
{property: options.propertyNames[i]},
node
);
}
}
if(options.filter) {
this.setFilterProperty(options.filter);
this.writeNode("ogc:Filter", options.filter, node);
}
return node;
}
}, OpenLayers.Format.WFST.v1.prototype.writers["wfs"]),
"gml": OpenLayers.Format.GML.v2.prototype.writers["gml"],
"feature": OpenLayers.Format.GML.v2.prototype.writers["feature"],
"ogc": OpenLayers.Format.Filter.v1_0_0.prototype.writers["ogc"]
},
CLASS_NAME: "OpenLayers.Format.WFST.v1_0_0"
});

View File

@ -1,137 +0,0 @@
/**
* @requires OpenLayers/Format/WFST/v1.js
* @requires OpenLayers/Format/Filter/v1_1_0.js
*/
/**
* Class: OpenLayers.Format.WFST.v1_1_0
* A format for creating WFS v1.1.0 transactions. Create a new instance with the
* <OpenLayers.Format.WFST.v1_1_0> constructor.
*
* Inherits from:
* - <OpenLayers.Format.Filter.v1_1_0>
* - <OpenLayers.Format.WFST.v1>
*/
OpenLayers.Format.WFST.v1_1_0 = OpenLayers.Class(
OpenLayers.Format.Filter.v1_1_0, OpenLayers.Format.WFST.v1, {
/**
* Property: version
* {String} WFS version number.
*/
version: "1.1.0",
/**
* Property: schemaLocations
* {Object} Properties are namespace aliases, values are schema locations.
*/
schemaLocations: {
"wfs": "http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"
},
/**
* Constructor: OpenLayers.Format.WFST.v1_1_0
* A class for parsing and generating WFS v1.1.0 transactions.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*
* Valid options properties:
* featureType - {String} Local (without prefix) feature typeName (required).
* featureNS - {String} Feature namespace (optional).
* featurePrefix - {String} Feature namespace alias (optional - only used
* if featureNS is provided). Default is 'feature'.
* geometryName - {String} Name of geometry attribute. Default is 'the_geom'.
*/
initialize: function(options) {
OpenLayers.Format.Filter.v1_1_0.prototype.initialize.apply(this, [options]);
OpenLayers.Format.WFST.v1.prototype.initialize.apply(this, [options]);
},
/**
* Property: readers
* Contains public functions, grouped by namespace prefix, that will
* be applied when a namespaced node is found matching the function
* name. The function will be applied in the scope of this parser
* with two arguments: the node being read and a context object passed
* from the parent.
*/
readers: {
"wfs": OpenLayers.Util.applyDefaults({
"TransactionResponse": function(node, obj) {
obj.insertIds = [];
obj.success = false;
this.readChildNodes(node, obj);
},
"TransactionSummary": function(node, obj) {
// this is a limited test of success
obj.success = true;
},
"InsertResults": function(node, obj) {
this.readChildNodes(node, obj);
},
"Feature": function(node, container) {
var obj = {fids: []};
this.readChildNodes(node, obj);
container.insertIds.push(obj.fids[0]);
}
}, OpenLayers.Format.WFST.v1.prototype.readers["wfs"]),
"gml": OpenLayers.Format.GML.v3.prototype.readers["gml"],
"feature": OpenLayers.Format.GML.v3.prototype.readers["feature"],
"ogc": OpenLayers.Format.Filter.v1_1_0.prototype.readers["ogc"]
},
/**
* Property: writers
* As a compliment to the readers property, this structure contains public
* writing functions grouped by namespace alias and named like the
* node names they produce.
*/
writers: {
"wfs": OpenLayers.Util.applyDefaults({
"Query": function(options) {
options = OpenLayers.Util.extend({
featureNS: this.featureNS,
featurePrefix: this.featurePrefix,
featureType: this.featureType,
srsName: this.srsName
}, options);
var node = this.createElementNSPlus("wfs:Query", {
attributes: {
typeName: (options.featureNS ? options.featurePrefix + ":" : "") +
options.featureType,
srsName: options.srsName
}
});
if(options.featureNS) {
node.setAttribute("xmlns:" + options.featurePrefix, options.featureNS);
}
if(options.propertyNames) {
for(var i=0,len = options.propertyNames.length; i<len; i++) {
this.writeNode(
"wfs:PropertyName",
{property: options.propertyNames[i]},
node
);
}
}
if(options.filter) {
this.setFilterProperty(options.filter);
this.writeNode("ogc:Filter", options.filter, node);
}
return node;
},
"PropertyName": function(obj) {
return this.createElementNSPlus("wfs:PropertyName", {
value: obj.property
});
}
}, OpenLayers.Format.WFST.v1.prototype.writers["wfs"]),
"gml": OpenLayers.Format.GML.v3.prototype.writers["gml"],
"feature": OpenLayers.Format.GML.v3.prototype.writers["feature"],
"ogc": OpenLayers.Format.Filter.v1_1_0.prototype.writers["ogc"]
},
CLASS_NAME: "OpenLayers.Format.WFST.v1_1_0"
});

View File

@ -1,353 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format.js
* @requires OpenLayers/Feature/Vector.js
*/
/**
* Class: OpenLayers.Format.WKT
* Class for reading and writing Well-Known Text. Create a new instance
* with the <OpenLayers.Format.WKT> constructor.
*
* Inherits from:
* - <OpenLayers.Format>
*/
OpenLayers.Format.WKT = OpenLayers.Class(OpenLayers.Format, {
/**
* Constructor: OpenLayers.Format.WKT
* Create a new parser for WKT
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance
*
* Returns:
* {<OpenLayers.Format.WKT>} A new WKT parser.
*/
initialize: function(options) {
this.regExes = {
'typeStr': /^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,
'spaces': /\s+/,
'parenComma': /\)\s*,\s*\(/,
'doubleParenComma': /\)\s*\)\s*,\s*\(\s*\(/, // can't use {2} here
'trimParens': /^\s*\(?(.*?)\)?\s*$/
};
OpenLayers.Format.prototype.initialize.apply(this, [options]);
},
/**
* Method: read
* Deserialize a WKT string and return a vector feature or an
* array of vector features. Supports WKT for POINT, MULTIPOINT,
* LINESTRING, MULTILINESTRING, POLYGON, MULTIPOLYGON, and
* GEOMETRYCOLLECTION.
*
* Parameters:
* wkt - {String} A WKT string
*
* Returns:
* {<OpenLayers.Feature.Vector>|Array} A feature or array of features for
* GEOMETRYCOLLECTION WKT.
*/
read: function(wkt) {
var features, type, str;
var matches = this.regExes.typeStr.exec(wkt);
if(matches) {
type = matches[1].toLowerCase();
str = matches[2];
if(this.parse[type]) {
features = this.parse[type].apply(this, [str]);
}
if (this.internalProjection && this.externalProjection) {
if (features &&
features.CLASS_NAME == "OpenLayers.Feature.Vector") {
features.geometry.transform(this.externalProjection,
this.internalProjection);
} else if (features &&
type != "geometrycollection" &&
typeof features == "object") {
for (var i=0, len=features.length; i<len; i++) {
var component = features[i];
component.geometry.transform(this.externalProjection,
this.internalProjection);
}
}
}
}
return features;
},
/**
* Method: write
* Serialize a feature or array of features into a WKT string.
*
* Parameters:
* features - {<OpenLayers.Feature.Vector>|Array} A feature or array of
* features
*
* Returns:
* {String} The WKT string representation of the input geometries
*/
write: function(features) {
var collection, geometry, type, data, isCollection;
if(features.constructor == Array) {
collection = features;
isCollection = true;
} else {
collection = [features];
isCollection = false;
}
var pieces = [];
if(isCollection) {
pieces.push('GEOMETRYCOLLECTION(');
}
for(var i=0, len=collection.length; i<len; ++i) {
if(isCollection && i>0) {
pieces.push(',');
}
geometry = collection[i].geometry;
type = geometry.CLASS_NAME.split('.')[2].toLowerCase();
if(!this.extract[type]) {
return null;
}
if (this.internalProjection && this.externalProjection) {
geometry = geometry.clone();
geometry.transform(this.internalProjection,
this.externalProjection);
}
data = this.extract[type].apply(this, [geometry]);
pieces.push(type.toUpperCase() + '(' + data + ')');
}
if(isCollection) {
pieces.push(')');
}
return pieces.join('');
},
/**
* Object with properties corresponding to the geometry types.
* Property values are functions that do the actual data extraction.
*/
extract: {
/**
* Return a space delimited string of point coordinates.
* @param {<OpenLayers.Geometry.Point>} point
* @returns {String} A string of coordinates representing the point
*/
'point': function(point) {
return point.x + ' ' + point.y;
},
/**
* Return a comma delimited string of point coordinates from a multipoint.
* @param {<OpenLayers.Geometry.MultiPoint>} multipoint
* @returns {String} A string of point coordinate strings representing
* the multipoint
*/
'multipoint': function(multipoint) {
var array = [];
for(var i=0, len=multipoint.components.length; i<len; ++i) {
array.push(this.extract.point.apply(this, [multipoint.components[i]]));
}
return array.join(',');
},
/**
* Return a comma delimited string of point coordinates from a line.
* @param {<OpenLayers.Geometry.LineString>} linestring
* @returns {String} A string of point coordinate strings representing
* the linestring
*/
'linestring': function(linestring) {
var array = [];
for(var i=0, len=linestring.components.length; i<len; ++i) {
array.push(this.extract.point.apply(this, [linestring.components[i]]));
}
return array.join(',');
},
/**
* Return a comma delimited string of linestring strings from a multilinestring.
* @param {<OpenLayers.Geometry.MultiLineString>} multilinestring
* @returns {String} A string of of linestring strings representing
* the multilinestring
*/
'multilinestring': function(multilinestring) {
var array = [];
for(var i=0, len=multilinestring.components.length; i<len; ++i) {
array.push('(' +
this.extract.linestring.apply(this, [multilinestring.components[i]]) +
')');
}
return array.join(',');
},
/**
* Return a comma delimited string of linear ring arrays from a polygon.
* @param {<OpenLayers.Geometry.Polygon>} polygon
* @returns {String} An array of linear ring arrays representing the polygon
*/
'polygon': function(polygon) {
var array = [];
for(var i=0, len=polygon.components.length; i<len; ++i) {
array.push('(' +
this.extract.linestring.apply(this, [polygon.components[i]]) +
')');
}
return array.join(',');
},
/**
* Return an array of polygon arrays from a multipolygon.
* @param {<OpenLayers.Geometry.MultiPolygon>} multipolygon
* @returns {Array} An array of polygon arrays representing
* the multipolygon
*/
'multipolygon': function(multipolygon) {
var array = [];
for(var i=0, len=multipolygon.components.length; i<len; ++i) {
array.push('(' +
this.extract.polygon.apply(this, [multipolygon.components[i]]) +
')');
}
return array.join(',');
}
},
/**
* Object with properties corresponding to the geometry types.
* Property values are functions that do the actual parsing.
*/
parse: {
/**
* Return point feature given a point WKT fragment.
* @param {String} str A WKT fragment representing the point
* @returns {<OpenLayers.Feature.Vector>} A point feature
* @private
*/
'point': function(str) {
var coords = OpenLayers.String.trim(str).split(this.regExes.spaces);
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(coords[0], coords[1])
);
},
/**
* Return a multipoint feature given a multipoint WKT fragment.
* @param {String} A WKT fragment representing the multipoint
* @returns {<OpenLayers.Feature.Vector>} A multipoint feature
* @private
*/
'multipoint': function(str) {
var points = OpenLayers.String.trim(str).split(',');
var components = [];
for(var i=0, len=points.length; i<len; ++i) {
components.push(this.parse.point.apply(this, [points[i]]).geometry);
}
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiPoint(components)
);
},
/**
* Return a linestring feature given a linestring WKT fragment.
* @param {String} A WKT fragment representing the linestring
* @returns {<OpenLayers.Feature.Vector>} A linestring feature
* @private
*/
'linestring': function(str) {
var points = OpenLayers.String.trim(str).split(',');
var components = [];
for(var i=0, len=points.length; i<len; ++i) {
components.push(this.parse.point.apply(this, [points[i]]).geometry);
}
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.LineString(components)
);
},
/**
* Return a multilinestring feature given a multilinestring WKT fragment.
* @param {String} A WKT fragment representing the multilinestring
* @returns {<OpenLayers.Feature.Vector>} A multilinestring feature
* @private
*/
'multilinestring': function(str) {
var line;
var lines = OpenLayers.String.trim(str).split(this.regExes.parenComma);
var components = [];
for(var i=0, len=lines.length; i<len; ++i) {
line = lines[i].replace(this.regExes.trimParens, '$1');
components.push(this.parse.linestring.apply(this, [line]).geometry);
}
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiLineString(components)
);
},
/**
* Return a polygon feature given a polygon WKT fragment.
* @param {String} A WKT fragment representing the polygon
* @returns {<OpenLayers.Feature.Vector>} A polygon feature
* @private
*/
'polygon': function(str) {
var ring, linestring, linearring;
var rings = OpenLayers.String.trim(str).split(this.regExes.parenComma);
var components = [];
for(var i=0, len=rings.length; i<len; ++i) {
ring = rings[i].replace(this.regExes.trimParens, '$1');
linestring = this.parse.linestring.apply(this, [ring]).geometry;
linearring = new OpenLayers.Geometry.LinearRing(linestring.components);
components.push(linearring);
}
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon(components)
);
},
/**
* Return a multipolygon feature given a multipolygon WKT fragment.
* @param {String} A WKT fragment representing the multipolygon
* @returns {<OpenLayers.Feature.Vector>} A multipolygon feature
* @private
*/
'multipolygon': function(str) {
var polygon;
var polygons = OpenLayers.String.trim(str).split(this.regExes.doubleParenComma);
var components = [];
for(var i=0, len=polygons.length; i<len; ++i) {
polygon = polygons[i].replace(this.regExes.trimParens, '$1');
components.push(this.parse.polygon.apply(this, [polygon]).geometry);
}
return new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiPolygon(components)
);
},
/**
* Return an array of features given a geometrycollection WKT fragment.
* @param {String} A WKT fragment representing the geometrycollection
* @returns {Array} An array of OpenLayers.Feature.Vector
* @private
*/
'geometrycollection': function(str) {
// separate components of the collection with |
str = str.replace(/,\s*([A-Za-z])/g, '|$1');
var wktArray = OpenLayers.String.trim(str).split('|');
var components = [];
for(var i=0, len=wktArray.length; i<len; ++i) {
components.push(OpenLayers.Format.WKT.prototype.read.apply(this,[wktArray[i]]));
}
return components;
}
},
CLASS_NAME: "OpenLayers.Format.WKT"
});

View File

@ -1,214 +0,0 @@
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML.js
*/
/**
* Class: OpenLayers.Format.WMC
* Read and write Web Map Context documents.
*
* Inherits from:
* - <OpenLayers.Format.XML>
*/
OpenLayers.Format.WMC = OpenLayers.Class({
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.1.0".
*/
defaultVersion: "1.1.0",
/**
* APIProperty: version
* {String} Specify a version string if one is known.
*/
version: null,
/**
* Property: layerOptions
* {Object} Default options for layers created by the parser. These
* options are overridden by the options which are read from the
* capabilities document.
*/
layerOptions: null,
/**
* Property: layerParams
* {Object} Default parameters for layers created by the parser. This
* can be used to override DEFAULT_PARAMS for OpenLayers.Layer.WMS.
*/
layerParams: null,
/**
* Property: parser
* {Object} Instance of the versioned parser. Cached for multiple read and
* write calls of the same version.
*/
parser: null,
/**
* Constructor: OpenLayers.Format.WMC
* Create a new parser for WMC docs.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(options) {
OpenLayers.Util.extend(this, options);
this.options = options;
},
/**
* APIMethod: read
* Read WMC data from a string, and return an object with map properties
* and a list of layers.
*
* Parameters:
* data - {String} or {DOMElement} data to read/parse.
* options - {Object} The options object must contain a map property. If
* the map property is a string, it must be the id of a dom element
* where the new map will be placed. If the map property is an
* <OpenLayers.Map>, the layers from the context document will be added
* to the map.
*
* Returns:
* {<OpenLayers.Map>} A map based on the context.
*/
read: function(data, options) {
if(typeof data == "string") {
data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
}
var root = data.documentElement;
var version = this.version;
if(!version) {
version = root.getAttribute("version");
if(!version) {
version = this.defaultVersion;
}
}
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.WMC[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a WMC parser for version " +
version;
}
this.parser = new format(this.options);
}
var context = this.parser.read(data, options);
var map;
if(options.map) {
this.context = context;
if(options.map instanceof OpenLayers.Map) {
map = this.mergeContextToMap(context, options.map);
} else {
map = this.contextToMap(context, options.map);
}
} else {
// not documented as part of the API, provided as a non-API option
map = context;
}
return map;
},
/**
* Method: contextToMap
* Create a map given a context object.
*
* Parameters:
* context - {Object} The context object.
* id - {String | Element} The dom element or element id that will contain
* the map.
*
* Returns:
* {<OpenLayers.Map>} A map based on the context object.
*/
contextToMap: function(context, id) {
var map = new OpenLayers.Map(id, {
maxExtent: context.maxExtent,
projection: context.projection
});
map.addLayers(context.layers);
map.setCenter(
context.bounds.getCenterLonLat(),
map.getZoomForExtent(context.bounds, true)
);
return map;
},
/**
* Method: mergeContextToMap
* Add layers from a context object to a map.
*
* Parameters:
* context - {Object} The context object.
* map - {<OpenLayers.Map>} The map.
*
* Returns:
* {<OpenLayers.Map>} The same map with layers added.
*/
mergeContextToMap: function(context, map) {
map.addLayers(context.layers);
return map;
},
/**
* APIMethod: write
* Write a WMC document given a map.
*
* Parameters:
* obj - {<OpenLayers.Map> | Object} A map or context object.
* options - {Object} Optional configuration object.
*
* Returns:
* {String} A WMC document string.
*/
write: function(obj, options) {
if(obj.CLASS_NAME == "OpenLayers.Map") {
obj = this.mapToContext(obj);
}
var version = (options && options.version) ||
this.version || this.defaultVersion;
if(!this.parser || this.parser.VERSION != version) {
var format = OpenLayers.Format.WMC[
"v" + version.replace(/\./g, "_")
];
if(!format) {
throw "Can't find a WMS capabilities parser for version " +
version;
}
this.parser = new format(this.options);
}
var wmc = this.parser.write(obj, options);
return wmc;
},
/**
* Method: mapToContext
* Create a context object given a map.
*
* Parameters:
* map - {<OpenLayers.Map>} The map.
*
* Returns:
* {Object} A context object.
*/
mapToContext: function(map) {
var context = {
bounds: map.getExtent(),
maxExtent: map.maxExtent,
projection: map.projection,
layers: map.layers,
size: map.getSize()
};
return context;
},
CLASS_NAME: "OpenLayers.Format.WMC"
});

Some files were not shown because too many files have changed in this diff Show More