2010-01-18 Miguel de Dios <miguel.dedios@artica.es>

* include/javascript/OpenLayers/*: clean and reduce the size of distribution
	of OpenLayers.



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@2286 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
This commit is contained in:
mdtrooper 2010-01-18 16:36:00 +00:00
parent 74ef6bfeb0
commit 827344056a
203 changed files with 0 additions and 41261 deletions

View File

@ -1,27 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Ajax_loadUrl(t) {
t.plan(5);
var _get = OpenLayers.Request.GET;
var caller = {};
var onComplete = function() {};
var onFailure = function() {};
var params = {};
OpenLayers.Request.GET = function(config) {
t.eq(config.url, "http://example.com/?format=image+kml", "correct url")
t.eq(config.params, params, "correct params");
t.eq(config.scope, caller, "correct scope");
t.ok(config.success === onComplete, "correct success callback");
t.ok(config.failure === onFailure, "correct failure callback");
};
OpenLayers.loadURL("http://example.com/?format=image+kml", params, caller, onComplete, onFailure);
OpenLayers.Request.GET = _get;
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,366 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_String_startsWith(t) {
t.plan(3);
var str = "chickenHead";
var test1 = "chicken";
var test2 = "beet";
t.ok(OpenLayers.String.startsWith(str, "chicken"),
"'chickenHead' starts with 'chicken'");
t.ok(!OpenLayers.String.startsWith(str, "Head"),
"'chickenHead' does not start with 'Head'");
t.ok(!OpenLayers.String.startsWith(str, "beet"),
"'chickenHead' doesnt start with 'beet'");
}
function test_String_contains(t) {
t.plan(4);
var str = "chickenHead";
t.ok(OpenLayers.String.contains(str, "chicken"),
"(beginning) 'chickenHead' contains with 'chicken'");
t.ok(OpenLayers.String.contains(str, "ick"),
"(middle) 'chickenHead' contains with 'ick'");
t.ok(OpenLayers.String.contains(str, "Head"),
"(end) 'chickenHead' contains with 'Head'");
t.ok(!OpenLayers.String.startsWith(str, "beet"),
"'chickenHead' doesnt start with 'beet'");
}
function test_String_trim(t) {
t.plan(6);
var str = "chickenHead";
t.eq(OpenLayers.String.trim(str),
"chickenHead", "string with no extra whitespace is left alone");
str = " chickenHead";
t.eq(OpenLayers.String.trim(str),
"chickenHead", "string with extra whitespace at beginning is trimmed correctly");
str = "chickenHead ";
t.eq(OpenLayers.String.trim(str),
"chickenHead", "string with extra whitespace at end is trimmed correctly");
str = " chickenHead ";
t.eq(OpenLayers.String.trim(str),
"chickenHead", "string with extra whitespace at beginning and end is trimmed correctly");
str = "chicken\nHead ";
t.eq(OpenLayers.String.trim(str),
"chicken\nHead", "multi-line string with extra whitespace at end is trimmed correctly");
str = " ";
t.eq(OpenLayers.String.trim(str), "", "whitespace string is trimmed correctly");
}
function test_String_camelize(t) {
t.plan(7);
var str = "chickenhead";
t.eq(OpenLayers.String.camelize(str), "chickenhead", "string with no hyphens is left alone");
str = "chicken-head";
t.eq(OpenLayers.String.camelize(str), "chickenHead", "string with one middle hyphen is camelized correctly");
str = "chicken-head-man";
t.eq(OpenLayers.String.camelize(str), "chickenHeadMan", "string with multiple middle hyphens is camelized correctly");
str = "-chickenhead";
t.eq(OpenLayers.String.camelize(str), "Chickenhead", "string with starting hyphen is camelized correctly (capitalized)");
str = "-chicken-head-man";
t.eq(OpenLayers.String.camelize(str), "ChickenHeadMan", "string with starting hypen and multiple middle hyphens is camelized correctly");
str = "chicken-";
t.eq(OpenLayers.String.camelize(str), "chicken", "string ending in hyphen is camelized correctly (hyphen dropped)");
str = "chicken-head-man-";
t.eq(OpenLayers.String.camelize(str), "chickenHeadMan", "string with multiple middle hyphens and end hyphen is camelized correctly (end hyphen dropped)");
}
function test_String_format(t) {
var unchanged = [
"", "${ ", "${", " ${", "${${", "${}", "${${}}", " ${ ${",
"}", "${${} }"
]
t.plan(7 + unchanged.length);
var format = OpenLayers.String.format;
var expected;
for(var i=0; i<unchanged.length; ++i) {
expected = unchanged[i];
t.eq(format(expected), expected,
"'" + expected + "' left unchanged");
}
t.eq(format("${foo} none"),
"undefined none", "undefined properties don't bomb");
window.foo = "bar";
t.eq(format("${foo} none"),
"bar none", "window context used if none passed");
var context = {bar: "foo"};
t.eq(format("${bar} foo", context), "foo foo",
"properties accessed from context");
var context = {bar: "foo", foo: "bar"};
t.eq(format("a ${bar} is a ${foo}", context), "a foo is a bar",
"multiple properties replaced correctly");
// test context with properties that are functions
var context = {
bar: "church",
getDrunk: function() {
return arguments[0];
}
};
t.eq(
format("I go to the ${bar} to ${getDrunk}.", context, ["eat pretzels"]),
"I go to the church to eat pretzels.",
"function correctly called in context with arguments"
);
// test that things don't break
var context = {
meaning: function(truth) {
return truth;
}
};
t.eq(
format("In life, truth is ${meaning}.", context),
"In life, truth is undefined.",
"still works if arguments are not supplied"
);
// test contexts where attribute values can be objects
var context = {
a: {
b: {
c: 'd',
e: function() {
return 'f';
}
}
}
};
t.eq(
format("${a.b.c} ${a.b.e} ${a.b.q} ${a} ${a...b...c}", context),
"d f undefined [object Object] d",
"attribute values that are objects are supported"
);
}
function test_String_isNumeric(t) {
var cases = [
{value: "3", expect: true},
{value: "+3", expect: true},
{value: "-3", expect: true},
{value: "3.0", expect: true},
{value: "+3.0", expect: true},
{value: "-3.0", expect: true},
{value: "6.02e23", expect: true},
{value: "+1.0e-100", expect: true},
{value: "-1.0e+100", expect: true},
{value: "1E100", expect: true},
{value: null, expect: false},
{value: true, expect: false},
{value: false, expect: false},
{value: undefined, expect: false},
{value: "", expect: false},
{value: "3 ", expect: false},
{value: " 3", expect: false},
{value: "1e", expect: false},
{value: "1+e", expect: false},
{value: "1-e", expect: false}
];
t.plan(cases.length);
var func = OpenLayers.String.isNumeric;
var obj, val, got, exp;
for(var i=0; i<cases.length; ++i) {
obj = cases[i];
val = obj.value;
exp = obj.expect;
got = func(val);
t.eq(got, exp, "'" + val + "' returns " + exp);
}
}
function test_Number_numericIf(t) {
var cases = [
{value: "3", expect: 3},
{value: "+3", expect: 3},
{value: "-3", expect: -3},
{value: "3.0", expect: 3},
{value: "+3.0", expect: 3},
{value: "-3.0", expect: -3},
{value: "6.02e23", expect: 6.02e23},
{value: "+1.0e-100", expect: 1e-100},
{value: "-1.0e+100", expect: -1e100},
{value: "1E100", expect: 1e100},
{value: null, expect: null},
{value: true, expect: true},
{value: false, expect: false},
{value: undefined, expect: undefined},
{value: "", expect: ""},
{value: "3 ", expect: "3 "},
{value: " 3", expect: " 3"},
{value: "1e", expect: "1e"},
{value: "1+e", expect: "1+e"},
{value: "1-e", expect: "1-e"}
];
t.plan(cases.length);
var func = OpenLayers.String.numericIf;
var obj, val, got, exp;
for(var i=0; i<cases.length; ++i) {
obj = cases[i];
val = obj.value;
exp = obj.expect;
got = func(val);
t.eq(got, exp, "'" + val + "' returns " + exp);
}
}
function test_Number_limitSigDigs(t) {
t.plan(9);
var num = 123456789;
t.eq(OpenLayers.Number.limitSigDigs(num), 0, "passing 'null' as sig returns 0");
t.eq(OpenLayers.Number.limitSigDigs(num, -1), 0, "passing -1 as sig returns 0");
t.eq(OpenLayers.Number.limitSigDigs(num, 0), 0, "passing 0 as sig returns 0");
t.eq(OpenLayers.Number.limitSigDigs(num, 15), 123456789, "passing sig greater than num digits in number returns number unmodified");
t.eq(OpenLayers.Number.limitSigDigs(num, 1), 100000000, "passing sig 1 works");
t.eq(OpenLayers.Number.limitSigDigs(num, 3), 123000000, "passing middle sig works (rounds down)");
t.eq(OpenLayers.Number.limitSigDigs(num, 5), 123460000, "passing middle sig works (rounds up)");
t.eq(OpenLayers.Number.limitSigDigs(num, 9), 123456789, "passing sig equal to num digits in number works");
num = 1234.56789;
t.eq(OpenLayers.Number.limitSigDigs(num, 5), 1234.6, "running limSigDig() on a floating point number works fine");
}
function test_Number_format(t) {
t.plan(9);
var format = OpenLayers.Number.format;
t.eq(format(12345), "12,345", "formatting an integer number works");
t.eq(format(12345, 3), "12,345.000", "zero padding an integer works");
t.eq(format(12345, null, ","), "12,345", "adding thousands separator to an integer works");
t.eq(format(12345, 0, ","), "12,345", "adding thousands separator to an integer with defined 0 decimal places works");
var num = 12345.6789
t.eq(format(num, null, "", ","), "12345,6789", "only changing decimal separator and leaving everything else untouched works");
t.eq(format(num, 5), "12,345.67890", "filling up decimals with trailing zeroes works");
t.eq(format(num, 3, ".", ","), "12.345,679", "rounding and changing decimal/thousands separator in function call works");
t.eq(format(num, 0, ""), "12346", "empty thousands separator in function call works");
OpenLayers.Number.thousandsSeparator = ".";
OpenLayers.Number.decimalSeparator = ",";
t.eq(format(num, 3), "12.345,679", "changing thousands/decimal separator globally works");
}
function test_Function_bind(t) {
t.plan(12);
g_obj = {};
g_Arg1 = {};
g_Arg2 = {};
g_Arg3 = {};
g_Arg4 = {};
var foo = function(x,y,z,a) {
t.ok(this == g_obj, "context correctly set");
t.ok(x == g_Arg1, "arg1 passed correctly");
t.ok(y == g_Arg2, "arg2 passed correctly");
t.ok(z == g_Arg3, "arg3 passed correctly");
t.ok(a == g_Arg4, "arg4 passed correctly");
t.eq(arguments.length, 4, "correct number of arguments ((regression test for #876))");
};
var newFoo = OpenLayers.Function.bind(foo, g_obj, g_Arg1, g_Arg2);
newFoo(g_Arg3, g_Arg4);
//run again to make sure the arguments are handled correctly
newFoo(g_Arg3, g_Arg4);
}
function test_Function_bindAsEventListener(t) {
t.plan(4);
g_obj = {};
g_Event = {};
g_WindowEvent = {};
var foo = function(x) {
t.ok(this == g_obj, "context correctly set");
g_X = x;
};
var newFoo = OpenLayers.Function.bindAsEventListener(foo, g_obj);
g_X = null;
newFoo(g_Event);
t.ok(g_X == g_Event, "event properly passed as first argument when event specified");
g_X = null;
newFoo();
t.ok(g_X == window.event, "window.event properly passed as first argument when nothing specified");
}
function test_Array_filter(t) {
t.plan(8);
OpenLayers.Array.filter(["foo"], function(item, index, array) {
t.eq(item, "foo", "callback called with proper item");
t.eq(index, 0, "callback called with proper index");
t.eq(array, ["foo"], "callback called with proper array");
t.eq(this, {"foo": "bar"}, "callback called with this set properly");
}, {"foo": "bar"});
var array = [0, 1, 2, 3];
var select = OpenLayers.Array.filter(array, function(value) {
return value > 1;
});
t.eq(select, [2, 3], "filter works for basic callback");
t.eq(array, [0, 1, 2, 3], "filter doesn't modify original");
var obj = {
test: function(value) {
if(value > 1) {
return true;
}
}
};
var select = OpenLayers.Array.filter(array, function(value) {
return this.test(value);
}, obj);
t.eq(select, [2, 3], "filter works for callback and caller");
t.eq(array, [0, 1, 2, 3], "filter doesn't modify original");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,637 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var bounds;
function test_Bounds_constructor (t) {
t.plan( 21 );
bounds = new OpenLayers.Bounds();
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.CLASS_NAME, "OpenLayers.Bounds", "bounds.CLASS_NAME is set correctly" );
t.eq( bounds.left, null, "bounds.left is initialized to null" );
t.eq( bounds.bottom, null, "bounds.bottom is initialized to null" );
t.eq( bounds.right, null, "bounds.right is initialized to null" );
t.eq( bounds.top, null, "bounds.top is initialized to null" );
bounds = new OpenLayers.Bounds(0,2,10,4);
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.CLASS_NAME, "OpenLayers.Bounds", "bounds.CLASS_NAME is set correctly" );
t.eq( bounds.left, 0, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 10, "bounds.right is set correctly" );
t.eq( bounds.top, 4, "bounds.top is set correctly" );
t.eq( bounds.getWidth(), 10, "bounds.getWidth() returns correct value" );
t.eq( bounds.getHeight(), 2, "bounds.getHeight() returns correct value" );
var sz = bounds.getSize();
var size = new OpenLayers.Size(10,2);
t.ok(sz.equals(size),"bounds.getSize() has correct value" );
var center = new OpenLayers.Pixel(5,3);
var boundsCenter = bounds.getCenterPixel();
t.ok( boundsCenter.equals(center), "bounds.getCenterLonLat() has correct value" );
var center = new OpenLayers.LonLat(5,3);
var boundsCenter = bounds.getCenterLonLat();
t.ok( boundsCenter.equals(center), "bounds.getCenterLonLat() has correct value" );
// This is an actual use case with Mercator projection at global scale
bounds = new OpenLayers.Bounds(-40075016.67999999,-20037508.339999992,
40075016.67999999,20037508.339999992);
t.eq( bounds.left, -40075016.68, "bounds.left adjusted for floating precision");
t.eq( bounds.bottom, -20037508.34, "bounds.bottom adjusted for floating precision");
t.eq( bounds.right, 40075016.68, "bounds.right adjusted for floating precision");
t.eq( bounds.top, 20037508.34, "bounds.top adjusted for floating precision");
}
function test_Bounds_constructorFromStrings(t) {
t.plan( 6 );
bounds = new OpenLayers.Bounds("0","2","10","4");
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.CLASS_NAME, "OpenLayers.Bounds", "bounds.CLASS_NAME is set correctly" );
t.eq( bounds.left, 0, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 10, "bounds.right is set correctly" );
t.eq( bounds.top, 4, "bounds.top is set correctly" );
}
function test_Bounds_toBBOX(t) {
t.plan( 5 );
bounds = new OpenLayers.Bounds(1,2,3,4);
t.eq( bounds.toBBOX(), "1,2,3,4", "toBBOX() returns correct value." );
bounds = new OpenLayers.Bounds(1.00000001,2,3,4);
t.eq( bounds.toBBOX(), "1,2,3,4", "toBBOX() rounds off small differences." );
bounds = new OpenLayers.Bounds(1.00000001,2.5,3,4);
t.eq( bounds.toBBOX(), "1,2.5,3,4", "toBBOX() returns correct value. for a half number" );
bounds = new OpenLayers.Bounds(1,2.5555555,3,4);
t.eq( bounds.toBBOX(), "1,2.555556,3,4", "toBBOX() rounds to correct value." );
bounds = new OpenLayers.Bounds(1,2.5555555,3,4);
t.eq( bounds.toBBOX(1), "1,2.6,3,4", "toBBOX() rounds to correct value with power provided." );
bounds = new OpenLayers.Bounds(1,2.5555555,3,4);
}
function test_Bounds_toString(t) {
t.plan( 1 );
bounds = new OpenLayers.Bounds(1,2,3,4);
t.eq( bounds.toString(), "left-bottom=(1,2) right-top=(3,4)", "toString() returns correct value." );
}
function test_Bounds_toArray(t) {
t.plan( 1 );
bounds = new OpenLayers.Bounds(1,2,3,4);
t.eq( bounds.toArray(), [1,2,3,4], "toArray() returns correct value." );
}
function test_Bounds_toGeometry(t) {
t.plan(7);
var minx = Math.random();
var miny = Math.random();
var maxx = Math.random();
var maxy = Math.random();
var bounds = new OpenLayers.Bounds(minx, miny, maxx, maxy);
var poly = bounds.toGeometry();
t.eq(poly.CLASS_NAME, "OpenLayers.Geometry.Polygon",
"polygon instance created");
t.eq(poly.components.length, 1,
"polygon with one ring created");
var ring = poly.components[0];
t.eq(ring.components.length, 5,
"four sided polygon created");
t.eq(ring.components[0].x, OpenLayers.Util.toFloat(minx),
"bounds left preserved");
t.eq(ring.components[0].y, OpenLayers.Util.toFloat(miny),
"bounds bottom preserved");
t.eq(ring.components[2].x, OpenLayers.Util.toFloat(maxx),
"bounds left preserved");
t.eq(ring.components[2].y, OpenLayers.Util.toFloat(maxy),
"bounds bottom preserved");
}
function test_Bounds_contains(t) {
t.plan( 6 );
bounds = new OpenLayers.Bounds(10,10,40,40);
t.eq( bounds.contains(20,20), true, "bounds(10,10,40,40) correctly contains LonLat(20,20)" );
t.eq( bounds.contains(0,0), false, "bounds(10,10,40,40) correctly does not contain LonLat(0,0)" );
t.eq( bounds.contains(40,40), true, "bounds(10,10,40,40) correctly contains LonLat(40,40) with inclusive set to true" );
t.eq( bounds.contains(40,40, false), false, "bounds(10,10,40,40) correctly does not contain LonLat(40,40) with inclusive set to false" );
var px = new OpenLayers.Pixel(15,30);
t.eq( bounds.containsPixel(px), bounds.contains(px.x, px.y), "containsPixel works");
var ll = new OpenLayers.LonLat(15,30);
t.eq( bounds.containsLonLat(ll), bounds.contains(ll.lon, ll.lat), "containsLonLat works");
}
function test_Bounds_fromString(t) {
t.plan( 10 );
bounds = OpenLayers.Bounds.fromString("1,2,3,4");
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.left, 1, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 3, "bounds.right is set correctly" );
t.eq( bounds.top, 4, "bounds.top is set correctly" );
bounds = OpenLayers.Bounds.fromString("1.1,2.2,3.3,4.4");
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.left, 1.1, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2.2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 3.3, "bounds.right is set correctly" );
t.eq( bounds.top, 4.4, "bounds.top is set correctly" );
}
function test_Bounds_getSize(t) {
t.plan( 1 );
var bounds = new OpenLayers.Bounds(0,10,100,120);
t.ok( bounds.getSize().equals(new OpenLayers.Size(100, 110)), "getCenterPixel() works correctly");
}
function test_Bounds_clone(t) {
t.plan( 6 );
var oldBounds = new OpenLayers.Bounds(1,2,3,4);
var bounds = oldBounds.clone();
t.ok( bounds instanceof OpenLayers.Bounds, "clone returns new OpenLayers.Bounds object" );
t.eq( bounds.left, 1, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 3, "bounds.right is set correctly" );
t.eq( bounds.top, 4, "bounds.top is set correctly" );
oldBounds.left = 100;
t.eq( bounds.left, 1, "changing olBounds.left does not change bounds.left" );
}
function test_Bounds_intersectsBounds(t) {
t.plan(21);
var aBounds = new OpenLayers.Bounds(-180, -90, 180, 90);
//inside
var bBounds = new OpenLayers.Bounds(-20, -10, 20, 10);
var cBounds = new OpenLayers.Bounds(-181,-90,180,90);
t.eq( aBounds.intersectsBounds(bBounds), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + ")" );
t.eq( aBounds.intersectsBounds(bBounds, true), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is true" );
t.eq( aBounds.intersectsBounds(bBounds, false), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is false" );
t.eq( aBounds.intersectsBounds(cBounds, false), true, "aBounds with cBounds adjusted one degree left passes intersect bounds. (3 sides match, 1 side different)." );
t.eq( cBounds.intersectsBounds(aBounds, false), true, "cBounds with aBounds adjusted one degree left passes intersect bounds. (3 sides match, 1 side different)." );
//outside
bBounds = new OpenLayers.Bounds(-181, -91, 181, 91);
t.eq( aBounds.intersectsBounds(bBounds), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + ")" );
t.eq( aBounds.intersectsBounds(bBounds, true), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is true" );
t.eq( aBounds.intersectsBounds(bBounds, false), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is false" );
//total intersect
bBounds = new OpenLayers.Bounds(-185, -100, 20, 50);
t.eq( aBounds.intersectsBounds(bBounds), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + ")" );
t.eq( aBounds.intersectsBounds(bBounds, true), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is true" );
t.eq( aBounds.intersectsBounds(bBounds, false), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is false" );
//border intersect
bBounds = new OpenLayers.Bounds(-360, -180, -180, -90);
t.eq( aBounds.intersectsBounds(bBounds), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + ")" );
t.eq( aBounds.intersectsBounds(bBounds, true), true, "(" + aBounds.toBBOX() + ") correctly intersects (" + bBounds.toBBOX() + "), inclusive is true" );
t.eq( aBounds.intersectsBounds(bBounds, false), false, "(" + aBounds.toBBOX() + ") does not intersect (" + bBounds.toBBOX() + "), inclusive is false" );
//no intersect
bBounds = new OpenLayers.Bounds(-360, -180, -185, -95);
t.eq( aBounds.intersectsBounds(bBounds), false, "(" + aBounds.toBBOX() + ") does not intersect (" + bBounds.toBBOX() + ")" );
t.eq( aBounds.intersectsBounds(bBounds, true), false, "(" + aBounds.toBBOX() + ") does not intersect (" + bBounds.toBBOX() + "), inclusive is true" );
t.eq( aBounds.intersectsBounds(bBounds, false), false, "(" + aBounds.toBBOX() + ") does not intersect (" + bBounds.toBBOX() + "), inclusive is false" );
// This is an actual use case with Mercator tiles at global scale
var merc_aBounds = new OpenLayers.Bounds(-40075016.67999999,20037508.339999992,
-20037508.339999992,40075016.67999999),
merc_bBounds = new OpenLayers.Bounds(-20037508.34,-20037508.34,
20037508.34,20037508.34);
t.eq( merc_aBounds.intersectsBounds(merc_bBounds, true), true, "intersect shouldn't fall prey to floating point errors, inclusive is true");
t.eq( merc_aBounds.intersectsBounds(merc_bBounds, false), false, "intersect shouldn't fall prey to floating point errors, inclusive is false");
// test for bounds intersection where none of the corners are contained within the other bounds
var b1 = new OpenLayers.Bounds(-1, -2, 1, 2);
var b2 = new OpenLayers.Bounds(-2, -1, 2, 1);
t.eq(b1.intersectsBounds(b2), true, "vertical rectangle intersects horizontal rectangle");
t.eq(b2.intersectsBounds(b1), true, "horizontal rectangle intersects vertical rectangle");
}
function test_Bounds_containsBounds(t) {
t.plan( 35 );
containerBounds = new OpenLayers.Bounds(10,10,40,40);
//totally outside
bounds = new OpenLayers.Bounds(0,0,5,5);
t.eq( containerBounds.containsBounds(bounds) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ")");
t.eq( containerBounds.containsBounds(bounds, false) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false" );
t.eq( containerBounds.containsBounds(bounds, false, true) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, false, false), false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is false" );
t.eq( containerBounds.containsBounds(bounds, true) , false , "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is true" );
t.eq( containerBounds.containsBounds(bounds, true, true) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is true, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, true, false) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is true, inclusive is false" );
//totally outside on border
bounds = new OpenLayers.Bounds(15,0,30,10);
t.eq( containerBounds.containsBounds(bounds) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ")");
t.eq( containerBounds.containsBounds(bounds, false) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false" );
t.eq( containerBounds.containsBounds(bounds, false, true) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, false, false), false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is false" );
t.eq( containerBounds.containsBounds(bounds, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true" );
t.eq( containerBounds.containsBounds(bounds, true, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, true, false) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is true, inclusive is false" );
//partially inside
bounds = new OpenLayers.Bounds(20,20,50,30);
t.eq( containerBounds.containsBounds(bounds) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ")");
t.eq( containerBounds.containsBounds(bounds, false) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false" );
t.eq( containerBounds.containsBounds(bounds, false, true) , false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, false, false), false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is false" );
t.eq( containerBounds.containsBounds(bounds, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true" );
t.eq( containerBounds.containsBounds(bounds, true, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, true, false) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is false" );
//totally inside on border
bounds = new OpenLayers.Bounds(10,20,30,30);
t.eq( containerBounds.containsBounds(bounds) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ")");
t.eq( containerBounds.containsBounds(bounds, false) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is false" );
t.eq( containerBounds.containsBounds(bounds, false, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is false, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, false, false), false, "(" + containerBounds.toBBOX() + ") correctly does not contain (" + bounds.toBBOX() + ") when partial is false, inclusive is false" );
t.eq( containerBounds.containsBounds(bounds, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true" );
t.eq( containerBounds.containsBounds(bounds, true, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, true, false) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is false" );
//totally inside
bounds = new OpenLayers.Bounds(20,20,30,30);
t.eq( containerBounds.containsBounds(bounds) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ")");
t.eq( containerBounds.containsBounds(bounds, false) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is false" );
t.eq( containerBounds.containsBounds(bounds, false, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is false, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, false, false), true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is false, inclusive is false" );
t.eq( containerBounds.containsBounds(bounds, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true" );
t.eq( containerBounds.containsBounds(bounds, true, true) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is true" );
t.eq( containerBounds.containsBounds(bounds, true, false) , true, "(" + containerBounds.toBBOX() + ") correctly contains (" + bounds.toBBOX() + ") when partial is true, inclusive is false" );
}
function test_Bounds_determineQuadrant(t) {
t.plan( 4 );
var bounds = new OpenLayers.Bounds(0,0,100,100);
var tl = new OpenLayers.LonLat(25, 75);
var tr = new OpenLayers.LonLat(75, 75);
var bl = new OpenLayers.LonLat(25, 25);
var br = new OpenLayers.LonLat(75, 25);
t.eq( bounds.determineQuadrant(tl), "tl", "bounds.determineQuadrant correctly identifies a coordinate in the top left quadrant");
t.eq( bounds.determineQuadrant(tr), "tr", "bounds.determineQuadrant correctly identifies a coordinate in the top right quadrant");
t.eq( bounds.determineQuadrant(bl), "bl", "bounds.determineQuadrant correctly identifies a coordinate in the bottom left quadrant");
t.eq( bounds.determineQuadrant(br), "br", "bounds.determineQuadrant correctly identifies a coordinate in the bottom right quadrant");
}
function test_Bounds_oppositeQuadrant(t) {
t.plan( 4 );
t.eq( OpenLayers.Bounds.oppositeQuadrant("tl"), "br", "OpenLayers.Bounds.oppositeQuadrant returns 'br' for 'tl'");
t.eq( OpenLayers.Bounds.oppositeQuadrant("tr"), "bl", "OpenLayers.Bounds.oppositeQuadrant returns 'bl' for 'tr'");
t.eq( OpenLayers.Bounds.oppositeQuadrant("bl"), "tr", "OpenLayers.Bounds.oppositeQuadrant returns 'tr' for 'bl'");
t.eq( OpenLayers.Bounds.oppositeQuadrant("br"), "tl", "OpenLayers.Bounds.oppositeQuadrant returns 'tl' for 'br'");
}
function test_Bounds_equals(t) {
t.plan( 3 );
var boundsA = new OpenLayers.Bounds(1,2,3,4);
var boundsB = new OpenLayers.Bounds(1,2,3,4);
var boundsC = new OpenLayers.Bounds(1,5,3,4);
t.ok( boundsA.equals(boundsB), "equals() returns true on two equal bounds." );
t.ok( !boundsA.equals(boundsC), "equals() returns false on two different bounds." );
t.ok( !boundsA.equals(null), "equals() returns false on comparison to null");
}
function test_Bounds_getHeight_getWidth(t) {
t.plan( 2 );
var bounds = new OpenLayers.Bounds(10,20,100,120);
t.eq( bounds.getWidth(), 90, "getWidth() works" );
t.eq( bounds.getHeight(), 100, "getHeight() works" );
}
function test_Bounds_getCenters(t) {
t.plan( 2 );
var bounds = new OpenLayers.Bounds(0,20,100,120);
t.ok( bounds.getCenterPixel().equals(new OpenLayers.Pixel(50, 70)), "getCenterPixel() works correctly");
t.ok( bounds.getCenterLonLat().equals(new OpenLayers.LonLat(50, 70)), "getCenterLonLat() works correctly");
}
function test_getCenterLonLat(t) {
t.plan(7);
var bounds = new OpenLayers.Bounds(0, 10, 20, 60);
// set private centerLonLat to confirm that it is getting returned if set
bounds.centerLonLat = "foo";
t.eq(bounds.getCenterLonLat(), "foo", "returns cached value");
bounds.centerLonLat = null;
// unmodified
var center = bounds.getCenterLonLat();
t.eq(center.lon, 10, "unmodified: correct x");
t.eq(center.lat, 35, "unmodified: correct y");
// transformed
bounds.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
center = bounds.getCenterLonLat();
t.eq(Math.round(center.lon), 1113195, "transformed: correct x");
t.eq(Math.round(center.lat), 4759314, "transformed: correct y");
// extended
bounds.extend(new OpenLayers.Bounds(-10000000, -10000000, 10000000, 10000000));
center = bounds.getCenterLonLat();
t.eq(center.lon, 0, "extended: correct x");
t.eq(center.lat, 0, "extended: correct y");
}
function test_Bounds_fromArray(t) {
t.plan( 5 );
var bbox = [1,2,3,4];
bounds = OpenLayers.Bounds.fromArray(bbox);
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.left, 1, "bounds.left is set correctly" );
t.eq( bounds.bottom, 2, "bounds.bottom is set correctly" );
t.eq( bounds.right, 3, "bounds.right is set correctly" );
t.eq( bounds.top, 4, "bounds.top is set correctly" );
}
function test_Bounds_fromSize(t) {
t.plan( 5 );
var height = 15;
var width = 16;
var size = new OpenLayers.Size(width, height);
bounds = OpenLayers.Bounds.fromSize(size);
t.ok( bounds instanceof OpenLayers.Bounds, "new OpenLayers.Bounds returns Bounds object" );
t.eq( bounds.left, 0, "bounds.left is set correctly" );
t.eq( bounds.bottom, height, "bounds.bottom is set correctly" );
t.eq( bounds.right, width, "bounds.right is set correctly" );
t.eq( bounds.top, 0, "bounds.top is set correctly" );
}
function test_Bounds_extend(t) {
t.plan( 9 );
var originalBounds = new OpenLayers.Bounds();
var bounds = originalBounds.clone();
//null bounds to start
bounds.extend(new OpenLayers.LonLat(4,5));
t.ok(bounds.equals(new OpenLayers.Bounds(4,5,4,5)), "uninitialized bounds can be safely extended");
originalBounds = new OpenLayers.Bounds(10,20,50,80);
bounds = originalBounds.clone();
//null obj
bounds.extend(null);
t.ok(bounds.equals(originalBounds), "null to extend does not crash or change original bounds");
//obj with no classname
var object = {};
bounds.extend(object);
t.ok(bounds.equals(originalBounds), "extend() passing object with no classname does not crash or change original bounds")
//obj is bounds
//pushing all limits with bounds obj
var testBounds = new OpenLayers.Bounds(5, 10, 60, 90);
object = testBounds.clone();
bounds.extend(object);
t.ok(bounds.equals(testBounds), "extend by valid bounds, pushing all limits, correctly extends bounds");
//pushing no limits with bounds obj
bounds = originalBounds.clone();
testBounds = new OpenLayers.Bounds(15, 30, 40, 70);
object = testBounds.clone();
bounds.extend(object);
t.ok(bounds.equals(originalBounds), "extend by valid bounds, pushing no limits, correctly does not extend bounds");
// obj is lonlat
//left, bottom
bounds = originalBounds.clone();
object = new OpenLayers.LonLat(5, 10);
bounds.extend(object);
t.ok( ((bounds.left == object.lon) &&
(bounds.bottom == object.lat) &&
(bounds.right == originalBounds.right) &&
(bounds.top == originalBounds.top)), "obj lonlat to extends correclty modifies left and bottom");
//right, top
bounds = originalBounds.clone();
object = new OpenLayers.LonLat(60,90);
bounds.extend(object);
t.ok( ((bounds.left == originalBounds.left) &&
(bounds.bottom == originalBounds.bottom) &&
(bounds.right == object.lon) &&
(bounds.top == object.lat)), "obj lonlat to extends correclty modifies right and top");
// obj is point
//left, bottom
bounds = originalBounds.clone();
object = new OpenLayers.Geometry.Point(5, 10);
bounds.extend(object);
t.ok( ((bounds.left == object.x) &&
(bounds.bottom == object.y) &&
(bounds.right == originalBounds.right) &&
(bounds.top == originalBounds.top)), "obj Point to extends correclty modifies left and bottom");
//right, top
bounds = originalBounds.clone();
object = new OpenLayers.Geometry.Point(60,90);
bounds.extend(object);
t.ok( ((bounds.left == originalBounds.left) &&
(bounds.bottom == originalBounds.bottom) &&
(bounds.right == object.x) &&
(bounds.top == object.y)), "obj Point to extends correclty modifies right and top");
}
function test_Bounds_wrapDateLine(t) {
t.plan( 13 );
var testBounds, wrappedBounds, desiredBounds;
var maxExtent = new OpenLayers.Bounds(-10,-10,10,10);
var exactBounds = maxExtent.clone();
var simpleBounds = new OpenLayers.Bounds( -5,-5,5,5);
//bad maxextent
testBounds = simpleBounds.clone();
wrappedBounds = testBounds.wrapDateLine(null);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds with a bad maxextent does nothing");
//exactly inside
testBounds = exactBounds.clone();
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(exactBounds), "wrapping a bounds precisely within (equal to) maxextent does nothing");
//inside
testBounds = simpleBounds.clone();
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds within maxextent does nothing");
// LEFT //
//straddling left
testBounds = simpleBounds.add(-10,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(testBounds), "wrapping a bounds that straddles the left of maxextent does nothing");
//left rightTolerance
testBounds = simpleBounds.add(-14,0);
wrappedBounds =
testBounds.wrapDateLine(maxExtent, {'rightTolerance': 1} );
desiredBounds = simpleBounds.add(6,0);
t.ok(wrappedBounds.equals(desiredBounds), "wrapping a bounds rightTolerance left of maxextent works");
//exactly left
testBounds = exactBounds.add(-20,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(exactBounds), "wrapping an exact bounds once left of maxextent works");
//left
testBounds = simpleBounds.add(-20,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds once left of maxextent works");
//way left
testBounds = simpleBounds.add(-200,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds way left of maxextent works");
// RIGHT //
//straddling right
testBounds = simpleBounds.add(10,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(testBounds), "wrapping a bounds that straddles the right of maxextent does nothing");
//right leftTolerance
testBounds = simpleBounds.add(14,0);
wrappedBounds =
testBounds.wrapDateLine(maxExtent, {'leftTolerance': 1} );
desiredBounds = simpleBounds.add(-6,0);
t.ok(wrappedBounds.equals(desiredBounds), "wrapping a bounds leftTolerance right of maxextent works");
//exactly right
testBounds = exactBounds.add(20,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(exactBounds), "wrapping an exact bounds once right of maxextent works");
//right
testBounds = simpleBounds.add(20,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds once right of maxextent works");
//way right
testBounds = simpleBounds.add(200,0);
wrappedBounds = testBounds.wrapDateLine(maxExtent);
t.ok(wrappedBounds.equals(simpleBounds), "wrapping a bounds way right of maxextent works");
}
function test_Bounds_transform(t) {
t.plan( 3 );
bounds = new OpenLayers.Bounds(10, -10, 20, 10);
bounds.transform(new OpenLayers.Projection("foo"), new OpenLayers.Projection("Bar"));
t.eq(bounds.toBBOX(), "10,-10,20,10", "null transform okay");
bounds.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
t.eq(bounds.toBBOX(), "1113194.907778,-1118889.974702,2226389.815556,1118889.974702", "bounds for spherical mercator transform are correct");
bounds.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
t.eq(bounds.toBBOX(), "10,-10,20,10", "bounds for inverse spherical mercator transform are correct");
}
function test_Bounds_add(t) {
t.plan( 8 );
origBounds = new OpenLayers.Bounds(1,2,3,4);
testBounds = origBounds.clone();
var bounds = testBounds.add(5, 50);
t.ok( testBounds.equals(origBounds), "testBounds is not modified by add operation");
var b = new OpenLayers.Bounds(6,52,8,54);
t.ok( bounds.equals(b), "bounds is set correctly");
//null values
var desiredMsg = "You must pass both x and y values to the add function.";
OpenLayers.Console.error = function(msg) {
t.eq(msg, desiredMsg, "error correctly reported");
}
bounds = testBounds.add(null, 50);
t.ok( testBounds.equals(origBounds), "testBounds is not modified by erroneous add operation (null x)");
t.ok(bounds == null, "returns null on erroneous add operation (null x)");
bounds = testBounds.add(5, null);
t.ok( testBounds.equals(origBounds), "testBounds is not modified by erroneous add operation (null y)");
t.ok(bounds == null, "returns null on erroneous add operation (null y)");
}
function test_Bounds_scale(t) {
t.plan(3);
origBounds = new OpenLayers.Bounds(1,2,3,4);
bounds = origBounds.scale(2);
var b = new OpenLayers.Bounds(0,1,4,5);
t.ok(bounds.equals(b), "Bounds scale correctly with default origin at center")
var origin = new OpenLayers.Pixel(0,1);
bounds = origBounds.scale(2,origin);
b = new OpenLayers.Bounds(2,3,6,7);
t.ok(bounds.equals(b), "Bounds scale correctly with offset origin");
origin = new OpenLayers.Pixel(5,1);
bounds = bounds.scale(2, origin);
b = new OpenLayers.Bounds(-1, 5, 7, 13);
t.ok(bounds.equals(b), "Bounds scale correctly with offset origin");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,315 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
// remove this next line at 3.0
var isMozilla = (navigator.userAgent.indexOf("compatible") == -1);
function test_Class(t) {
t.plan(1);
var MyClass = OpenLayers.Class({
initialize: function () {
t.ok(false, "initialize should not be called");
}
});
t.ok(true,
"defining a class does not call the constructor for the class");
}
function test_Class_constructor(t) {
t.plan(7);
var MyClass = OpenLayers.Class({
prop: null,
classProp: {'bad': 'practice'},
initialize: function(a1, a2) {
this.prop = "instance property";
t.ok(true,
"initialize is called when a new instance is created");
t.eq(a1, arg1,
"initialize is called with the proper first argument");
t.eq(a2, arg2,
"initialize is called with the proper second argument");
},
CLASS_NAME: "MyClass"
});
var arg1 = "anArg";
var arg2 = {"another": "arg"};
var myObj = new MyClass(arg1, arg2);
t.eq(MyClass.prop, null,
"creating a new instance doesn't modify the class");
t.eq(myObj.prop, "instance property",
"the new instance is assigned a property in the constructor");
t.eq(myObj["CLASS_NAME"], "MyClass",
"the new object is an instance of MyClass");
// allow for modification of class properties
MyClass.prototype.classProp.bad = "good";
t.eq(myObj.classProp.bad, "good",
"modifying a class property modifies properties of the instance");
}
function test_Class_inheritance(t) {
t.plan(7);
var BaseClass = OpenLayers.Class({
prop: "base",
initialize: function() {
t.ok(false,
"base class constructor is not called during inheritance");
},
toString: function() {
return "toString inherited";
},
CLASS_NAME: "BaseClass"
});
var ChildClass = OpenLayers.Class(BaseClass, {
initialize: function() {
t.ok(true,
"child class constructor is called in creating an instance");
},
CLASS_NAME: "ChildClass"
});
var child = new ChildClass();
t.eq(child.prop, "base",
"instance of child inherits properties from base");
t.eq(child.toString(), "toString inherited",
"instance of child inherits toString method from base");
t.eq(child["CLASS_NAME"],
"ChildClass",
"new object is an instance of the child class");
var F = OpenLayers.Class(Object, {});
t.ok(!("initialize" in Object.prototype), "no messing with non OL prototypes");
// test with an abstract class (i.e. a class that doesn't have an initialize
// method) as the parent class
var Vehicule = OpenLayers.Class({
numWheels: null
});
var Bike = OpenLayers.Class(Vehicule, {
initialize: function() {
this.numWheels = 2;
}
});
var b = new Bike();
t.ok(b instanceof Vehicule, "a bike is a vehicule");
// test inheritance with something that has a non-function initialize property
var P = OpenLayers.Class({
initialize: "foo"
});
var C = OpenLayers.Class(P, {
initialize: function() {
// pass
}
});
var c = new C();
t.eq(P.prototype.initialize, "foo", "Class restores custom initialize property.");
}
function test_Class_multiple_inheritance(t) {
t.plan(7);
var BaseClass1 = OpenLayers.Class({
override: "base1",
prop: "base1",
variable: null,
initialize: function() {
t.ok(true,
"only called when an instance of this class is created");
},
CLASS_NAME: "BaseClass1"
});
var BaseClass2 = OpenLayers.Class({
override: "base2",
initialize: function() {
t.ok(false,
"base class constructor is not called during inheritance");
},
CLASS_NAME: "BaseClass1"
});
var ChildClass = OpenLayers.Class(BaseClass1, BaseClass2, {
initialize: function(arg) {
if(this.prop == "base1") {
this.variable = "child";
}
t.ok(true,
"only child class constructor is called on initialization");
},
CLASS_NAME: "ChildClass"
});
var arg = "child";
var child = new ChildClass(arg);
t.eq(child.variable, arg,
"inheritance works before construction");
t.eq(child.prop, "base1",
"properties are inherited with multiple classes")
t.eq(child.override, "base2",
"properties are inherited in the expected order");
t.eq(child["CLASS_NAME"],
"ChildClass",
"object is an instance of child class");
var base1 = new BaseClass1();
t.eq(base1.override, "base1",
"inheritance doesn't mess with parents");
}
// Remove this at 3.0
function test_Class_backwards(t) {
t.plan(4);
// test that a new style class supports old style inheritance
var NewClass = OpenLayers.Class({
newProp: "new",
initialize: function() {
t.ok(false, "the base class is never instantiated");
},
toString: function() {
return "new style";
}
});
var OldClass = OpenLayers.Class.create();
OldClass.prototype = OpenLayers.Class.inherit(NewClass, {
oldProp: "old",
initialize: function() {
t.ok(true, "only the child class constructor is called");
}
});
var oldObj = new OldClass();
t.eq(oldObj.oldProp, "old",
"old style classes can still be instantiated");
t.eq(oldObj.newProp, "new",
"old style inheritance of properties works with new style base");
t.eq(oldObj.toString(), "new style",
"toString inheritance works with backwards style");
}
// Remove this at 3.0
function test_Class_create (t) {
t.plan( 3 );
var cls = OpenLayers.Class.create();
cls.prototype = {
initialize: function () {
if (isMozilla)
t.ok(this instanceof cls,
"initialize is called on the right class");
else
t.ok(true, "initialize is called");
}
};
var obj = new cls();
t.eq(typeof obj, "object", "obj is an object");
if (isMozilla)
t.ok(obj instanceof cls,
"object is of the right class");
else
t.ok(true, "this test doesn't work in IE");
}
// Remove this at 3.0
function test_Class_inherit (t) {
t.plan( 20 );
var A = OpenLayers.Class.create();
var initA = 0;
A.prototype = {
count: 0,
mixed: false,
initialize: function () {
initA++;
this.count++;
}
};
var B = OpenLayers.Class.create();
var initB = 0;
B.prototype = OpenLayers.Class.inherit( A, {
initialize: function () {
A.prototype.initialize.apply(this, arguments);
initB++;
this.count++;
}
});
var mixin = OpenLayers.Class.create()
mixin.prototype = {
mixed: true
};
t.eq( initA, 0, "class A not inited" );
t.eq( initB, 0, "class B not inited" );
var objA = new A();
t.eq( objA.count, 1, "object A init" );
t.eq( initA, 1, "class A init" );
if (isMozilla)
t.ok( objA instanceof A, "obj A isa A" );
else
t.ok( true, "IE sucks" );
var objB = new B();
t.eq( initA, 2, "class A init" );
t.eq( initB, 1, "class B init" );
t.eq( objB.count, 2, "object B init twice" );
if (isMozilla) {
t.ok( objB instanceof A, "obj B isa A" );
t.ok( objB instanceof B, "obj B isa B" );
} else {
t.ok( true, "IE sucks" );
t.ok( true, "IE sucks" );
}
var C = OpenLayers.Class.create();
C.prototype = OpenLayers.Class.inherit( B, mixin, {count: 0} );
t.eq( initA, 2, "class A init unchanged" );
t.eq( initB, 1, "class B init unchanged" );
var objC = new C();
t.eq( initA, 3, "class A init changed" );
t.eq( initB, 2, "class B init changed" );
t.eq( objC.count, 2, "object C init changed" );
if (isMozilla) {
t.ok( objC instanceof A, "obj C isa A" );
t.ok( objC instanceof B, "obj C isa B" );
t.ok( objC instanceof C, "obj C isa C" );
t.ok( !(objC instanceof mixin), "obj C isn'ta mixin" );
} else {
t.ok( true, "IE sucks" );
t.ok( true, "IE sucks" );
t.ok( true, "IE sucks" );
t.ok( true, "IE sucks" );
}
t.eq( objC.mixed, true, "class C has mixin properties" );
}
function test_Class_isInstanceOf(t) {
t.plan(7);
var wfs = new OpenLayers.Layer.WFS({});
var drag = new OpenLayers.Control.DragFeature({});
t.ok(wfs instanceof OpenLayers.Layer.WFS, "isInstanceOf(WFS)");
t.ok(wfs instanceof OpenLayers.Layer, "isInstanceOf(Layer)");
t.ok(!(wfs instanceof OpenLayers.Format), "not isInstanceOf(Format)");
t.ok(drag instanceof OpenLayers.Control, "drag is a control");
t.ok(!(drag instanceof OpenLayers.Layer), "drag is not a layer");
//test a class with multiple inheritance
var BadClass=OpenLayers.Class(OpenLayers.Layer.WFS, OpenLayers.Control.DragFeature);
var bad = new BadClass({});
t.ok(!(bad instanceof OpenLayers.Control), "bad is a control, but it is also a layer and we cannot have two superclasses");
t.ok(bad instanceof OpenLayers.Layer, "bad is a layer, it inherits from the layer first");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,268 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Element_visible(t) {
t.plan(3);
var elem = {
style: {
'display': ""
}
};
elem.style.display = "";
t.ok(OpenLayers.Element.visible(elem), "element with style.display == '' is visible");
elem.style.display = "block";
t.ok(OpenLayers.Element.visible(elem), "element with style.display == block is visible");
elem.style.display = "none";
t.ok(!OpenLayers.Element.visible(elem), "element with style.display == none is not visible");
}
function test_Element_toggle(t) {
t.plan(2);
var elem1 = {
style: {
'display': "none"
}
};
var elem2 = {
style: {
'display': ""
}
};
OpenLayers.Element.toggle(elem1, elem2);
t.eq(elem1.style.display, "", "hidden element toggled to display");
t.eq(elem2.style.display, "none", "shown element toggled to hidden");
}
function test_Element_hide(t) {
t.plan(2);
var elem1 = {
style: {
'display': "none"
}
};
var elem2 = {
style: {
'display': ""
}
};
OpenLayers.Element.hide(elem1, elem2);
t.eq(elem1.style.display, "none", "hidden element stays hidden");
t.eq(elem2.style.display, "none", "shown element hidden");
}
function test_Element_show(t) {
t.plan(2);
var elem1 = {
style: {
'display': "none"
}
};
var elem2 = {
style: {
'display': ""
}
};
OpenLayers.Element.show(elem1, elem2);
t.eq(elem1.style.display, "", "hidden element shown");
t.eq(elem2.style.display, "", "shown element stays shown");
}
function test_Element_remove(t) {
t.plan(1);
var elem = {
parentNode: {
'removeChild': function(elem) {
t.ok(true, "removeChild called");
}
}
};
OpenLayers.Element.remove(elem);
}
function test_Element_getHeight(t) {
t.plan(1);
var elem = {
'offsetHeight': {}
};
t.ok(OpenLayers.Element.getHeight(elem) == elem.offsetHeight, "offsetHeight returned");
}
function test_Element_getDimensions(t) {
if (!t.open_window) {
t.plan(0);
return;
} else {
t.plan(4);
}
//shown
t.open_window( "BaseTypes/Element.html", function( wnd ) {
t.delay_call(1, function() {
var elem = wnd.document.getElementById("elemID");
var dims = OpenLayers.Element.getDimensions(elem);
t.eq(dims.width, 50, "width correct when displayed");
t.eq(dims.height, 100, "height correct when displayed")
elem.style.display = "none";
dims = OpenLayers.Element.getDimensions(elem);
t.eq(dims.width, 50, "width correct when hidden");
t.eq(dims.height, 100, "height correct when hidden")
});
});
//hidden
}
function test_hasClass(t) {
t.plan(14);
var has = OpenLayers.Element.hasClass;
var element = document.createElement("div");
element.className = "fe fi fo fum one.part two-part three:part four";
t.ok(has(element, "fe"), "has fe");
t.ok(has(element, "fi"), "has fi");
t.ok(has(element, "fo"), "has fo");
t.ok(!has(element, "f"), "hasn't f");
t.ok(!has(element, "o"), "hasn't o");
t.ok(!has(element, "fumb"), "hasn't fumb");
t.ok(!has(element, "one"), "hasn't one");
t.ok(has(element, "one.part"), "has one.part");
t.ok(!has(element, "two"), "hasn't two");
t.ok(has(element, "two-part"), "has two-part");
t.ok(!has(element, "three"), "hasn't three");
t.ok(has(element, "three:part"), "has three:part");
t.ok(has(element, "four"), "has four");
element.className = "";
t.ok(!has(element, "nada"), "hasn't nada");
}
function test_addClass(t) {
t.plan(6);
var add = OpenLayers.Element.addClass;
var element = document.createElement("div");
element.id = "foo";
t.eq(element.className, "", "starts with no class name");
var mod = add(element, "first");
t.eq(mod.id, element.id, "returns the same element");
t.eq(element.className, "first", "properly adds first class name");
t.eq(add(element, "second").className, "first second",
"properly adds second class name");
t.eq(add(element, "second").className, "first second",
"doesn't do anything for duplicated names");
t.eq(add(element, "third").className, "first second third",
"properly adds third class name");
}
function test_removeClass(t) {
t.plan(5);
var remove = OpenLayers.Element.removeClass;
var element = document.createElement("div");
element.id = "foo";
element.className = "first second middle fourth last";
var mod = remove(element, "last");
t.eq(mod.id, element.id, "returns the same element");
t.eq(element.className, "first second middle fourth",
"properly removes last class name");
t.eq(remove(element, "first").className, "second middle fourth",
"properly removes first class name");
t.eq(remove(element, "middle").className, "second fourth",
"properly removes middle class name");
t.eq(remove(element, "nada").className, "second fourth",
"doesn't do anything for bogus class name");
}
function test_toggleClass(t) {
t.plan(5);
var toggle = OpenLayers.Element.toggleClass;
var element = document.createElement("div");
element.id = "foo";
var mod = toggle(element, "first");
t.eq(mod.id, element.id, "returns the same element");
t.eq(element.className, "first", "adds first new class name");
t.eq(toggle(element, "second").className, "first second",
"adds second new class name");
t.eq(toggle(element, "first").className, "second",
"removes first existing class name");
t.eq(toggle(element, "second").className, "",
"removes second existing class name");
}
function test_Element_getStyle(t) {
t.plan(5);
//tests for this function are not 100% complete... there is some funky
// business going on in there with
// * document.defaultView (moz/ff I believe)
// but I cant seem to find a good way to test them.
//
t.ok(OpenLayers.Element.getStyle(null, null) == null, "passing null values in to getStyle() doesnt bomb, returns null");
var elem = document.getElementById("elemID");
elem.style.chickenHead = {}
var style = "chickenHead";
t.ok(OpenLayers.Element.getStyle(elem, style) == elem.style.chickenHead, "get style on basic stylename returns correctly");
elem.style.chickenHead = "auto";
style = "chickenHead";
t.ok(OpenLayers.Element.getStyle(elem, style) == null, "get style on 'auto' style returns null");
if (OpenLayers.Util.getBrowserName() == "opera") {
elem.style.top = "15px";
style = "top";
elem.style.position = "static";
t.ok(OpenLayers.Element.getStyle(elem, style) == null, "in opera: get (top/left/right/bottom) style when position == 'static' returns null");
elem.style.position = "";
t.ok(OpenLayers.Element.getStyle(elem, style) == null, "in opera: get (top/left/right/bottom) style when position != 'static', gets computedStyle as static and returns null");
} else {
t.ok(true, "browser is not opera.");
t.ok(true, "trust me. browser is not opera.");
}
}
</script>
</head>
<body>
<div id="elemID" style="width:50px; height:100px; background-color:red">test</div>
</body>
</html>

View File

@ -1,173 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var lonlat;
function test_LonLat_constructor (t) {
t.plan( 6 );
lonlat = new OpenLayers.LonLat(6, 5);
t.ok( lonlat instanceof OpenLayers.LonLat, "new OpenLayers.LonLat returns LonLat object" );
t.eq( lonlat.CLASS_NAME, "OpenLayers.LonLat", "lonlat.CLASS_NAME is set correctly");
t.eq( lonlat.lon, 6, "lonlat.lon is set correctly");
t.eq( lonlat.lat, 5, "lonlat.lat is set correctly");
// possible global Mercator projection values
lonlat = new OpenLayers.LonLat(20037508.33999999, -20037508.33999999);
t.eq( lonlat.lon, 20037508.34, "lonlat.lon rounds correctly");
t.eq( lonlat.lat, -20037508.34, "lonlat.lat rounds correctly");
}
function test_LonLat_constructorFromStrings (t) {
t.plan( 4 );
lonlat = new OpenLayers.LonLat("6", "5");
t.ok( lonlat instanceof OpenLayers.LonLat, "new OpenLayers.LonLat returns LonLat object" );
t.eq( lonlat.CLASS_NAME, "OpenLayers.LonLat", "lonlat.CLASS_NAME is set correctly");
t.eq( lonlat.lon, 6, "lonlat.lon is set correctly");
t.eq( lonlat.lat, 5, "lonlat.lat is set correctly");
}
function test_LonLat_toString(t) {
t.plan( 1 );
lonlat = new OpenLayers.LonLat(5,6);
t.eq( lonlat.toString(), "lon=5,lat=6", "lonlat.toString() returns correctly");
}
function test_LonLat_toShortString(t) {
t.plan( 1 );
lonlat = new OpenLayers.LonLat(5,6);
t.eq( lonlat.toShortString(), "5, 6", "lonlat.toShortString() returns correctly");
}
function test_LonLat_clone(t) {
t.plan( 3 );
oldLonLat = new OpenLayers.LonLat(5,6);
lonlat = oldLonLat.clone();
t.ok( lonlat instanceof OpenLayers.LonLat, "clone returns new OpenLayers.LonLat object" );
t.ok( lonlat.equals(oldLonLat), "lonlat is set correctly");
oldLonLat.lon = 100;
t.eq( lonlat.lon, 5, "changing oldLonLat.lon doesn't change lonlat.lon");
}
function test_LonLat_add(t) {
t.plan( 8 );
origLL = new OpenLayers.LonLat(10,100);
lonlatA = origLL.clone();
addpx = lonlatA.add(5, 50);
t.ok( lonlatA.equals(origLL), "lonlatA is not modified by add operation");
var ll = new OpenLayers.LonLat(15,150);
t.ok( addpx.equals(ll), "addpx is set correctly");
//null values
var desiredMsg = "You must pass both lon and lat values to the add function.";
OpenLayers.Console.error = function(msg) {
t.eq(msg, desiredMsg, "error correctly reported");
}
addpx = lonlatA.add(null, 50);
t.ok( lonlatA.equals(origLL), "lonlatA is not modified by erroneous add operation (null lon)");
t.ok(addpx == null, "returns null on erroneous add operation (null lon)");
addpx = lonlatA.add(5, null);
t.ok( lonlatA.equals(origLL), "lonlatA is not modified by erroneous add operation (null lat)");
t.ok(addpx == null, "returns null on erroneous add operation (null lat)");
}
function test_LonLat_equals(t) {
t.plan( 5 );
lonlat = new OpenLayers.LonLat(5,6);
ll = new OpenLayers.LonLat(5,6);
t.eq( lonlat.equals(ll), true, "(5,6) equals (5,6)");
ll = new OpenLayers.LonLat(1,6);
t.eq( lonlat.equals(ll), false, "(5,6) does not equal (1,6)");
ll = new OpenLayers.LonLat(5,2);
t.eq( lonlat.equals(ll), false, "(5,6) does not equal (5,2)");
ll = new OpenLayers.LonLat(1,2);
t.eq( lonlat.equals(ll), false, "(5,6) does not equal (1,2)");
t.ok( !lonlat.equals(null), "equals() returns false on comparison to null");
}
function test_LonLat_fromString(t) {
t.plan( 2 );
lonlat = OpenLayers.LonLat.fromString("6,5");
t.ok( lonlat instanceof OpenLayers.LonLat, "new OpenLayers.LonLat returns LonLat object" );
var ll = new OpenLayers.LonLat(6, 5);
t.ok( lonlat.equals(ll), "lonlat is set correctly");
}
function test_LonLat_transform(t) {
t.plan( 6 );
lonlat = new OpenLayers.LonLat(10, -10);
lonlat.transform(new OpenLayers.Projection("foo"), new OpenLayers.Projection("Bar"));
t.eq(lonlat.lon, 10, "lon for null transform is the same")
t.eq(lonlat.lat, -10, "lat for null transform is the same")
lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
t.eq(Math.round(lonlat.lon), 1113195, "lon for spherical mercator transform is correct");
t.eq(Math.round(lonlat.lat), -1118890, "lat for spherical mercator correct")
lonlat.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
t.eq(lonlat.lon, 10, "lon for inverse spherical mercator transform is correct");
t.eq(Math.round(lonlat.lat), -10, "lat for inverse spherical mercator correct")
}
function test_LonLat_wrapDateLine(t) {
t.plan( 6 );
var goodLL = new OpenLayers.LonLat(0,0);
var testLL, wrappedLL;
//bad maxextent
var maxExtent = null;
testLL = goodLL.clone();
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll with a bad maxextent does nothing");
//good maxextent
maxExtent = new OpenLayers.Bounds(-10,-10,10,10);
//inside
testLL = goodLL.clone();
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll within the maxextent does nothing");
//left
testLL = goodLL.add(-20,0);
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll once left of maxextent works");
//way left
testLL = goodLL.add(-200,0);
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll way left of maxextent works");
//right
testLL = goodLL.add(20,0);
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll once right of maxextent works");
//way right
testLL = goodLL.add(200,0);
wrappedLL = testLL.wrapDateLine(maxExtent);
t.ok(wrappedLL.equals(goodLL), "wrapping a ll way right of maxextent works");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,111 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var pixel;
function test_Pixel_constructor (t) {
t.plan( 4 );
pixel = new OpenLayers.Pixel(5,6);
t.ok( pixel instanceof OpenLayers.Pixel, "new OpenLayers.Pixel returns Pixel object" );
t.eq( pixel.CLASS_NAME, "OpenLayers.Pixel", "pixel.CLASS_NAME is set correctly");
t.eq( pixel.x, 5, "pixel.x is set correctly");
t.eq( pixel.y, 6, "pixel.y is set correctly");
}
function test_Pixel_constructorFromString (t) {
t.plan( 4 );
pixel = new OpenLayers.Pixel("5","6");
t.ok( pixel instanceof OpenLayers.Pixel, "new OpenLayers.Pixel returns Pixel object" );
t.eq( pixel.CLASS_NAME, "OpenLayers.Pixel", "pixel.CLASS_NAME is set correctly");
t.eq( pixel.x, 5, "pixel.x is set correctly");
t.eq( pixel.y, 6, "pixel.y is set correctly");
}
function test_Pixel_toString(t) {
t.plan( 1 );
pixel = new OpenLayers.Pixel(5,6);
t.eq( pixel.toString(), "x=5,y=6", "pixel.toString() returns correctly");
}
function test_Pixel_clone(t) {
t.plan( 4 );
oldPixel = new OpenLayers.Pixel(5,6);
pixel = oldPixel.clone();
t.ok( pixel instanceof OpenLayers.Pixel, "clone returns new OpenLayers.Pixel object" );
t.eq( pixel.x, 5, "pixel.x is set correctly");
t.eq( pixel.y, 6, "pixel.y is set correctly");
oldPixel.x = 100;
t.eq( pixel.x, 5, "changing oldPixel.x doesn't change pixel.x");
}
function test_Pixel_equals(t) {
t.plan( 5 );
pixel = new OpenLayers.Pixel(5,6);
px = new OpenLayers.Pixel(5,6);
t.eq( pixel.equals(px), true, "(5,6) equals (5,6)");
px = new OpenLayers.Pixel(1,6);
t.eq( pixel.equals(px), false, "(5,6) does not equal (1,6)");
px = new OpenLayers.Pixel(5,2);
t.eq( pixel.equals(px), false, "(5,6) does not equal (5,2)");
px = new OpenLayers.Pixel(1,2);
t.eq( pixel.equals(px), false, "(5,6) does not equal (1,2)");
t.ok( !pixel.equals(null), "equals() returns false on comparison to null");
}
function test_Pixel_add(t) {
t.plan( 8 );
var origPX = new OpenLayers.Pixel(5,6);
var oldPixel = origPX.clone();
var pixel = oldPixel.add(10,20);
t.ok( oldPixel.equals(origPX), "oldPixel not modified by add operation");
var px = new OpenLayers.Pixel(15,26);
t.ok( pixel.equals(px), "returned pixel is correct");
//null values
var desiredMsg = "You must pass both x and y values to the add function.";
OpenLayers.Console.error = function(msg) {
t.eq(msg, desiredMsg, "error correctly reported");
}
pixel = oldPixel.add(null, 50);
t.ok( oldPixel.equals(origPX), "oldPixel is not modified by erroneous add operation (null x)");
t.ok(pixel == null, "returns null on erroneous add operation (null x)");
addpx = oldPixel.add(5, null);
t.ok( oldPixel.equals(origPX), "oldPixel is not modified by erroneous add operation (null y)");
t.ok(pixel == null, "returns null on erroneous add operation (null y)");
}
function test_Pixel_offset(t) {
t.plan( 4 );
var oldPixel = new OpenLayers.Pixel(5,6);
var offset = new OpenLayers.Pixel(10,20);
pixel = oldPixel.offset(offset);
t.eq( oldPixel.x, 5, "oldPixel.x not modified by offset operation");
t.eq( oldPixel.y, 6, "oldPixel.y not modified by offset operation");
t.eq( pixel.x, 15, "pixel.x is set correctly");
t.eq( pixel.y, 26, "pixel.y is set correctly");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,67 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var Size;
function test_Size_constructor (t) {
t.plan( 4 );
size = new OpenLayers.Size(5,6);
t.ok( size instanceof OpenLayers.Size, "new OpenLayers.Size returns size object" );
t.eq( size.CLASS_NAME, "OpenLayers.Size", "size.CLASS_NAME is set correctly");
t.eq( size.w, 5, "size.w is set correctly");
t.eq( size.h, 6, "size.h is set correctly");
}
function test_Size_constructorFromString (t) {
t.plan( 4 );
size = new OpenLayers.Size("5","6");
t.ok( size instanceof OpenLayers.Size, "new OpenLayers.Size returns size object" );
t.eq( size.CLASS_NAME, "OpenLayers.Size", "size.CLASS_NAME is set correctly");
t.eq( size.w, 5, "size.w is set correctly");
t.eq( size.h, 6, "size.h is set correctly");
}
function test_Size_toString(t) {
t.plan( 1 );
size = new OpenLayers.Size(5,6);
t.eq( size.toString(), "w=5,h=6", "size.toString() returns correctly");
}
function test_Size_clone(t) {
t.plan( 3 );
oldSize = new OpenLayers.Size(5,6);
size = oldSize.clone();
t.ok( size instanceof OpenLayers.Size, "clone returns new OpenLayers.Size object" );
t.ok( size.equals(oldSize), "new size is equal to old size correctly");
oldSize.w = 100;
t.eq( size.w, 5, "changing oldSize.w doesn't change size.w");
}
function test_Size_equals(t) {
t.plan( 5 );
size = new OpenLayers.Size(5,6);
sz = new OpenLayers.Size(5,6);
t.eq( size.equals(sz), true, "(5,6) equals (5,6)");
sz = new OpenLayers.Size(1,6);
t.eq( size.equals(sz), false, "(5,6) does not equal (1,6)");
sz = new OpenLayers.Size(5,2);
t.eq( size.equals(sz), false, "(5,6) does not equal (5,2)");
sz = new OpenLayers.Size(1,2);
t.eq( size.equals(sz), false, "(5,6) does not equal (1,2)");
t.ok( !size.equals(null), "equals() returns false on comparison to null");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,39 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Console(t) {
/**
* These tests only assure that OpenLayers works when not
* in debug mode. It means that calls to OpenLayers.Console
* will not do anything in this case. When OpenLayers is in
* debug mode, we assume that the Firebug extension or Firebug Lite
* works as advertised.
*/
// supported OpenLayers.Console methods
var methods = ['log', 'debug', 'info', 'warn', 'error', 'assert',
'dir', 'dirxml', 'trace', 'group', 'groupEnd', 'time',
'timeEnd', 'profile', 'profileEnd', 'count'];
t.plan(methods.length * 2);
var nothing, method;
for(var i=0; i<methods.length; ++i) {
method = OpenLayers.Console[methods[i]];
t.ok(method,
"OpenLayers.Console." + methods[i] + " exists");
nothing = OpenLayers.Console[methods[i]]();
t.eq(nothing, null,
"OpenLayers.Console." + methods[i] + "() " +
"call is harmless when not in debug mode");
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,81 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_constructor(t) {
t.plan(4);
var control = new OpenLayers.Control();
t.ok(control instanceof OpenLayers.Control, "new OpenLayers.Control returns object");
t.eq(control.displayClass, "olControl", "displayClass set correctly");
t.ok(control.id != null, "default id assigned to control");
var testID = {};
control = new OpenLayers.Control({ 'id': testID });
t.ok(control.id == testID, "if id specified in options, no default assigned.");
}
function test_Control_addControl(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
t.ok(control.map === map, "Control.map is set to the map object" );
t.ok(map.controls[map.controls.length - 1] === control, "map.controls contains control");
}
function test_Control_title(t) {
t.plan( 1 );
var titleText = 'Title test';
control = new OpenLayers.Control({title:titleText});
t.eq( control.title, titleText, "control.title set correctly" );
}
function test_eventListeners(t) {
t.plan(1);
var method = OpenLayers.Events.prototype.on;
// test that events.on is called at control construction
var options = {
eventListeners: {foo: "bar"}
};
OpenLayers.Events.prototype.on = function(obj) {
t.eq(obj, options.eventListeners, "events.on called with eventListeners");
}
var control = new OpenLayers.Control(options);
OpenLayers.Events.prototype.on = method;
control.destroy();
// if events.on is called again, this will fail due to an extra test
// test control without eventListeners
OpenLayers.Events.prototype.on = function(obj) {
t.fail("events.on called without eventListeners");
}
var control2 = new OpenLayers.Control();
OpenLayers.Events.prototype.on = method;
control2.destroy();
}
function test_Control_destroy(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
control.destroy();
t.ok(map.controls[map.controls.length - 1] != control, "map.controls doesn't contains control");
t.ok(control.map == null, "Control.map is null");
t.ok(control.handler == null, "Control.handler is null");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,43 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_Attribution_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.Attribution();
t.ok( control instanceof OpenLayers.Control.Attribution, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlAttribution", "displayClass is correct" );
}
function test_Control_Attribution_setBaseLayer (t) {
t.plan(1);
map = new OpenLayers.Map("map");
map.addControl(control);
map.addLayer(new OpenLayers.Layer("name",{'attribution':'My layer!', isBaseLayer: true}));
map.addLayer(new OpenLayers.Layer("name",{'attribution':'My layer 2!', isBaseLayer: true}));
map.setBaseLayer(map.layers[1]);
t.eq(control.div.innerHTML, 'My layer 2!', "Attribution correct with changed base layer");
}
function test_Control_Attribution_draw (t) {
t.plan(3);
control = new OpenLayers.Control.Attribution();
map = new OpenLayers.Map("map");
map.addControl(control);
map.addLayer(new OpenLayers.Layer("name",{'attribution':'My layer!'}));
t.eq(control.div.innerHTML, 'My layer!', "Attribution correct with one layer.");
map.addLayer(new OpenLayers.Layer("name", {'attribution':'My layer 2!'}));
t.eq(control.div.innerHTML, 'My layer!, My layer 2!', "Attribution correct with two layers.");
control.separator = '|';
map.addLayer(new OpenLayers.Layer("name",{'attribution':'My layer 3!'}));
t.eq(control.div.innerHTML, 'My layer!|My layer 2!|My layer 3!', "Attribution correct with three layers and diff seperator.");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,17 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_Button_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.Button();
t.ok( control instanceof OpenLayers.Control.Button, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlButton", "displayClass is correct" );
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,279 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_DragFeature_constructor(t) {
t.plan(3);
var options = {
geometryTypes: "foo"
};
var layer = "bar";
var control = new OpenLayers.Control.DragFeature(layer, options);
t.ok(control instanceof OpenLayers.Control.DragFeature,
"new OpenLayers.Control.DragFeature returns an instance");
t.eq(control.layer, "bar",
"constructor sets layer correctly");
t.eq(control.handlers.feature.geometryTypes, "foo",
"constructor sets options correctly on feature handler");
}
function test_Control_DragFeature_destroy(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
control.handlers.drag.destroy = function() {
t.ok(true,
"control.destroy calls destroy on drag handler");
}
control.handlers.feature.destroy = function() {
t.ok(true,
"control.destroy calls destroy on feature handler");
}
control.destroy();
}
function test_Control_DragFeature_activate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
t.ok(!control.handlers.feature.active,
"feature handler is not active prior to activating control");
control.activate();
t.ok(control.handlers.feature.active,
"feature handler is active after activating control");
}
function test_Control_DragFeature_deactivate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.handlers.drag.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on drag handler");
}
control.handlers.feature.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on feature handler");
}
control.deactivate();
}
function test_Control_DragFeature_over(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.activate();
t.ok(!control.handlers.drag.active,
"drag handler is not active before over a feature");
// simulate a mouseover on a feature
var feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
layer.getFeatureFromEvent = function(evt) {
return feature;
}
map.events.triggerEvent("mousemove", {type: "mousemove"});
t.eq(control.feature.id, feature.id,
"control gets the proper feature from the feature handler");
t.ok(control.handlers.drag.active,
"drag handler activated when over a feature");
}
function test_Control_DragFeature_down(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.activate();
// simulate a mouseover on a feature
var feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
layer.getFeatureFromEvent = function(evt) {
return feature;
}
map.events.triggerEvent("mousemove", {type: "mousemove"});
// simulate a mousedown on a feature
control.onStart = function(feat, pixel) {
t.eq(feat.id, feature.id, "onStart called with the correct feature");
t.eq(pixel, "bar", "onStart called with the correct pixel");
}
map.events.triggerEvent("mousedown", {xy: "bar", which: 1, type: "mousemove"});
t.eq(control.lastPixel, "bar",
"mousedown sets the lastPixel correctly");
}
function test_Control_DragFeature_move(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
map.getResolution = function() {
return 2;
}
control.activate();
// mock up a feature - for the sole purpose of testing mousemove
var uid = Math.random();
layer.getFeatureFromEvent = function() {
var geom = new OpenLayers.Geometry.Point(Math.random(),
Math.random());
geom.move = function(x, y) {
t.eq(x, 2, "move called with dx * res");
t.eq(y, -4, "move called with -dy * res");
};
var feature = new OpenLayers.Feature.Vector(geom);
feature.layer = layer;
feature.uid = uid;
return feature;
};
layer.drawFeature = function(feature) {
t.eq(feature.uid, uid,
"layer.drawFeature called with correct feature");
};
// simulate a mouseover on a feature
map.events.triggerEvent("mousemove", {type: "mousemove"});
// simulate a mousedown on a feature
var down = new OpenLayers.Pixel(0, 0);
map.events.triggerEvent("mousedown", {xy: down, which: 1, type: "mousemove"});
// simulate a mousemove on a feature
var move = new OpenLayers.Pixel(1, 2);
map.events.triggerEvent("mousemove", {xy: move, which: 1, type: "mousemove"});
}
function test_Control_DragFeature_up(t) {
t.plan(6);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.activate();
// simulate a mouseover on a feature
var feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
layer.getFeatureFromEvent = function(evt) {
return feature;
}
map.events.triggerEvent("mousemove", {type: "mousemove"});
t.eq(control.over, true,
"mouseover on a feature sets the over property to true");
t.ok(OpenLayers.Element.hasClass(control.map.viewPortDiv, "olControlDragFeatureOver"),
"mouseover on a feature adds class name to map container");
t.eq(control.handlers.drag.active, true,
"mouseover on a feature activates drag handler");
// simulate a mouse-up on the map, with the mouse still
// over the dragged feature
control.handlers.drag.started = true;
map.events.triggerEvent("mouseup", {type: "mouseup"});
t.eq(control.handlers.drag.active, true,
"mouseup while still over dragged feature does not deactivate drag handler");
// simulate a mouse-up on the map, with the mouse out of
// the dragged feature
control.handlers.drag.started = true;
control.over = false;
map.events.triggerEvent("mouseup", {type: "mouseup"});
t.eq(control.handlers.drag.active, false,
"mouseup deactivates drag handler");
control.deactivate();
t.ok(!OpenLayers.Element.hasClass(control.map.viewPortDiv, "olControlDragFeatureOver"),
"deactivate removes class name from map container");
}
function test_Control_DragFeature_done(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.activate();
// simulate a mouseover on a feature
var feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
layer.getFeatureFromEvent = function() {
return feature;
};
map.events.triggerEvent("mousemove", {type: "mousemove"});
t.eq(control.feature.id, feature.id,
"feature is set on mouse over");
control.doneDragging();
t.eq(control.feature.id, feature.id,
"feature sticks around after doneDragging is called.");
}
function test_Control_DragFeature_out(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.DragFeature(layer);
map.addControl(control);
control.activate();
// simulate a mouseover on a feature
var feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
layer.getFeatureFromEvent = function() {
return feature;
};
map.events.triggerEvent("mousemove", {type: "mousemove"});
t.eq(control.feature.id, feature.id,
"feature is set on mouse over");
// simulate a mouseout on a feature
layer.getFeatureFromEvent = function() {
return null;
};
map.events.triggerEvent("mousemove", {type: "mousemove"});
t.ok(control.feature == null,
"feature is set to null on mouse out");
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,82 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map, control, layer;
function init_map() {
control = new OpenLayers.Control.DragPan();
map = new OpenLayers.Map("map", {controls:[control]});
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.zoomToMaxExtent();
map.zoomIn();
control.activate();
return [map, control];
}
function test_Control_DragPan_constructor (t) {
t.plan( 1 );
control = new OpenLayers.Control.DragPan();
t.ok( control instanceof OpenLayers.Control.DragPan, "new OpenLayers.Control returns object" );
}
function test_Control_DragPan_drag (t) {
t.plan(4);
var data = init_map();
map = data[0]; control = data[1];
res = map.baseLayer.resolutions[map.getZoom()];
t.eq(map.center.lat, 0, "Lat is 0 before drag");
t.eq(map.center.lon, 0, "Lon is 0 before drag");
map.events.triggerEvent('mousedown', {'type':'mousedown', 'xy':new OpenLayers.Pixel(0,0), 'which':1});
map.events.triggerEvent('mousemove', {'type':'mousemove', 'xy':new OpenLayers.Pixel(5,5), 'which':1});
map.events.triggerEvent('mouseup', {'type':'mouseup', 'xy':new OpenLayers.Pixel(5,5), 'which':1});
t.eq(map.getCenter().lat, res * 5, "Lat is " + (res * 5) + " after drag");
t.eq(map.getCenter().lon, res * -5, "Lon is " + (res * -5) + " after drag");
}
function test_Control_DragPan_click(t) {
t.plan(1);
var control = new OpenLayers.Control.DragPan();
var map = new OpenLayers.Map("map", {controls:[control]});
var layer = new OpenLayers.Layer.WMS("OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0",
{layers: 'basic'});
map.addLayer(layer);
map.zoomToMaxExtent();
map.zoomIn();
control.activate();
map.setCenter = function() {
t.ok(false, "map.setCenter should not be called here");
};
var xy = new OpenLayers.Pixel(0, 0);
var down = {
'type': 'mousedown',
'xy': xy,
'which': 1
};
var move = {
'type': 'mousemove',
'xy': xy,
'which': 1
};
var up = {
'type': 'mouseup',
'xy': xy,
'which': 1
};
map.events.triggerEvent('mousedown', down);
map.events.triggerEvent('mousemove', move);
map.events.triggerEvent('mouseup', up);
t.ok(true, "clicking without moving the mouse does not call setCenter");
}
</script>
</head>
<body>
<a id="scale" href="">DragPan</a> <br />
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,83 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(2);
var control = new OpenLayers.Control.DrawFeature("foo", function() {});
t.ok(control instanceof OpenLayers.Control.DrawFeature,
"constructor returns an instance");
t.ok(OpenLayers.Util.indexOf(control.EVENT_TYPES, "featureadded") > -1,
"featureadded event in EVENT_TYPES");
}
function test_drawFeature(t) {
t.plan(3);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.DrawFeature(layer, function() {});
var geom = {};
layer.addFeatures = function(features) {
t.ok(features[0].geometry == geom, "layer.addFeatures called");
t.eq(features[0].state, OpenLayers.State.INSERT, "layer state set");
};
function handlefeatureadded(event) {
t.ok(event.feature.geometry == geom, "featureadded triggered");
}
control.events.on({"featureadded": handlefeatureadded});
control.drawFeature(geom);
control.events.un({"featureadded": handlefeatureadded});
}
function test_sketch_events(t) {
t.plan(6);
var map = new OpenLayers.Map("map", {
resolutions: [1]
});
var layer = new OpenLayers.Layer.Vector("foo", {
maxExtent: new OpenLayers.Bounds(-10, -10, 10, 10),
isBaseLayer: true
});
var control = new OpenLayers.Control.DrawFeature(
layer, OpenLayers.Handler.Point
);
map.addLayer(layer);
map.addControl(control);
map.zoomToMaxExtent();
control.activate();
var log = {};
layer.events.on({
sketchstarted: function(event) {
log.event = event;
},
sketchmodified: function(event) {
log.event = event;
},
sketchcomplete: function(event) {
log.event = event;
}
});
// mock up draw/modify of a point
map.events.triggerEvent("mousedown", {xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.event.type, "sketchstarted", "[mousedown] sketchstarted triggered");
t.geom_eq(log.event.vertex, new OpenLayers.Geometry.Point(-200, 125), "[mousedown] correct vertex");
map.events.triggerEvent("mousemove", {xy: new OpenLayers.Pixel(10, 10)});
t.eq(log.event.type, "sketchmodified", "[mousemove] sketchmodified triggered");
t.geom_eq(log.event.vertex, new OpenLayers.Geometry.Point(-190, 115), "[mousemove] correct vertex");
map.events.triggerEvent("mouseup", {xy: new OpenLayers.Pixel(10, 10)});
t.eq(log.event.type, "sketchcomplete", "[mouseup] sketchcomplete triggered");
t.geom_eq(log.event.feature.geometry, new OpenLayers.Geometry.Point(-190, 115), "[mouseup] correct geometry");
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,118 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_GetFeature_constructor(t) {
t.plan(2);
var protocol = "foo";
var control = new OpenLayers.Control.GetFeature({
protocol: protocol
});
t.ok(control instanceof OpenLayers.Control.GetFeature,
"new OpenLayers.Control.SelectFeature returns an instance");
t.eq(control.protocol, "foo",
"constructor sets protocol correctly");
}
function test_Control_GetFeature_select(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.WMS("foo", "wms", {
layers: "foo"
});
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(1,2));
var feature1 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,2));
var feature2 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(2,3));
var control = new OpenLayers.Control.GetFeature({
protocol: new OpenLayers.Protocol({
read: function(obj) {
obj.callback.call(obj.scope, {
features: [feature1, feature2],
code: 1
});
}
}),
box: true
});
map.addControl(control);
var singleTest = function(evt) {
t.eq(evt.feature.id, feature1.id, "featureselected callback called with closest feature");
}
control.events.register("featureselected", this, singleTest);
control.selectSingle({xy: new OpenLayers.Pixel(200, 125)});
control.events.unregister("featureselected", this, singleTest);
var features = []
var boxTest = function(evt) {
features.push(evt.feature);
}
control.events.register("featureselected", this, boxTest);
control.selectBox(new OpenLayers.Bounds(0,0,4,4));
control.events.unregister("featureselected", this, boxTest);
t.eq(features.length, 2, "2 features inside box selected");
t.eq(features[1].id, feature2.id, "featureselected callback called with multiple features");
}
function test_Control_GetFeature_hover(t) {
t.plan(6);
var abortedResponse = null;
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.WMS("foo", "wms", {
layers: "foo"
});
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(1,2));
var feature1 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,2));
var feature2 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(2,3));
var response = new OpenLayers.Protocol.Response();
var control = new OpenLayers.Control.GetFeature({
protocol: new OpenLayers.Protocol({
read: function(obj){
obj.callback.call(obj.scope, {
features: [feature1, feature2],
code: 1
});
return response;
},
abort: function(response) {
abortedResponse = response;
}
}),
hover: true
});
map.addControl(control);
var hoverFeature;
var hoverTest = function(evt) {
t.eq(evt.feature.id, hoverFeature.id, "hoverfeature callback called with closest feature");
}
var outTest = function(evt) {
t.eq(evt.feature.id, feature1.id, "outfeature callback called with previously hovered feature");
}
control.events.register("hoverfeature", this, hoverTest);
control.events.register("outfeature", this, outTest);
hoverFeature = feature1;
control.selectHover({xy: new OpenLayers.Pixel(200, 125)});
t.ok(control.hoverResponse == response,
"selectHover stores the protocol response in the hoverResponse property");
hoverFeature = feature2;
control.selectHover({xy: new OpenLayers.Pixel(400, 0)});
control.cancelHover();
t.ok(abortedResponse == response,
"cancelHover calls protocol.abort() with the expected response");
t.eq(control.hoverResponse, null,
"cancelHover sets this.hoverResponse to null");
control.events.unregister("hoverfeature", this, hoverTest);
control.events.unregister("outfeature", this, outTest);
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,172 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_KeyboardDefaults_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.KeyboardDefaults();
t.ok( control instanceof OpenLayers.Control.KeyboardDefaults,
"new OpenLayers.Control.KeyboardDefaults returns object" );
t.eq( control.displayClass, "olControlKeyboardDefaults", "displayClass is correct" );
}
function test_Control_KeyboardDefaults_addControl (t) {
t.plan( 4 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.KeyboardDefaults();
t.ok( control instanceof OpenLayers.Control.KeyboardDefaults,
"new OpenLayers.Control.KeyboardDefaults returns object" );
t.ok( map instanceof OpenLayers.Map,
"new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( OpenLayers.Util.indexOf(map.controls, control), "map.controls contains control" );
}
/* 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
*/
function test_Control_KeyboardDefaults_KeyDownEvent (t) {
t.plan( 16 );
var evt = {which: 1};
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.KeyboardDefaults();
map.addControl(control);
var STARTING_ZOOM_LEVEL = 4;
var DELAY = 2;
var centerLL = new OpenLayers.LonLat(0,0);
map.setCenter(centerLL, STARTING_ZOOM_LEVEL);
// Start new test.
evt.keyCode = OpenLayers.Event.KEY_LEFT;
control.defaultKeyPress(evt);
t.delay_call(
DELAY, function() {
t.ok( map.getCenter().lon < centerLL.lon, "key left works correctly" );
// Start new test.
evt.keyCode = OpenLayers.Event.KEY_RIGHT;
control.defaultKeyPress(evt);
},
DELAY, function() {
t.eq( map.getCenter().lon, centerLL.lon, "key right works correctly" );
// Start new test.
evt.keyCode = OpenLayers.Event.KEY_UP;
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lat > centerLL.lat, "key up works correctly" );
// Start new test.
evt.keyCode = OpenLayers.Event.KEY_DOWN;
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lat == centerLL.lat, "key down works correctly" );
// Start new test.
evt.keyCode = 33; //page up
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lat > centerLL.lat, "key page up works correctly" );
// Start new test.
evt.keyCode = 34; //page down
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lat == centerLL.lat, "key page down works correctly" );
// Start new test.
evt.keyCode = 35; //end
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lon > centerLL.lon, "key end works correctly" );
// Start new test.
evt.keyCode = 36; //home
control.defaultKeyPress(evt);
},
DELAY, function() {
t.ok( map.getCenter().lon == centerLL.lon, "key home works correctly");
// Start new test.
evt.keyCode = 43; //+
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 1, "key code 43 works correctly: +/= key (ASCII), keypad + (ASCII, Opera)" );
// Start new test.
evt.keyCode = 61;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 2, "key code 61 works correctly: +/= key (Mozilla, Opera, some ASCII)");
// Start new test.
evt.keyCode = 187;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 3, "key code 187 works correctly: +/= key (IE)");
// Start new test.
evt.keyCode = 107;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 4, "key code 107 works correctly: keypad + (IE, Mozilla)");
// Start new test.
// set zoomanimation flag manually,
// reason: loadend event in layers.js will not achieved in unittests
map.zoomanimationActive = false;
evt.keyCode = 45;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 3, "key code 45 works correctly: -/_ key (ASCII, Opera), keypad - (ASCII, Opera)");
// Start new test.
// set zoomanimation flag manually,
// reason: loadend event in layers.js will not achieved in unittests
map.zoomanimationActive = false;
evt.keyCode = 109;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 2, "key code 109 works correctly: -/_ key (Mozilla), keypad - (Mozilla, IE)");
// Start new test.
// set zoomanimation flag manually,
// reason: loadend event in layers.js will not achieved in unittests
map.zoomanimationActive = false;
evt.keyCode = 189;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL + 1, "key code 189 works correctly: -/_ key (IE)");
// Start new test.
// set zoomanimation flag manually,
// reason: loadend event in layers.js will not achieved in unittests
map.zoomanimationActive = false;
evt.keyCode = 95;
control.defaultKeyPress(evt);
t.eq( map.getZoom(), STARTING_ZOOM_LEVEL, "key code 95 works correctly: -/_ key (some ASCII)");
}
);
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,193 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_LayerSwitcher_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.LayerSwitcher();
t.ok( control instanceof OpenLayers.Control.LayerSwitcher, "new OpenLayers.Control.LayerSwitcher returns object" );
t.eq( control.displayClass, "olControlLayerSwitcher", "displayClass is correct" );
}
function test_Control_LayerSwitcher_draw (t) {
t.plan( 2 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
var div = control.draw();
t.ok( control.div != null, "draw makes a div" );
t.ok( div != null, "draw returns its div" );
}
function test_Control_LayerSwitcher_outsideViewport (t) {
t.plan( 2 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')});
map.addControl(control);
t.eq(control.div.style.width, "250px", "Div is not minimized when added.");
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
t.eq(control.div.style.width, "0px", "Div is minimized when added.");
}
function test_Control_LayerSwitcher_loadContents(t) {
t.plan( 5 );
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("WMS",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
markers = new OpenLayers.Layer.Markers("markers");
map.addLayer(markers);
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
t.ok(control.layersDiv != null, "correctly makes layers div");
t.ok(control.baseLayersDiv != null, "correctly makes layers div");
t.ok(control.dataLayersDiv != null, "correctly makes layers div");
t.ok(control.maximizeDiv != null, "correctly makes resize div");
t.ok(control.minimizeDiv != null, "correctly makes resize div");
}
function test_Control_LayerSwitcher_redraw (t) {
t.plan( (OpenLayers.Util.getBrowserName() == "opera" ? 9 : 19 ) );
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("WMS",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
markers = new OpenLayers.Layer.Markers("markers");
map.addLayer(markers);
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
var wmsInput = OpenLayers.Util.getElement(control.id + "_input_" + layer.name);
t.ok(wmsInput != null, "correctly makes an input for wms layer");
t.eq(wmsInput.type, "radio", "wms correctly made a radio button");
t.eq(wmsInput.name, "baseLayers", "wms correctly named");
t.eq(wmsInput.value, layer.name, "wms correctly valued");
var markersInput = OpenLayers.Util.getElement(control.id + "_input_" + markers.name);
t.ok(markersInput != null, "correctly makes an input for markers layer");
t.eq(markersInput.type, "checkbox", "wms correctly made a radio button");
t.eq(markersInput.name, markers.name, "wms correctly named");
t.eq(markersInput.value, markers.name, "wms correctly valued");
t.eq(false, control.checkRedraw(), "check redraw is false");
if (OpenLayers.Util.getBrowserName() != "opera") {
control = new OpenLayers.Control.LayerSwitcher();
var myredraw = control.redraw;
control.redraw = function() {
t.ok(true, "redraw called when setting vis");
}
map.addControl(control);
var func = myredraw.bind(control);
func();
markers.setVisibility(false);
t.eq(control.checkRedraw(), true, "check redraw is true after changing layer and not letting redraw happen.");
map.removeControl(control);
control = new OpenLayers.Control.LayerSwitcher();
var myredraw = control.redraw;
control.redraw = function() {
t.ok(true, "redraw called when setting inRange");
}
map.addControl(control);
var func = myredraw.bind(control);
func();
markers.inRange = false;
t.eq(control.checkRedraw(), true, "check redraw is true after changing layer.inRange and not letting redraw happen.");
map.removeControl(control);
control = new OpenLayers.Control.LayerSwitcher();
var myredraw = control.redraw;
control.redraw = function() {
t.ok(true, "redraw called when raising base layer ");
}
map.addControl(control);
var func = myredraw.bind(control);
func();
map.raiseLayer(layer, 1);
t.eq(control.checkRedraw(), true, "check redraw is true after changing layer.inRange and not letting redraw happen.");
map.removeControl(control);
} else {
t.debug_print("FIXME: Some LayerSwitcher tests fail in Opera.");
}
}
function test_Control_LayerSwitcher_ascendingw (t) {
t.plan( 4 );
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("WMS",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
markers = new OpenLayers.Layer.Markers("markers");
map.addLayer(markers);
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
control2 = new OpenLayers.Control.LayerSwitcher({'ascending':false});
map.addControl(control2);
t.ok(control.div.childNodes[1].childNodes[0].innerHTML.match("Base Layer"), "Base Layers first in LayerSwitcher with ascending true");
t.ok(control.div.childNodes[1].childNodes[2].innerHTML.match("Overlays"), "Overlays in LayerSwitcher with ascending true");
t.ok(control2.div.childNodes[1].childNodes[2].innerHTML.match("Base Layer"), "Base Layers last in LayerSwitcher with ascending false");
t.ok(control2.div.childNodes[1].childNodes[0].innerHTML.match("Overlays"), "Base Layers last in LayerSwitcher with ascending false");
}
function test_Control_LayerSwitcher_displayInLayerSwitcher (t) {
t.plan( 2 );
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("WMS",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"}, {'displayInLayerSwitcher': false});
map.addLayer(layer);
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
t.eq(control.div.childNodes[1].childNodes[0].style.display, "none" , "Base layer display off when no visble base layer");
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("WMS",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.LayerSwitcher();
map.addControl(control);
t.eq(control.div.childNodes[1].childNodes[0].style.display, "" , "Base layer display on when visble base layer");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
<div id="layerswitcher" style="width:250px; height:256px;" />
</body>
</html>

View File

@ -1,75 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialze(t) {
t.plan(1);
var map = new OpenLayers.Map("map");
var control = new OpenLayers.Control.Measure(
OpenLayers.Handler.Path, {persist: true}
);
map.addControl(control);
t.eq(control.persist, true, "passing persist to constructor sets persist on handler");
map.destroy();
}
function test_cancel(t) {
t.plan(4);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer(null, {
isBaseLayer: true
});
map.addLayer(layer);
map.zoomToMaxExtent();
var control = new OpenLayers.Control.Measure(
OpenLayers.Handler.Path, {persist: true}
);
map.addControl(control);
control.activate();
try {
control.cancel();
t.ok(true, "calling cancel before drawing works");
} catch(err) {
t.fail("calling cancel before drawing causes trouble: " + err);
}
t.eq(control.active, true, "control remains active after cancel");
// create a simple measurement
function trigger(type, x, y) {
map.events.triggerEvent(type, {
xy: new OpenLayers.Pixel(x, y)
})
};
trigger("mousedown", 0, 0);
trigger("mouseup", 0, 0);
trigger("mousemove", 10, 10);
trigger("mousedown", 10, 10);
trigger("mouseup", 10, 10);
// confirm that the sketch persists
t.eq(control.handler.layer.features.length, 1, "feature persists");
// cancel and see that sketch is gone
control.cancel();
t.eq(control.handler.layer.features.length, 0, "feature is gone after cancel");
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 512px; height: 256px;"></div>
</body>
</html>

View File

@ -1,620 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var layer = {
styleMap: {createSymbolizer: function(){}},
events: {
on: function() {},
un: function() {}
}
};
var options = {
geometryTypes: "bar"
};
var control = new OpenLayers.Control.ModifyFeature(layer, options);
t.ok(control.layer == layer,
"constructor sets layer correctly");
t.eq(control.selectControl.geometryTypes, "bar",
"constructor sets options correctly on feature handler");
t.eq(control.mode, OpenLayers.Control.ModifyFeature.RESHAPE,
"constructor initializes modification mode correctly");
control.destroy();
}
function test_destroy(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
control.selectControl.destroy = function() {
t.ok(true,
"control.destroy calls destroy on select control");
}
control.dragControl.destroy = function() {
t.ok(true,
"control.destroy calls destroy on feature handler");
}
control.destroy();
map.destroy();
}
function test_activate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
t.ok(!control.selectControl.active,
"select control is not active prior to activating control");
control.activate();
t.ok(control.selectControl.active,
"select control is active after activating control");
map.destroy();
}
function test_initDeleteCodes(t) {
t.plan(3);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.ModifyFeature(layer, {'deleteCodes': 46});
t.eq(control.deleteCodes[0], 46, "Delete code properly turned into an array.");
var control = new OpenLayers.Control.ModifyFeature(layer);
t.eq(control.deleteCodes[0], 46, "Default deleteCodes include delete");
t.eq(control.deleteCodes[1], 68, "Default deleteCodes include 'd'");
control.destroy();
layer.destroy();
}
function test_handleKeypress(t) {
t.plan(11);
/**
* There are two things that we want to test here
* 1) test that control.deleteCodes are respected
* 3) test that a vertex is properly deleted
*
* In the future, feature deletion may be added to the control.
*/
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.ModifyFeature(layer);
var delKey = 46;
var dKey = 100;
control.deleteCodes = [delKey, dKey];
// test that a polygon vertex is deleted for all delete codes
var point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point()
);
var poly = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon()
);
// mock up vertex deletion
control.dragControl.feature = point;
control.feature = poly;
control.vertices = [point];
point.geometry.parent = {
removeComponent: function(geometry) {
t.eq(geometry.id, point.geometry.id,
"vertex deletion: removeComponent called on parent with proper geometry");
}
};
layer.events.on({"featuremodified": function(event) {
t.eq(event.feature.id, poly.id, "vertex deletion: featuremodifed triggered");
}});
layer.drawFeature = function(feature) {
t.eq(feature.id, poly.id,
"vertex deletion: drawFeature called with the proper feature");
};
control.resetVertices = function() {
t.ok(true, "vertex deletion: resetVertices called");
};
control.onModification = function(feature) {
t.eq(feature.id, poly.id,
"vertex deletion: onModification called with the proper feature");
};
// run the above four tests twice
control.handleKeypress({keyCode:delKey});
control.handleKeypress({keyCode:dKey});
t.eq(control.feature.state, OpenLayers.State.UPDATE, "feature state set to update");
// now make sure nothing happens if the vertex is mid-drag
control.dragControl.handlers.drag.dragging = true;
control.handleKeypress({keyCode:delKey});
// clean up
control.destroy();
layer.destroy();
}
function test_onUnSelect(t) {
t.plan(6);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.ModifyFeature(layer);
var fakeFeature = {'id':'myid'};
control.vertices = 'a';
control.virtualVertices = 'b';
control.features = true;
layer.events.on({"afterfeaturemodified": function(event) {
t.eq(event.feature, fakeFeature, "afterfeaturemodified triggered");
}});
control.dragControl.deactivate = function() { t.ok(true, "Deactivate called on drag control"); }
control.onModificationEnd = function (feature) { t.eq(feature.id, fakeFeature.id, "onModificationEnd got feature.") }
layer.removeFeatures = function(verts) {
t.ok(verts == 'a', "Normal verts removed correctly");
}
layer.destroyFeatures = function(verts) {
t.ok(verts == 'b', "Virtual verts destroyed correctly");
}
control.unselectFeature(fakeFeature);
t.eq(control.feature, null, "feature is set to null");
layer.destroyFeatures = function() {};
control.destroy();
layer.destroy();
}
function test_stop_modification(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.Vector("Vectors!", {isBaseLayer: true});
var feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(0, 0)
);
layer.addFeatures([feature]);
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0, 0));
// If a feature is to be modified, control.selectFeature gets called.
// We want this test to fail if selectFeature gets called.
var modified = false;
var _ = OpenLayers.Control.ModifyFeature.prototype.selectFeature;
OpenLayers.Control.ModifyFeature.prototype.selectFeature = function() {
modified = true;
}
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
// register a listener that will stop feature modification
layer.events.on({"beforefeaturemodified": function() {return false}});
// we can initiate feature modification by selecting a feature with
// the control's select feature control
control.selectControl.select(feature);
if(modified) {
t.fail("selectFeature called, prepping feature for modification");
} else {
t.ok(true, "the beforefeaturemodified listener stopped feature modification");
}
OpenLayers.Control.ModifyFeature.prototype.selectFeature = _;
}
function test_selectFeature(t) {
t.plan(12);
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.Vector("Vectors!", {isBaseLayer: true});
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0, 0));
var control = new OpenLayers.Control.ModifyFeature(layer);
control.vertices = [];
control.virtualVertices = [];
var callback = function(obj) {
t.ok(obj.feature == fakeFeature, "beforefeaturemodified triggered");
};
layer.events.on({"beforefeaturemodified": callback});
control.dragControl.activate = function() { t.ok(true, "drag Control activated"); }
control.onModificationStart = function(feature) { t.eq(feature.id, fakeFeature.id, "On Modification Start called with correct feature."); }
// Start of testing
control.collectVertices = function() { t.fail("Collect vertices called when geom is a point"); }
var fakeFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0, 0));
// Points don't call collectVertices
control.selectFeature(fakeFeature);
control.collectVertices = function() {
t.ok(true, "collectVertices called");
this.vertices = 'a';
this.virtualVertices = 'd';
layer.addFeatures(this.vertices);
layer.addFeatures(this.virtualVertices);
}
layer.addFeatures = function(features) {
t.ok(features == 'a' || features == 'd', "features passed correctly");
}
fakeFeature.geometry = new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(0, 0),
new OpenLayers.Geometry.Point(1, 1)
])
]);
// OnSelect calls collectVertices and passes features to layer
control.selectFeature(fakeFeature);
control.vertices = ['a'];
control.virtualVertices = ['b'];
layer.addFeatures = function(features) {}
layer.removeFeatures = function(features) {
t.eq(features.length, 1, "Correct feature length passed in");
}
// Features are removed whenever they exist
control.selectFeature(fakeFeature);
control.destroy();
// layer.destroy() will call removeFeatures with an empty array, make
// removeFeatures reference an empty function to prevent the above
// test to fail
layer.removeFeatures = function(features) {};
layer.destroy();
}
function test_resetVertices(t) {
t.plan(21);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.ModifyFeature(layer);
var point = new OpenLayers.Geometry.Point(5,6);
var point2 = new OpenLayers.Geometry.Point(7,8);
var point3 = new OpenLayers.Geometry.Point(9,10);
control.feature = new OpenLayers.Feature.Vector(point);
control.resetVertices();
t.eq(control.vertices.length, 0, "Correct vertices length");
t.eq(control.virtualVertices.length, 0, "Correct virtual vertices length.");
var multiPoint = new OpenLayers.Geometry.MultiPoint([point, point2]);
control.feature = new OpenLayers.Feature.Vector(multiPoint);
control.resetVertices();
t.eq(control.vertices.length, 2, "Correct vertices length with multipoint");
t.eq(control.virtualVertices.length, 0, "Correct virtual vertices length (multipoint).");
var line = new OpenLayers.Geometry.LineString([point, point2]);
control.feature = new OpenLayers.Feature.Vector(line);
control.resetVertices();
t.eq(control.vertices.length, 2, "Correct vertices length with line");
t.eq(control.virtualVertices.length, 1, "Correct virtual vertices length (linestring).");
var polygon = new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([point, point2, point3])]);
control.feature = new OpenLayers.Feature.Vector(polygon);
control.resetVertices();
t.eq(control.vertices.length, 3, "Correct vertices length with polygon");
t.eq(control.virtualVertices.length, 3, "Correct virtual vertices length (polygon).");
control.mode = OpenLayers.Control.ModifyFeature.DRAG;
control.resetVertices();
t.ok(control.dragHandle != null, "Drag handle is set");
t.eq(control.vertices.length, 0, "Correct vertices length with polygon (DRAG)");
control.mode = OpenLayers.Control.ModifyFeature.ROTATE;
control.resetVertices();
t.ok(control.radiusHandle != null, "Radius handle is set");
t.eq(control.vertices.length, 0, "Correct vertices length with polygon (ROTATE)");
control.mode = OpenLayers.Control.ModifyFeature.RESIZE;
control.resetVertices();
t.ok(control.radiusHandle != null, "Radius handle is set");
t.eq(control.vertices.length, 0, "Correct vertices length with polygon (RESIZE)");
control.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
control.resetVertices();
t.ok(control.radiusHandle == null, "Radius handle is not set (RESHAPE)");
t.eq(control.vertices.length, 3, "Correct vertices length with polygon (RESHAPE)");
t.eq(control.virtualVertices.length, 3, "Correct virtual vertices length (RESHAPE)");
control.mode = OpenLayers.Control.ModifyFeature.RESIZE | OpenLayers.Control.ModifyFeature.RESHAPE;
control.resetVertices();
t.ok(control.radiusHandle != null, "Radius handle is set (RESIZE|RESHAPE)");
t.eq(control.vertices.length, 0, "No vertices when both resizing and reshaping (RESIZE|RESHAPE)");
t.eq(control.virtualVertices.length, 0, "No virtual vertices when both resizing and reshaping (RESIZE|RESHAPE)");
control.dragControl.feature = new OpenLayers.Feature.Vector(polygon);
control.dragControl.map = {};
control.dragControl.map.div = {};
control.dragControl.map.div.style = {};
control.dragControl.map.viewPortDiv = "foo";
control.dragControl.handlers.drag.deactivate = function() {
this.active = false;
}
control.resetVertices();
t.ok(!control.dragControl.handlers.drag.active, "resetVertices deactivates drag handler");
control.dragControl.map = null;
control.destroy();
layer.destroy();
}
function test_dragVertex(t) {
t.plan(8);
var map = new OpenLayers.Map("map", {
resolutions: [1]
});
var layer = new OpenLayers.Layer.Vector("foo", {
maxExtent: new OpenLayers.Bounds(-10, -10, 10, 10),
isBaseLayer: true
});
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
map.zoomToMaxExtent();
var log = {};
layer.events.on({
"vertexmodified": function(event) {
log.event = event;
}
});
// pretend to drag a point
var feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(0, 0)
);
control.feature = feature;
var pixel = new OpenLayers.Pixel(-100, 100);
control.dragVertex(feature, pixel);
t.eq(log.event.type, "vertexmodified", "[drag point] vertexmodified triggered");
t.geom_eq(log.event.vertex, feature.geometry, "[drag point] listeners receive correct vertex");
t.eq(log.event.feature.id, feature.id, "[drag point] listeners receive correct feature");
t.ok(log.event.pixel === pixel, "[drag point] listeners receive correct pixel");
// pretend to drag vertex of a linestring
var vert = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(0, 0)
);
var feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.LineString([
vert.geometry, new OpenLayers.Geometry.Point(10, 0)
])
);
control.feature = feature;
var pixel = new OpenLayers.Pixel(-100, 100);
control.dragVertex(vert, pixel);
t.eq(log.event.type, "vertexmodified", "[drag vertex] vertexmodified triggered");
t.geom_eq(log.event.vertex, vert.geometry, "[drag vertex] listeners receive correct vertex");
t.eq(log.event.feature.id, feature.id, "[drag vertex] listeners receive correct feature");
t.ok(log.event.pixel === pixel, "[drag vertex] listeners receive correct pixel");
map.destroy();
}
function test_onDrag(t) {
t.plan(1);
t.ok(true, "onDrag not tested yet.");
}
function test_dragComplete(t) {
t.plan(8);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.ModifyFeature(layer);
var fakeFeature = {
'geometry': { 'id':'myGeom'},
'id': 'fakeFeature'
};
layer.addFeatures = function (verts) {
t.ok(verts == 'virtual' || verts == 'normal', verts + " verts correct");
}
layer.removeFeatures = function (verts) {
t.ok(verts == 'previous virtual' || verts == 'previous normal', verts + " verts correct");
}
layer.events.on({"featuremodified": function(event) {
t.eq(event.feature, fakeFeature, "featuremodified triggered");
}});
control.onModification = function(feat) {
t.eq(feat.id, fakeFeature.id, "onModification gets correct feat");
}
control.collectVertices = function() {
t.ok(true, "collectVertices called");
this.vertices = 'normal';
this.virtualVertices = 'virtual';
layer.addFeatures(this.vertices);
layer.addFeatures(this.virtualVertices);
}
control.feature = fakeFeature;
control.vertices = 'previous normal';
control.virtualVertices = 'previous virtual';
control.dragComplete();
t.eq(fakeFeature.state, OpenLayers.State.UPDATE, "feature state set to UPDATE");
control.destroy();
// layer.destroy() will call removeFeatures with an empty array, make
// removeFeatures reference an empty function to prevent the above
// test to fail
layer.removeFeatures = function(verts) {};
layer.destroy();
}
function test_deactivate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.selectControl.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on select control");
}
control.dragControl.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on drag control");
}
control.active = true;
control.deactivate();
map.destroy();
}
function test_onModificationStart(t) {
t.plan(1);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
// make sure onModificationStart is called on feature selection
var testFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(Math.random(), Math.random())
);
control.onModificationStart = function(feature) {
t.eq(feature.id, testFeature.id,
"onModificationStart called with the right feature");
};
control.selectFeature(testFeature);
map.destroy();
}
function test_onModification(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
// make sure onModification is called on drag complete
var point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(Math.random(), Math.random())
);
control.feature = point;
control.onModification = function(feature) {
t.eq(feature.id, point.id,
"onModification called with the right feature on drag complete");
};
control.dragComplete();
// make sure onModification is called on vertex deletion
var poly = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon()
);
var oldDraw = layer.drawFeature;
layer.drawFeature = function() {
return;
};
control.feature = poly;
control.vertices = [point];
layer.events.on({"featuremodified": function(event) {
t.eq(event.feature.id, poly.id, "featuremodified triggered");
}});
control.onModification = function(feature) {
t.eq(feature.id, poly.id,
"onModification called with the right feature on vertex delete");
};
point.geometry.parent = poly.geometry;
control.dragControl.feature = point;
control.handleKeypress({keyCode:46});
layer.drawFeature = oldDraw;
map.destroy();
}
function test_onModificationEnd(t) {
t.plan(3);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
// make sure onModificationEnd is called on unselect feature
var testFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(Math.random(), Math.random())
);
layer.events.on({"afterfeaturemodified": function(event) {
t.eq(event.feature.id, testFeature.id, "afterfeaturemodified triggered");
t.eq(event.modified, false, "afterfeaturemodified event given proper modified property (false - feature was not modified in this case)");
}});
control.onModificationEnd = function(feature) {
t.eq(feature.id, testFeature.id,
"onModificationEnd called with the right feature");
};
control.unselectFeature(testFeature);
map.destroy();
}
function test_events(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.ModifyFeature(layer);
map.addControl(control);
control.activate();
// make sure onModificationStart is called on feature selection
var testFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(Math.random(), Math.random())
);
// test that beforefeatureselected is triggered
function handle_beforefeatureselected(event) {
t.ok(event.feature == testFeature, "beforefeatureselected called with the correct feature");
}
layer.events.on({
"beforefeatureselected": handle_beforefeatureselected
});
layer.events.triggerEvent("beforefeatureselected", {
feature: testFeature
});
layer.events.un({
"beforefeatureselected": handle_beforefeatureselected
});
// test that beforefeatureselected is triggered
function handle_featureselected(event) {
t.ok(event.feature == testFeature, "featureselected called with the correct feature");
}
layer.events.on({
"featureselected": handle_featureselected
});
layer.events.triggerEvent("featureselected", {
feature: testFeature
});
layer.events.un({
"featureselected": handle_featureselected
});
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,88 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map, control;
function test_initialize (t) {
t.plan( 2 );
control = new OpenLayers.Control.MousePosition();
t.ok( control instanceof OpenLayers.Control.MousePosition, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlMousePosition", "displayClass is correct" );
}
function test_redraw_noLayer_displayProjection(t) {
t.plan(2);
control = new OpenLayers.Control.MousePosition({'displayProjection': new OpenLayers.Projection("WGS84")});
map = new OpenLayers.Map('map');
map.addControl(control);
control.redraw({'xy': new OpenLayers.Pixel(10,10)});
control.redraw({'xy': new OpenLayers.Pixel(12,12)});
t.eq(control.div.innerHTML, "", "innerHTML set correctly");
l = new OpenLayers.Layer('name', {'isBaseLayer': true});
map.addLayer(l);
map.zoomToMaxExtent();
control.redraw({'xy': new OpenLayers.Pixel(10,10)});
control.redraw({'xy': new OpenLayers.Pixel(12,12)});
t.eq(control.div.innerHTML, "-175.78125, 85.78125", "innerHTML set correctly when triggered.");
}
function test_destroy(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control.MousePosition();
map.addControl(control);
var listeners = map.events.listeners.mousemove.length;
control.destroy();
t.eq(map.events.listeners.mousemove.length, listeners - 1, "mousemove event is unregistered");
map.destroy();
}
function test_addControl(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control.MousePosition();
map.addControl(control);
t.ok(control.map === map, "Control.map is set to the map object");
t.ok(map.controls[map.controls.length - 1] === control, "map.controls contains control");
t.eq(parseInt(control.div.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Control div zIndexed properly" );
t.eq(parseInt(map.viewPortDiv.lastChild.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Viewport div contains control div");
map.destroy();
}
function test_redraw_noLayer_displayProjection(t) {
t.plan(3);
var control = new OpenLayers.Control.MousePosition();
var map = new OpenLayers.Map('map');
map.addControl(control);
t.eq(control.div.innerHTML, "0.00000, 0.00000", "innerHTML set correctly");
control.redraw({'xy': new OpenLayers.Pixel(10,10)});
control.redraw({'xy': new OpenLayers.Pixel(12,12)});
t.eq(control.div.innerHTML, "0.00000, 0.00000", "innerHTML set correctly");
var l = new OpenLayers.Layer('name', {'isBaseLayer': true});
map.addLayer(l);
map.zoomToMaxExtent();
control.redraw({'xy': new OpenLayers.Pixel(10,10)});
control.redraw({'xy': new OpenLayers.Pixel(12,12)});
t.eq(control.div.innerHTML, "-175.78125, 85.78125", "innerHTML set correctly when triggered.");
map.destroy();
}
function test_formatOutput(t) {
t.plan(1);
var control = new OpenLayers.Control.MousePosition({
prefix: 'prefix',
suffix: 'suffix',
separator: 'separator',
numDigits: 3
});
var lonlat = new OpenLayers.LonLat(0.75699, 0.37365);
var val = control.formatOutput(lonlat);
t.eq(val, 'prefix0.757separator0.374suffix', 'formatOutput correctly formats the mouse position output');
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,59 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_MouseToolbar_constructor (t) {
t.plan( 1 );
control = new OpenLayers.Control.MouseToolbar();
t.ok( control instanceof OpenLayers.Control.MouseToolbar, "new OpenLayers.Control.MouseToolbar returns object" );
}
function test_Control_MouseToolbar_addControl (t) {
t.plan( 8 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.MouseToolbar();
t.ok( control instanceof OpenLayers.Control.MouseToolbar, "new OpenLayers.Control.MouseToolbar returns object" );
t.ok( map instanceof OpenLayers.Map, "new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( map.controls[4] === control, "map.controls contains control" );
t.eq( parseInt(control.div.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Control div zIndexed properly" );
t.eq( parseInt(map.viewPortDiv.lastChild.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Viewport div contains control div" );
t.eq( control.div.style.left, "6px", "Control div left located correctly by default");
t.eq( control.div.style.top, "300px", "Control div top located correctly by default");
}
function test_Control_MouseToolbar_control_events (t) {
t.plan( 1 );
if ((navigator.userAgent.indexOf("compatible") == -1)) {
var evt = {which: 1}; // control expects left-click
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.MouseToolbar();
map.addControl(control);
var centerLL = new OpenLayers.LonLat(0,0);
map.setCenter(centerLL, 5);
evt.shiftKey = true;
evt.xy = new OpenLayers.Size(5,5);
control.defaultMouseDown(evt);
evt.xy = new OpenLayers.Size(15,15);
control.defaultMouseUp(evt);
t.eq(map.getZoom(), 6, "Map zoom set correctly after zoombox");
} else {
t.ok(true, "IE does not run this test.")
}
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,34 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_NavToolbar_constructor (t) {
t.plan( 4 );
control = new OpenLayers.Control.NavToolbar();
t.ok( control instanceof OpenLayers.Control.NavToolbar, "new OpenLayers.Control.NavToolbar returns object" );
t.eq( control.displayClass, "olControlNavToolbar", "displayClass is correct" );
t.ok( control.controls[0] instanceof OpenLayers.Control.Navigation, "NavToolbar contains Control.Navigation object" );
t.ok( control.controls[1] instanceof OpenLayers.Control.ZoomBox, "NavToolbar contains Control.ZoomBox object" );
}
function test_Control_NavToolbar_addControl (t) {
t.plan( 6 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.NavToolbar();
t.ok( control instanceof OpenLayers.Control.NavToolbar, "new OpenLayers.Control.NavToolbar returns object" );
t.ok( map instanceof OpenLayers.Map, "new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( map.controls[4] === control, "map.controls contains control" );
t.eq( parseInt(control.div.style.zIndex), map.Z_INDEX_BASE['Control'] + 7, "Control div zIndexed properly" );
t.eq( parseInt(map.viewPortDiv.lastChild.style.zIndex), map.Z_INDEX_BASE['Control'] + 7, "Viewport div contains control div" );
// t.eq( control.div.style.top, "6px", "Control div top located correctly by default");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,104 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_Navigation_constructor (t) {
t.plan( 3 );
var temp = OpenLayers.Control.prototype.initialize;
OpenLayers.Control.prototype.initialize = function() {
t.ok(true, "OpenLayers.Control's constructor called");
};
var control = new OpenLayers.Control.Navigation();
t.ok( control instanceof OpenLayers.Control.Navigation, "new OpenLayers.Control returns object" );
t.ok( !control.handleRightClicks, "'handleRightClicks' property is disabled by default");
OpenLayers.Control.prototype.initialize = temp;
}
function test_Control_Navigation_destroy (t) {
t.plan(10);
var temp = OpenLayers.Control.prototype.destroy;
OpenLayers.Control.prototype.destroy = function() {
t.ok(true, "OpenLayers.Control's destroy called");
temp.call(this);
};
var control = {
events: {
destroy: function() {
t.ok(true, "events destroyed");
}
},
'deactivate': function() {
t.ok(true, "navigation control deactivated before being destroyed");
},
'dragPan': {
'destroy': function() {
t.ok(true, "dragPan destroyed");
}
},
'zoomBox': {
'destroy': function() {
t.ok(true, "zoomBox destroyed");
}
},
handlers: {
'wheel': {
'destroy': function() {
t.ok(true, "wheelHandler destroyed");
}
},
'click': {
'destroy': function() {
t.ok(true, "clickHandler destroyed");
}
}
}
};
//this will also trigger one test by calling OpenLayers.Control's destroy
// and three more for the destruction of dragPan, zoomBox, and wheelHandler
OpenLayers.Control.Navigation.prototype.destroy.apply(control, []);
t.eq(control.dragPan, null, "'dragPan' set to null");
t.eq(control.zoomBox, null, "'zoomBox' set to null");
t.eq(control.handlers, null, "handlers set to null");
OpenLayers.Control.prototype.destroy = temp;
}
function test_Control_Navigation_disableZoomWheel(t) {
t.plan(2);
var nav = new OpenLayers.Control.Navigation();
var wheel = new OpenLayers.Handler.MouseWheel(nav, {});
nav.handlers.wheel = wheel;
wheel.register = function() {};
wheel.unregister = function() {};
wheel.activate();
nav.disableZoomWheel();
t.eq(nav.zoomWheelEnabled, false, "mouse wheel deactivated");
t.eq(wheel.active, false, "mouse wheel handler deactivated");
}
function test_Control_Navigation_enableZoomWheel(t) {
t.plan(2);
var nav = new OpenLayers.Control.Navigation({zoomWheelEnabled: false});
nav.active = true;
var wheel = new OpenLayers.Handler.MouseWheel(nav, {});
wheel.register = function() {};
wheel.unregister = function() {};
nav.handlers.wheel = wheel;
nav.enableZoomWheel();
t.eq(nav.zoomWheelEnabled, true, "mouse wheel activated");
t.eq(wheel.active, true, "mouse wheel handler activated");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,176 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(4);
control = new OpenLayers.Control.NavigationHistory();
t.ok(control instanceof OpenLayers.Control.NavigationHistory,
"constructor returns correct instance");
t.eq(control.displayClass, "olControlNavigationHistory",
"displayClass is correct");
t.ok(control.next instanceof OpenLayers.Control.Button,
"constructor creates next control");
t.ok(control.previous instanceof OpenLayers.Control.Button,
"constructor creates previous control");
}
function test_destroy(t) {
t.plan(2);
control = new OpenLayers.Control.NavigationHistory();
control.next.destroy = function() {
t.ok(true, "destroy calls next.destroy");
}
control.previous.destroy = function() {
t.ok(true, "destroy calls previous.destroy");
}
control.destroy();
}
function test_previous(t) {
var numStates = 10;
t.plan(
numStates * 3 // for lon, lat, zoom
+ 3 // for confirming that previous with empty stack works
);
var history = new Array(numStates);
for(var i=0; i<numStates; ++i) {
history[i] = {
center: new OpenLayers.LonLat(
(i * 360 / numStates) - 180, (i * 180 / numStates) - 90
),
zoom: i
};
}
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer(
"test", {isBaseLayer: true}
);
map.addLayer(layer);
var control = new OpenLayers.Control.NavigationHistory();
map.addControl(control);
// set previous states
for(i=0; i<numStates; ++i) {
map.setCenter(history[i].center, history[i].zoom);
}
// test previous states
for(i=numStates-1; i>=0; --i) {
t.eq(map.getCenter().lon, history[i].center.lon, "(step " + i + ") lon correct");
t.eq(map.getCenter().lat, history[i].center.lat, "(step " + i + ") lat correct");
t.eq(map.getZoom(), history[i].zoom, "(step " + i + ") zoom correct");
control.previous.trigger();
}
// test previous with empty stack
t.eq(map.getCenter().lon, history[0].center.lon, "(step 0 again) lon correct");
t.eq(map.getCenter().lat, history[0].center.lat, "(step 0 again) lat correct");
t.eq(map.getZoom(), history[0].zoom, "(step 0 again) zoom correct");
}
function test_next(t) {
var numStates = 10;
t.plan(
numStates * 3 // for lon, lat, zoom
+ 3 // for confirming that next with empty stack works
);
var history = new Array(numStates);
for(var i=0; i<numStates; ++i) {
history[i] = {
center: new OpenLayers.LonLat(
(i * 360 / numStates) - 180, (i * 180 / numStates) - 90
),
zoom: i
};
}
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer(
"test", {isBaseLayer: true}
);
map.addLayer(layer);
var control = new OpenLayers.Control.NavigationHistory();
map.addControl(control);
// set previous states
for(i=0; i<numStates; ++i) {
map.setCenter(history[i].center, history[i].zoom);
}
// set next states
for(i=numStates-1; i>=0; --i) {
control.previous.trigger();
}
// test next states
for(i=0; i<numStates; ++i) {
t.eq(map.getCenter().lon, history[i].center.lon, "(step " + i + ") lon correct");
t.eq(map.getCenter().lat, history[i].center.lat, "(step " + i + ") lat correct");
t.eq(map.getZoom(), history[i].zoom, "(step " + i + ") zoom correct");
control.next.trigger();
}
// test next with empty stack
t.eq(map.getCenter().lon, history[numStates-1].center.lon, "(step " + (numStates-1) + " again) lon correct");
t.eq(map.getCenter().lat, history[numStates-1].center.lat, "(step " + (numStates-1) + " again) lat correct");
t.eq(map.getZoom(), history[numStates-1].zoom, "(step " + (numStates-1) + " again) zoom correct");
}
function test_limit(t) {
var numStates = 10;
var limit = 3;
t.plan(
numStates * 6 // for previous & next lon, lat, zoom
);
var history = new Array(numStates);
for(var i=0; i<numStates; ++i) {
history[i] = {
center: new OpenLayers.LonLat(
(i * 360 / numStates) - 180, (i * 180 / numStates) - 90
),
zoom: i
};
}
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer(
"test", {isBaseLayer: true}
);
map.addLayer(layer);
var control = new OpenLayers.Control.NavigationHistory({limit: limit});
map.addControl(control);
// set previous states
for(i=0; i<numStates; ++i) {
map.setCenter(history[i].center, history[i].zoom);
}
// test previous states (only up to limit should work)
var state;
for(i=numStates-1; i>=0; --i) {
state = Math.max(i, numStates - limit - 1);
t.eq(map.getCenter().lon, history[state].center.lon, "(previous step " + i + ") lon correct: state " + state);
t.eq(map.getCenter().lat, history[state].center.lat, "(previous step " + i + ") lat correct: state " + state);
t.eq(map.getZoom(), history[state].zoom, "(previous step " + i + ") zoom correct: state " + state);
control.previous.trigger();
}
// test next states
for(i=0; i<numStates; ++i) {
state = Math.min(numStates - 1, numStates - limit - 1 + i);
t.eq(map.getCenter().lon, history[state].center.lon, "(next step " + i + ") lon correct: state " + state);
t.eq(map.getCenter().lat, history[state].center.lat, "(next step " + i + ") lat correct: state " + state);
t.eq(map.getZoom(), history[state].zoom, "(next step " + i + ") zoom correct: state " + state);
control.next.trigger();
}
}
</script>
</head>
<body>
<div id="map" style="width: 100px; height: 100px;"/>
</body>
</html>

View File

@ -1,80 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_initialize(t) {
t.plan( 2 );
control = new OpenLayers.Control.OverviewMap();
t.ok( control instanceof OpenLayers.Control.OverviewMap, "new OpenLayers.Control.OverviewMap returns object" );
t.eq( control.displayClass, "olControlOverviewMap", "displayClass is correct" );
}
function test_addControl (t) {
t.plan( 6 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.OverviewMap();
t.ok( control instanceof OpenLayers.Control.OverviewMap, "new OpenLayers.Control.OverviewMap returns object" );
t.ok( map instanceof OpenLayers.Map, "new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( map.controls[4] === control, "map.controls contains control" );
t.eq( parseInt(control.div.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Control div zIndexed properly" );
t.eq( parseInt(map.viewPortDiv.lastChild.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Viewport div contains control div" );
map.destroy();
}
function test_control_events (t) {
t.plan( 10 );
var evt = {which: 1}; // control expects left-click
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.OverviewMap();
map.addControl(control, new OpenLayers.Pixel(20,20));
var centerLL = new OpenLayers.LonLat(-71,42);
map.setCenter(centerLL, 11);
t.delay_call(1, function() {
var overviewCenter = control.ovmap.getCenter();
var overviewZoom = control.ovmap.getZoom();
t.eq(overviewCenter.lon, -71, "Overviewmap center lon correct");
t.eq(overviewCenter.lat, 42, "Overviewmap center lat correct");
t.eq(overviewZoom, 8, "Overviewmap zoomcorrect");
control.mapDivClick({'xy':new OpenLayers.Pixel(5,5)});
}, 2, function() {
var cent = map.getCenter();
t.eq(cent.lon, -71.3515625, "Clicking on the Overview Map has the correct effect on map lon");
t.eq(cent.lat, 42.17578125, "Clicking on the Overview Map has the correct effect on map lat");
control.handlers.drag = {
last: new OpenLayers.Pixel(5,5),
destroy: function() {}
};
control.rectDrag(new OpenLayers.Pixel(15, 15));
control.updateMapToRect();
}, 2, function() {
var cent = map.getCenter();
t.eq(cent.lon, -71.2734375, "Dragging on the Overview Map has the correct effect on map lon");
t.eq(cent.lat, 42.09765625, "Dragging on the Overview Map has the correct effect on map lat");
map.setCenter(new OpenLayers.LonLat(0,0), 0);
var overviewCenter = control.ovmap.getCenter();
var overviewZoom = control.ovmap.getZoom();
t.eq(overviewCenter.lon, 0, "Overviewmap center lon correct -- second zoom");
t.eq(overviewCenter.lat, 0, "Overviewmap center lat correct -- second zoom");
t.eq(overviewZoom, 0, "Overviewmap zoomcorrect -- second zoom");
map.destroy();
});
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,230 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_PanZoom_constructor (t) {
t.plan( 4 );
control = new OpenLayers.Control.PanZoom();
t.ok( control instanceof OpenLayers.Control.PanZoom, "new OpenLayers.Control.PanZoom returns object" );
t.eq( control.displayClass, "olControlPanZoom", "displayClass is correct" );
control = new OpenLayers.Control.PanZoom({position: new OpenLayers.Pixel(100,100)});
t.eq( control.position.x, 100, "PanZoom X Set correctly.");
t.eq( control.position.y, 100, "PanZoom y Set correctly.");
}
function test_Control_PanZoom_addControl (t) {
t.plan( 8 );
map = new OpenLayers.Map('map');
control = new OpenLayers.Control.PanZoom();
t.ok( control instanceof OpenLayers.Control.PanZoom, "new OpenLayers.Control.PanZoom returns object" );
t.ok( map instanceof OpenLayers.Map, "new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( map.controls[4] === control, "map.controls contains control" );
t.eq( parseInt(control.div.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Control div zIndexed properly" );
t.eq( parseInt(map.viewPortDiv.lastChild.style.zIndex), map.Z_INDEX_BASE['Control'] + 5, "Viewport div contains control div" );
t.eq( control.div.style.top, "4px", "Control div top located correctly by default");
var control2 = new OpenLayers.Control.PanZoom();
map.addControl(control2, new OpenLayers.Pixel(100,100));
t.eq( control2.div.style.top, "100px", "2nd control div is located correctly");
}
function test_Control_PanZoom_removeButtons(t) {
t.plan(2);
map = new OpenLayers.Map("map");
control = new OpenLayers.Control.PanZoom();
map.addControl(control);
control.removeButtons();
t.eq(control.buttons.length, 0, "buttons array cleared correctly");
t.eq(control.div.childNodes.length, 0, "control div is empty");
}
function test_Control_PanZoom_control_events (t) {
if ( !window.document.createEvent || OpenLayers.Util.getBrowserName() == "opera" || !t.open_window) {
//ie can't simulate mouseclicks
t.plan(0);
t.debug_print("FIXME: This browser does not support the PanZoom test at this time.");
} else {
t.plan(35);
t.open_window( "Control/PanZoom.html", function( wnd ) {
t.delay_call( 3, function() {
var flag;
function setFlag(evt) {
flag[evt.type] = true;
}
function resetFlags() {
flag = {
mousedown: false,
mouseup: false,
click: false,
dblclick: false
};
}
resetFlags();
wnd.mapper.events.register("mousedown", mapper, setFlag);
wnd.mapper.events.register("mouseup", mapper, setFlag);
wnd.mapper.events.register("click", mapper, setFlag);
wnd.mapper.events.register("dblclick", mapper, setFlag);
simulateClick(wnd, wnd.control.buttons[0]);
t.delay_call(2, function() {
t.ok( wnd.mapper.getCenter().lat > wnd.centerLL.lat, "Pan up works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[1]);
}, 2, function() {
t.ok( wnd.mapper.getCenter().lon < wnd.centerLL.lon, "Pan left works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[2]);
}, 2, function() {
t.ok( wnd.mapper.getCenter().lon == wnd.centerLL.lon, "Pan right works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[3]);
}, 2, function() {
t.ok( wnd.mapper.getCenter().lat == wnd.centerLL.lat, "Pan down works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[4]);
}, 2, function() {
t.eq( wnd.mapper.getZoom(), 6, "zoomin works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[6]);
}, 2, function() {
t.eq( wnd.mapper.getZoom(), 5, "zoomout works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
simulateClick(wnd, wnd.control.buttons[5]);
}, 2, function() {
t.eq( wnd.mapper.getZoom(), 2, "zoomworld works correctly" );
t.ok(!flag.mousedown, "mousedown does not get to the map");
t.ok(flag.mouseup, "mouseup does get to the map");
t.ok(!flag.click, "click does not get to the map");
t.ok(!flag.dblclick, "dblclick does not get to the map");
resetFlags();
});
});
});
}
}
function test_slideRatio(t) {
t.plan(4);
var control = new OpenLayers.Control.PanZoom({
slideRatio: .5
});
var map = new OpenLayers.Map();
map.addControl(control);
control.draw();
control.activate();
map.getSize = function() {
return {
w: 250,
h: 100
}
};
var delta, dir;
var evt = {which: 1}; // a fake left click
var buttons = control.buttons;
map.pan = function(dx, dy){
t.eq([dx,dy],delta,"Panning " + dir + " sets right delta with slideRatio");
};
//up
var delta = [0, -50];
var dir = "up";
control.buttonDown.call(buttons[0], evt);
//left
var delta = [-125, 0];
var dir = "left";
control.buttonDown.call(buttons[1], evt);
//right
var delta = [125, 0];
var dir = "right";
control.buttonDown.call(buttons[2], evt);
//down
var delta = [0, 50];
var dir = "down";
control.buttonDown.call(buttons[3], evt);
map.destroy();
}
function simulateClick(wnd, elem) {
var evt = wnd.document.createEvent("MouseEvents");
evt.initMouseEvent("mousedown", true, true, wnd, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
evt = wnd.document.createEvent("MouseEvents");
evt.initMouseEvent("mouseup", true, true, wnd, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
evt = wnd.document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, wnd, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
evt = wnd.document.createEvent("MouseEvents");
evt.initMouseEvent("dblclick", true, true, wnd, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
}
function loader() {
control = new OpenLayers.Control.PanZoom();
mapper = new OpenLayers.Map('map', { controls: [control]});
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://labs.metacarta.com/wms-c/Basic.py?",
{layers: "basic"});
mapper.addLayer(layer);
centerLL = new OpenLayers.LonLat(0,0);
mapper.setCenter(centerLL, 5);
}
</script>
</head>
<body onload="loader()">
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,75 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_PanZoomBar_constructor (t) {
t.plan( 4 );
control = new OpenLayers.Control.PanZoomBar({position: new OpenLayers.Pixel(100,100)});
t.ok( control instanceof OpenLayers.Control.PanZoomBar, "new OpenLayers.Control.PanZoomBar returns object" );
t.eq( control.displayClass, "olControlPanZoomBar", "displayClass is correct" );
t.eq( control.position.x, 100, "PanZoom X Set correctly.");
t.eq( control.position.y, 100, "PanZoom y Set correctly.");
}
function test_Control_PanZoomBar_addControl (t) {
t.plan( 8 );
map = new OpenLayers.Map('map', {controls:[]});
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.PanZoomBar();
t.ok( control instanceof OpenLayers.Control.PanZoomBar, "new OpenLayers.Control.PanZoomBar returns object" );
t.ok( map instanceof OpenLayers.Map, "new OpenLayers.Map creates map" );
map.addControl(control);
t.ok( control.map === map, "Control.map is set to the map object" );
t.ok( map.controls[0] === control, "map.controls contains control" );
t.eq( parseInt(control.div.style.zIndex), 1001, "Control div zIndexed properly" );
t.eq( parseInt(map.viewPortDiv.lastChild.style.zIndex), 1001, "Viewport div contains control div" );
t.eq( control.div.style.top, "4px", "Control div top located correctly by default");
var control2 = new OpenLayers.Control.PanZoomBar();
map.addControl(control2, new OpenLayers.Pixel(100,100));
t.eq( control2.div.style.top, "100px", "2nd control div is located correctly");
}
function test_Control_PanZoomBar_clearDiv(t) {
t.plan(2);
map = new OpenLayers.Map('map', {controls:[]});
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.PanZoomBar();
map.addControl(control);
control.removeButtons();
control._removeZoomBar();
t.eq(control.div.childNodes.length, 0, "control's div cleared.");
t.eq(control.zoombarDiv, null, "zoombar div nullified.")
}
function test_Control_PanZoomBar_divClick (t) {
t.plan(2);
map = new OpenLayers.Map('map', {controls:[]});
var layer = new OpenLayers.Layer.WMS("Test Layer",
"http://octo.metacarta.com/cgi-bin/mapserv?",
{map: "/mapdata/vmap_wms.map", layers: "basic"});
map.addLayer(layer);
control = new OpenLayers.Control.PanZoomBar();
map.addControl(control);
control.divClick({'xy': {'x': 0, 'y': 50}, which: 1});
t.eq(map.zoom, 11, "zoom is correct on standard map");
map.fractionalZoom = true;
control.divClick({'xy': {'x': 0, 'y': 49}, which: 1});
t.eq(map.zoom.toFixed(3), '10.545', "zoom is correct on fractional zoom map");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,126 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_Panel_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.Panel();
t.ok( control instanceof OpenLayers.Control.Panel, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlPanel", "displayClass is correct" );
}
function test_Control_Panel_constructor (t) {
t.plan(6);
var map = new OpenLayers.Map('map');
var panel = new OpenLayers.Control.Panel();
var toolControl = new OpenLayers.Control.ZoomBox();
var AnotherToolControl = OpenLayers.Class(OpenLayers.Control, {
CLASS_NAME: 'mbControl.TestTool',
type: OpenLayers.Control.TYPE_TOOL
});
var anotherToolControl = new AnotherToolControl();
var ToggleControl = OpenLayers.Class(OpenLayers.Control, {
CLASS_NAME: 'mbControl.TestToggle',
type: OpenLayers.Control.TYPE_TOGGLE
});
var toggleControl = new ToggleControl();
t.ok(panel instanceof OpenLayers.Control.Panel,
"new OpenLayers.Control.Panel returns object");
panel.addControls([toolControl, anotherToolControl, toggleControl]);
t.eq(panel.controls.length, 3,
"added three controls to the panel");
map.addControl(panel);
panel.activateControl(toolControl);
t.ok(toolControl.active && !anotherToolControl.active && !toggleControl.active,
"activated one tool control, the other one is inactive and the toggle control also.");
panel.redraw = function(){
t.ok(true,"Redraw called on activated toggle");
}
panel.activateControl(toggleControl);
t.ok(toolControl.active && !anotherToolControl.active && toggleControl.active,
"activated the toggle control, which has no influence on the tool controls.");
panel.activateControl(anotherToolControl);
t.ok(!toolControl.active && anotherToolControl.active && toggleControl.active,
"activated the other tool control, the first one is inactive and the toggle control still active.");
}
function test_Control_Panel_titles (t) {
t.plan(2);
var panel = new OpenLayers.Control.Panel();
var toolControl = new OpenLayers.Control.ZoomBox({
title:"Zoom box: Selecting it you can zoom on an area by clicking and dragging."
});
panel.addControls([toolControl]);
t.eq(panel.controls.length, 1, "added a control to the panel");
t.eq(panel.controls[0].title, toolControl.panel_div.title, "the title is correctly set");
}
function test_Control_Panel_getBy(t) {
var panel = {
getBy: OpenLayers.Control.Panel.prototype.getBy,
getControlsBy: OpenLayers.Control.Panel.prototype.getControlsBy,
controls: [
{foo: "foo", id: Math.random()},
{foo: "bar", id: Math.random()},
{foo: "foobar", id: Math.random()},
{foo: "foo bar", id: Math.random()},
{foo: "foo", id: Math.random()}
]
};
var cases = [
{
got: panel.getControlsBy("foo", "foo"),
expected: [panel.controls[0], panel.controls[4]],
message: "(string literal) got two controls matching foo"
}, {
got: panel.getControlsBy("foo", "bar"),
expected: [panel.controls[1]],
message: "(string literal) got one control matching foo"
}, {
got: panel.getControlsBy("foo", "barfoo"),
expected: [],
message: "(string literal) got empty array for no foo match"
}, {
got: panel.getControlsBy("foo", /foo/),
expected: [panel.controls[0], panel.controls[2], panel.controls[3], panel.controls[4]],
message: "(regexp literal) got three controls containing string"
}, {
got: panel.getControlsBy("foo", /foo$/),
expected: [panel.controls[0], panel.controls[4]],
message: "(regexp literal) got three controls ending with string"
}, {
got: panel.getControlsBy("foo", /\s/),
expected: [panel.controls[3]],
message: "(regexp literal) got control containing space"
}, {
got: panel.getControlsBy("foo", new RegExp("BAR", "i")),
expected: [panel.controls[1], panel.controls[2], panel.controls[3]],
message: "(regexp object) got layers ignoring case"
}, {
got: panel.getControlsBy("foo", {test: function(str) {return str.length > 3;}}),
expected: [panel.controls[2], panel.controls[3]],
message: "(custom object) got controls with foo length greater than 3"
}
];
t.plan(cases.length);
for(var i=0; i<cases.length; ++i) {
t.eq(cases[i].got, cases[i].expected, cases[i].message);
}
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,237 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_Permalink_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.Permalink();
t.ok( control instanceof OpenLayers.Control.Permalink, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlPermalink", "displayClass is correct" );
}
function test_Control_Permalink_uncentered (t) {
t.plan( 1 );
control = new OpenLayers.Control.Permalink('permalink');
map = new OpenLayers.Map('map');
map.addControl(control);
map.events.triggerEvent("changelayer", {});
t.ok(true, "permalink didn't bomb out.");
}
function test_Control_Permalink_initwithelem (t) {
t.plan( 1 );
control = new OpenLayers.Control.Permalink(OpenLayers.Util.getElement('permalink'));
t.ok(true, "If the above line doesn't throw an error, we're safe.");
}
function test_Control_Permalink_updateLinks (t) {
t.plan( 3 );
control = new OpenLayers.Control.Permalink('permalink');
t.ok( control instanceof OpenLayers.Control.Permalink, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'}, {'isBaseLayer': false});
map.addLayer(layer);
layer.setVisibility(true);
if (!map.getCenter()) map.zoomToMaxExtent();
map.addControl(control);
map.pan(5, 0, {animate:false});
t.ok(OpenLayers.Util.isEquivalentUrl(OpenLayers.Util.getElement('permalink').href, location+"?zoom=2&lat=0&lon=1.75781&layers=BT"), 'pan sets permalink');
map.layers[1].setVisibility(false);
t.ok(OpenLayers.Util.isEquivalentUrl(OpenLayers.Util.getElement('permalink').href, location+"?zoom=2&lat=0&lon=1.75781&layers=BF"), 'setVisibility sets permalink');
}
function test_Control_Permalink_updateLinksBase (t) {
t.plan( 2 );
control = new OpenLayers.Control.Permalink('permalink', "./edit.html" );
t.ok( control instanceof OpenLayers.Control.Permalink, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
if (!map.getCenter()) map.zoomToMaxExtent();
map.addControl(control);
map.pan(5, 0, {animate:false});
OpenLayers.Util.getElement('edit_permalink').href = './edit.html?zoom=2&lat=0&lon=1.75781&layers=B';
t.eq(OpenLayers.Util.getElement('permalink').href, OpenLayers.Util.getElement('edit_permalink').href, "Panning sets permalink with base");
}
function test_Control_Permalink_noElement (t) {
t.plan( 2 );
control = new OpenLayers.Control.Permalink( );
t.ok( control instanceof OpenLayers.Control.Permalink, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
map.addControl(control);
t.eq(map.controls[4].div.firstChild.nodeName, "A", "Permalink control creates div with 'a' inside." );
}
function test_Control_Permalink_base_with_query (t) {
t.plan( 3 );
control = new OpenLayers.Control.Permalink('permalink', "./edit.html?foo=bar" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://example.com" );
map.addLayer(layer);
if (!map.getCenter()) map.zoomToMaxExtent();
map.addControl(control);
map.pan(5, 0, {animate:false});
OpenLayers.Util.getElement('edit_permalink').href = './edit.html?foo=bar&zoom=2&lat=0&lon=1.75781&layers=B';
t.eq(OpenLayers.Util.getElement('permalink').href, OpenLayers.Util.getElement('edit_permalink').href, "Panning sets permalink with base and querystring");
control = new OpenLayers.Control.Permalink('permalink', "./edit.html?foo=bar&" );
map.addControl(control);
map.pan(0, 0, {animate:false});
t.eq(OpenLayers.Util.getElement('permalink').href, OpenLayers.Util.getElement('edit_permalink').href, "Panning sets permalink with base and querystring ending with '&'");
control = new OpenLayers.Control.Permalink('permalink', "./edit.html?" );
OpenLayers.Util.getElement('edit_permalink').href = './edit.html?zoom=2&lat=0&lon=1.75781&layers=B';
map.addControl(control);
map.pan(5, 0, {animate:false});
map.pan(-5, 0, {animate:false});
t.eq(OpenLayers.Util.getElement('permalink').href, OpenLayers.Util.getElement('edit_permalink').href, "Panning sets permalink with base and querystring ending with '?'");
}
function test_Control_Permalink_nonRepeating (t) {
t.plan( 2 );
control = new OpenLayers.Control.Permalink('permalink', "./edit.html?zoom=3" );
t.ok( control instanceof OpenLayers.Control.Permalink, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
if (!map.getCenter()) map.zoomToMaxExtent();
map.addControl(control);
map.pan(5, 0, {animate:false});
OpenLayers.Util.getElement('edit_permalink').href = './edit.html?zoom=2&lat=0&lon=1.75781&layers=B';
t.eq(OpenLayers.Util.getElement('permalink').href, OpenLayers.Util.getElement('edit_permalink').href, "Panning sets permalink with existing zoom in base");
}
function test_Control_Permalink_customized(t) {
t.plan(2);
var argParserClass = OpenLayers.Class(OpenLayers.Control.ArgParser, {
CLASS_NAME: "CustomArgParser"
});
control = new OpenLayers.Control.Permalink(null, "./edit.html", {
argParserClass: argParserClass,
createParams: function(center, zoom, layers) {
var params = OpenLayers.Control.Permalink.prototype.createParams.apply(control, arguments);
params.customParam = "foo";
return params;
}
});
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
if (!map.getCenter()) map.zoomToMaxExtent();
map.addControl(control);
map.pan(5, 0, {animate:false});
t.eq(this.map.controls[this.map.controls.length-1].CLASS_NAME, "CustomArgParser", "Custom ArgParser added correctly.");
t.eq(control.div.firstChild.getAttribute("href"), "./edit.html?zoom=2&lat=0&lon=1.75781&layers=B&customParam=foo", "Custom parameter encoded correctly.");
}
function test_Control_Permalink_createParams(t) {
t.plan(18);
var baseLayer = { 'isBaseLayer': true };
var m = {
'getCenter': function() { return null; }
};
var pl = {
'map': m,
'base': {}
};
old_getParameters = OpenLayers.Util.getParameters;
OpenLayers.Util.getParameters = function(base) {
t.ok(base == pl.base, "correct base sent in to Util.getParameters()");
return g_Params;
};
//null center, null map.getCenter()
g_Params = {};
m.baseLayer = baseLayer;
var returnParams = OpenLayers.Control.Permalink.prototype.createParams.apply(pl, []);
t.ok(returnParams == g_Params, "correct params returned on null center");
//valid center, zoom, layers
g_Params = { 'test': {} };
var center = { 'lon': 1.2345678901, 'lat': 9.8765432109 };
var zoom = {};
var layers = [
{ 'isBaseLayer': true },
baseLayer,
{ 'isBaseLayer': false, 'getVisibility': function() { return true; } },
{ 'isBaseLayer': false, 'getVisibility': function() { return false; } }
];
var returnParams = OpenLayers.Control.Permalink.prototype.createParams.apply(pl, [center, zoom, layers]);
t.ok(returnParams.test == g_Params.test, "correct params returned from Util.getParameters() when valid center, zoom, layers");
t.ok(returnParams.zoom == zoom, "params.zoom set correctly when valid center, zoom, layers");
t.eq(returnParams.lon, 1.23457, "lon set and rounded correctly when valid center, zoom, layers");
t.eq(returnParams.lat, 9.87654, "lat set and rounded correctly when valid center, zoom, layers");
t.eq(returnParams.layers, "0BTF", "layers processed correctly when valid center, zoom, layers")
//null center, zoom, layers, with displayProjection
g_Params = { 'test': {} };
g_Projection = {};
m = {
'baseLayer': baseLayer,
'getProjectionObject': function() { return g_Projection; },
'center': { 'lon': {}, 'lat': {} },
'getCenter': function() { return this.center; },
'zoom': {},
'getZoom': function() { return this.zoom; },
'layers': [
{ 'isBaseLayer': false, 'getVisibility': function() { return true; } },
baseLayer,
{ 'isBaseLayer': false, 'getVisibility': function() { return false; } },
{ 'isBaseLayer': true }
],
'getLayers': function() { return this.layers; }
};
pl = {
'base': {},
'map': m,
'displayProjection': {}
};
old_transform = OpenLayers.Projection.transform;
OpenLayers.Projection.transform = function(point, projObj, dispProj) {
t.ok(point.x = m.center.lon, "correct x value passed into transform");
t.ok(point.y = m.center.lat, "correct x value passed into transform");
t.ok(projObj == g_Projection, "correct projection object from map passed into transform");
t.ok(dispProj == pl.displayProjection, "correct displayProjection from control passed into transform");
return { 'x': 9.8765432109, 'y': 1.2345678901 };
};
center = zoom = layers = null;
var returnParams = OpenLayers.Control.Permalink.prototype.createParams.apply(pl, [center, zoom, layers]);
t.ok(returnParams.test == g_Params.test, "correct params returned from Util.getParameters() when null center, zoom, layers, with displayProjection");
t.ok(returnParams.zoom == m.zoom, "params.zoom set correctly when null center, zoom, layers, with displayProjection");
t.eq(returnParams.lon, 9.87654, "lon set, transformed, and rounded correctly when null center, zoom, layers, with displayProjection");
t.eq(returnParams.lat, 1.23457, "lat set, transformed, and rounded correctly when null center, zoom, layers, with displayProjection");
t.eq(returnParams.layers, "TBF0", "layers processed correctly when null center, zoom, layers, with displayProjection");
OpenLayers.Util.getParameters = old_getParameters;
OpenLayers.Projection.transform = old_transform;
}
</script>
</head>
<body>
<a id="permalink" href="">Permalink</a> <br />
<a id="edit_permalink" href="">Edit</a> <br />
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,53 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function test_Control_Scale_constructor (t) {
t.plan( 2 );
control = new OpenLayers.Control.Scale();
t.ok( control instanceof OpenLayers.Control.Scale, "new OpenLayers.Control returns object" );
t.eq( control.displayClass, "olControlScale", "displayClass is correct" );
}
function test_Control_Scale_initwithelem (t) {
t.plan( 1 );
control = new OpenLayers.Control.Scale(OpenLayers.Util.getElement('scale'));
t.ok(true, "If this happens, then we passed. (FF throws an error above otherwise)");
}
function test_Control_Scale_updateScale (t) {
t.plan( 4 );
control = new OpenLayers.Control.Scale('scale');
t.ok( control instanceof OpenLayers.Control.Scale, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.eq(OpenLayers.Util.getElement('scale').innerHTML, "Scale = 1 : 443M", "Scale set by default." );
map.zoomIn();
t.eq(OpenLayers.Util.getElement('scale').innerHTML, "Scale = 1 : 221M", "Zooming in changes scale" );
map.baseLayer.resolutions = [OpenLayers.Util.getResolutionFromScale(110)];
map.zoomTo(0);
t.eq(OpenLayers.Util.getElement('scale').innerHTML, "Scale = 1 : 110", "Scale of 100 isn't rounded" );
}
function test_Control_Scale_internalScale (t) {
t.plan(2);
control = new OpenLayers.Control.Scale();
t.ok( control instanceof OpenLayers.Control.Scale, "new OpenLayers.Control returns object" );
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.eq(control.div.firstChild.innerHTML, "Scale = 1 : 443M", "Internal scale displayed properly.");
}
</script>
</head>
<body>
<a id="scale" href="">Scale</a> <br />
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,189 +0,0 @@
<html>
<head>
<script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA9XNhd8q0UdwNC7YSO4YZghSPUCi5aRYVveCcVYxzezM4iaj_gxQ9t-UajFL70jfcpquH5l1IJ-Zyyw'></script>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var validkey = (window.location.protocol == "file:") ||
(window.location.host == "localhost") ||
(window.location.host == "openlayers.org");
function test_initialize(t) {
t.plan(2);
var control = new OpenLayers.Control.ScaleLine();
t.ok(control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
t.eq(control.displayClass, "olControlScaleLine", "displayClass is correct" );
control.destroy();
}
function test_initwithelem(t) {
t.plan(1);
var control = new OpenLayers.Control.ScaleLine({"div":OpenLayers.Util.getElement('ScaleLine')});
t.ok(true, "If this happens, then we passed. (FF throws an error above otherwise)");
control.destroy();
}
function test_calcDegrees(t) {
t.plan(5);
var control = new OpenLayers.Control.ScaleLine();
t.ok(control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.eq(control.div.firstChild.style.visibility, "visible", "top scale is present.");
t.eq(control.div.lastChild.style.visibility, "visible", "bottom scale is present.");
t.eq(control.div.firstChild.innerHTML, "10000 km", "top scale has correct text.");
t.eq(control.div.lastChild.innerHTML, "5000 mi", "bottom scale has correct text.");
map.destroy();
}
function test_calcsOther (t) {
t.plan(5);
var control = new OpenLayers.Control.ScaleLine();
t.ok(control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
var map = new OpenLayers.Map('map');
map.units = "mi";
var layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.eq(control.div.firstChild.style.visibility, "visible", "top scale is present.");
t.eq(control.div.lastChild.style.visibility, "visible", "bottom scale is present.");
t.eq(control.div.firstChild.innerHTML, "100 km", "top scale has correct text.");
t.eq(control.div.lastChild.innerHTML, "100 mi", "bottom scale has correct text.");
map.destroy();
}
function test_calcMeters (t) {
t.plan(5);
// this example is taken from the projected-map.html OpenLayers example
var lat = 900863;
var lon = 235829;
var zoom = 6;
var map = new OpenLayers.Map( 'map' );
var basemap = new OpenLayers.Layer.WMS( "Boston",
"http://boston.freemap.in/cgi-bin/mapserv?",
{
map: '/www/freemap.in/boston/map/gmaps.map',
layers: 'border,water,roads,rapid_transit,buildings',
format: 'png',
transparent: 'off'
},
{
maxExtent: new OpenLayers.Bounds(33861, 717605, 330846, 1019656),
maxResolution: 296985/1024,
projection:"EPSG:2805", // Used in WMS/WFS requests.
units: "m" // Only neccesary for working with scales.
} );
map.addLayer(basemap);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
map.addControl(new OpenLayers.Control.LayerSwitcher());
var control = new OpenLayers.Control.ScaleLine();
t.ok( control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
map.addControl(control);
t.eq(control.div.firstChild.style.visibility, "visible", "top scale is present.");
t.eq(control.div.lastChild.style.visibility, "visible", "bottom scale is present.");
t.eq(control.div.firstChild.innerHTML, "200 m", "top scale has correct text.");
t.eq(control.div.lastChild.innerHTML, "1000 ft", "bottom scale has correct text.");
map.destroy();
}
function test_useArguments (t) {
t.plan(5);
var control = new OpenLayers.Control.ScaleLine({topOutUnits: 'dd'} );
t.ok( control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.eq(control.div.firstChild.style.visibility, "visible", "top scale is present.");
t.eq(control.div.lastChild.style.visibility, "visible", "bottom scale is present.");
t.eq(control.div.firstChild.innerHTML, "100 dd", "top scale has correct text.");
t.eq(control.div.lastChild.innerHTML, "5000 mi", "bottom scale has correct text.");
map.destroy();
}
function test_respectZoom (t) {
if(validkey) {
t.plan( 4 );
} else {
t.plan( 3 );
}
// ok, switch the units we use for zoomed in values. This will test that we're both
// correctly respecting all specified parameters and that we're switching to the
// "in" units when zoomed in
var control = new OpenLayers.Control.ScaleLine({topOutUnits : "mi", bottomOutUnits: "km", topInUnits: 'ft', bottomInUnits: 'm'});
t.ok( control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS('Test Layer', "http://octo.metacarta.com/cgi-bin/mapserv", {map: '/mapdata/vmap_wms.map', layers: 'basic', format: 'image/jpeg'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
var widthIsOk = true;
for (var i=0; i<map.numZoomLevels && widthIsOk; i++) {
map.zoomTo(i);
var w1 = parseInt(control.eTop.style.width);
var w2 = parseInt(control.eBottom.style.width);
widthIsOk = w1 <= control.maxWidth && w2 <= control.maxWidth;
}
t.ok(widthIsOk, "respects maxWidth at all zoom levels in dd");
widthIsOk = true;
control.maxWidth = 200;
for (var i=0; i<map.numZoomLevels && widthIsOk; i++) {
map.zoomTo(i);
var w1 = parseInt(control.eTop.style.width);
var w2 = parseInt(control.eBottom.style.width);
widthIsOk = w1 <= control.maxWidth && w2 <= control.maxWidth;
}
t.ok(widthIsOk, "respects modified maxWidth at all zoom levels in dd");
if (validkey) {
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.Google('Goog Layer');
var control = new OpenLayers.Control.ScaleLine({topOutUnits : "mi", bottomOutUnits: "km", topInUnits: 'ft', bottomInUnits: 'm'});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
var widthIsOk = true;
for (var i=0; i<map.numZoomLevels && widthIsOk; i++) {
map.zoomTo(i);
var w1 = parseInt(control.eTop.style.width);
var w2 = parseInt(control.eBottom.style.width);
widthIsOk = w1 <= control.maxWidth && w2 <= control.maxWidth;
}
t.ok(widthIsOk, "respects maxWidth at all zoom levels in m");
} else {
t.debug_print("Google tests can't be run from " +
window.location.host);
}
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.Google('Goog Layer');
map.addLayer(layer);
map.destroy();
}
function test_ie_oneunit(t) {
t.plan(2);
var control = new OpenLayers.Control.ScaleLine({bottomOutUnits:'',bottomInUnits:'',maxWidth:150});
t.ok(control instanceof OpenLayers.Control.ScaleLine, "new OpenLayers.Control returns object" );
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS('Test Layer', "bogus", {});
map.addLayer(layer);
map.zoomTo(0);
map.addControl(control);
t.ok(true, "invisible bottom scale doesn't cause scaleline failure (IE only)");
map.destroy();
}
</script>
</head>
<body>
<a id="ScaleLine" href="">ScaleLine</a> <br />
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,381 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Control_SelectFeature_constructor(t) {
t.plan(5);
var options = {
// geometryTypes: "foo"
};
var layer = "bar";
var control = new OpenLayers.Control.SelectFeature([layer], options);
t.ok(control instanceof OpenLayers.Control.SelectFeature,
"new OpenLayers.Control.SelectFeature returns an instance");
t.eq(control.layers[0], "bar",
"constructor with array of layers sets layer correctly");
// t.eq(control.handlers.feature.geometryTypes, "foo",
// "constructor sets options correctly on feature handler");
t.ok(control.layer instanceof OpenLayers.Layer.Vector.RootContainer, "control has a root container layer if constructor was called with an array of layers");
control = new OpenLayers.Control.SelectFeature(layer, options);
t.eq(control.layers, null, "this.layers is null if constructor called with a single layer");
t.eq(control.layer, layer, "this.layer holds the layer that was passed with the constructor if called with a single layer")
}
function test_Control_SelectFeature_destroy(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.SelectFeature(layer, {box: true});
control.handlers.feature.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on feature handler");
}
control.handlers.box.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on box handler");
}
// should nullify the layer property here
control.destroy();
}
function test_Control_SelectFeature_select(t) {
t.plan(4);
var map = new OpenLayers.Map("map");
var layer1 = new OpenLayers.Layer.Vector();
var layer2 = new OpenLayers.Layer.Vector();
map.addLayers([layer1, layer2]);
var control = new OpenLayers.Control.SelectFeature([layer1, layer2]);
var feature1 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,1));
var feature2 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,0));
layer1.addFeatures(feature1);
layer2.addFeatures(feature2);
var drawFeature = function(feature, style) {
feature.layer.styleMap.createSymbolizer(feature, style);
}
layer1.drawFeature = drawFeature;
layer2.drawFeature = drawFeature;
control.select(feature1);
t.eq(feature1.renderIntent, "select", "render intent is set to select");
control.select(feature2);
t.eq(feature2.renderIntent, "select", "render intent is set to select");
control.unselect(feature1);
t.eq(feature1.renderIntent, "default", "render intent is set back to default");
control.unselect(feature2);
t.eq(feature2.renderIntent, "default", "render intent is set back to default");
}
function test_Control_SelectFeature_clickFeature(t) {
t.plan(6);
// mock up layer
var layer = {
selectedFeatures: [],
drawFeature: function() {},
events: {
triggerEvent: function() {}
}
};
// mock up active control
var control = new OpenLayers.Control.SelectFeature(layer);
control.handlers.feature = {
evt: {}
};
// mock up features
var features = new Array(4);
for(var i=0; i<features.length; ++i) {
features[i] = {
id: Math.random(),
tested: 0,
style: "",
layer: layer
};
}
// test that onSelect gets called properly
control.onSelect = function(feature) {
feature.tested += 1;
t.eq(feature.id, features[feature.index].id,
"onSelect called with proper feature (" + feature.index + ")");
t.eq(feature.tested, feature.test,
"onSelect called only once for feature (" + feature.index + ")");
t.ok(this == control, "onSelect called in the scope of the control if control.scope is not provided");
}
// test that onUnselect gets called properly
control.onUnselect = function(feature) {
feature.tested += 1;
t.eq(feature.id, features[feature.index].id,
"onUnselect called with proper feature (" + feature.index + ")");
t.eq(feature.tested, feature.test,
"onUnselect called only once for feature (" + feature.index + ")");
t.ok(this == control, "onUnselect called in the scope of the control if control.scope is not provided");
}
// mock up first click on first feature (runs 3 tests from onSelect)
var feature = features[0];
feature.index = 0;
feature.test = 1;
control.clickFeature(feature);
// mock up second click on first feature (runs no tests - already selected)
control.toggle = false;
control.clickFeature(feature);
// mock up second click on first feature (runs 3 tests from onUnselect)
control.toggle = true;
feature.test = 2;
control.clickFeature(feature);
}
function test_box(t) {
t.plan(5);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
map.setBaseLayer(layer);
map.setCenter(new OpenLayers.LonLat(1,1));
var control = new OpenLayers.Control.SelectFeature(layer, {'multiple': true, box: true });
var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
var feature2 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,1));
var feature3 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(-2,-2));
var feature4 = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(0, 0), new OpenLayers.Geometry.Point(1, 1)
]));
layer.addFeatures([feature, feature2, feature3, feature4]);
control.setMap(map);
map.getLonLatFromPixel = function(arg) {
return new OpenLayers.LonLat(arg.x, arg.y);
}
control.selectBox(new OpenLayers.Bounds(-1, -1, 2, 2));
t.eq(layer.selectedFeatures.length, 3, "box around all features selects 3 features");
control.selectBox(new OpenLayers.Bounds(-3, -3, -1, -1));
t.eq(layer.selectedFeatures.length, 4, "box around other features doesn't turn off already selected features.");
control.multipleSelect = function() {
return false;
};
control.selectBox(new OpenLayers.Bounds(-3, -3, -1, -1));
t.eq(layer.selectedFeatures.length, 1, "box around other features correctly turns off already selected features.");
control.geometryTypes = null;
control.selectBox(new OpenLayers.Bounds(-100, -100, 100, 100));
t.eq(layer.selectedFeatures.length, layer.features.length, "all features selected with no geometryTypes filter");
control.geometryTypes = ["OpenLayers.Geometry.Point"];
control.selectBox(new OpenLayers.Bounds(-100, -100, 100, 100));
t.eq(layer.selectedFeatures.length, 3, "3 features selected with geometryTypes filter");
}
function test_Control_SelectFeature_activate(t) {
t.plan(4);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.SelectFeature(layer, {box: true});
map.addControl(control);
t.ok(!control.handlers.feature.active,
"feature handler is not active prior to activating control");
t.ok(!control.handlers.box.active,
"box handler is not active prior to activating control");
control.activate();
t.ok(control.handlers.feature.active,
"feature handler is active after activating control");
t.ok(control.handlers.box.active,
"box handler is active after activating control");
}
function test_Control_SelectFeature_deactivate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
var control = new OpenLayers.Control.SelectFeature(layer, {box: true});
map.addControl(control);
control.activate();
control.handlers.feature.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on feature handler");
OpenLayers.Handler.Feature.prototype.deactivate.apply(this, arguments);
}
control.handlers.box.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on box handler");
}
control.deactivate();
}
function test_highlighyOnly(t) {
t.plan(23);
/*
* setup
*/
var map, layer, ctrl1, ctrl2, _feature, feature, evt, _style;
map = new OpenLayers.Map("map");
layer = new OpenLayers.Layer.Vector("name", {isBaseLayer: true});
map.addLayer(layer);
ctrl1 = new OpenLayers.Control.SelectFeature(layer, {
highlightOnly: false,
hover: false
});
map.addControl(ctrl1);
ctrl2 = new OpenLayers.Control.SelectFeature(layer, {
highlightOnly: true,
hover: true
});
map.addControl(ctrl2);
ctrl2.activate();
ctrl1.activate();
feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
// override the layer's getFeatureFromEvent func so that it always
// returns the feature referenced to by _feature
layer.getFeatureFromEvent = function(evt) { return _feature; };
evt = {xy: new OpenLayers.Pixel(Math.random(), Math.random())};
map.zoomToMaxExtent();
/*
* tests
*/
// with renderIntent
ctrl1.renderIntent = "select";
ctrl2.renderIntent = "temporary";
// mouse over feature, feature is drawn with "temporary"
_feature = feature;
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
t.eq(feature.renderIntent, "temporary",
"feature drawn with expected render intent after \"mouseover\"");
t.eq(feature._lastHighlighter, ctrl2.id,
"feature._lastHighlighter properly set after \"mouseover\"");
t.eq(feature._prevHighlighter, undefined,
"feature._prevHighlighter properly set after \"mouseover\"");
// click in feature, feature is drawn with "select"
_feature = feature;
evt.type = "click";
map.events.triggerEvent("click", evt);
t.eq(feature.renderIntent, "select",
"feature drawn with expected render intent after \"clickin\"");
t.eq(feature._lastHighlighter, ctrl1.id,
"feature._lastHighlighter properly set after \"clickin\"");
t.eq(feature._prevHighlighter, ctrl2.id,
"feature._prevHighlighter properly set after \"clickin\"");
// mouse out of feature, feature is still drawn with "select"
_feature = null;
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
t.eq(feature.renderIntent, "select",
"feature drawn with expected render intent after \"mouseout\"");
t.eq(feature._lastHighlighter, ctrl1.id,
"feature._lastHighlighter properly set after \"nouseout\"");
t.ok(feature._prevHighlighter, ctrl2.id,
"feature._prevHighlighter properly set after \"mouseout\"");
// mouse over feature again, feature is drawn with "temporary"
_feature = feature;
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
t.eq(feature.renderIntent, "temporary",
"feature drawn with expected render intent after \"mouseover\"");
t.eq(feature._lastHighlighter, ctrl2.id,
"feature._lastHighlighter properly set after \"mouseover\"");
t.eq(feature._prevHighlighter, ctrl1.id,
"feature._prevHighlighter properly set after \"mouseover\"");
// mouve out of feature again, feature is still drawn with "select"
_feature = null;
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
t.eq(feature.renderIntent, "select",
"feature drawn with expected render intent after \"mouseout\"");
t.eq(feature._lastHighlighter, ctrl1.id,
"feature._lastHighlighter properly set after \"mouseout\"");
t.eq(feature._prevHighlighter, undefined,
"feature._prevHighlighter properly set after \"mouseout\"");
// click out of feature, feature is drawn with "default"
_feature = null;
evt.type = "click";
map.events.triggerEvent("click", evt);
t.eq(feature.renderIntent, "default",
"feature drawn with expected render intent after \"clickout\"");
t.eq(feature._lastHighlighter, undefined,
"feature._lastHighlighter properly set after \"clickout\"");
t.eq(feature._prevHighlighter, undefined,
"feature._prevHighlighter properly set after \"clickout\"");
// with selectStyle
ctrl1.selectStyle = OpenLayers.Feature.Vector.style["select"];
ctrl2.selectStyle = OpenLayers.Feature.Vector.style["temporary"];
layer.renderer.drawFeature = function(f, s) {
var style = OpenLayers.Feature.Vector.style[_style];
t.eq(s, style, "renderer drawFeature called with expected style obj (" + _style + ")");
};
// mouse over feature, feature is drawn with "temporary"
_feature = feature;
_style = "temporary";
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
// click in feature, feature is drawn with "select"
_feature = feature;
_style = "select";
evt.type = "click";
map.events.triggerEvent("click", evt);
// mouse out of feature, feature is still drawn with "select" and
// the renderer drawFeature method should not be called
_feature = null;
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
// mouse over feature again, feature is drawn with "temporary"
_feature = feature;
_style = "temporary";
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
// mouve out of feature again, feature is still drawn with "select"
_feature = null;
_style = "select";
evt.type = "mousemove";
map.events.triggerEvent("mousemove", evt);
// click out of feature, feature is drawn with "default"
_feature = null;
_style = "default";
evt.type = "click";
map.events.triggerEvent("click", evt);
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,334 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(5);
// construct with a single layer
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping({
layer: layer
});
t.ok(control.layer === layer, "[a] source layer properly set");
t.eq(control.targets.length, 1, "[a] one target layer");
t.ok(control.targets[0].layer === layer, "[a] target set");
control.destroy();
// construct with a different target, default target config
var layer2 = new OpenLayers.Layer.Vector();
control = new OpenLayers.Control.Snapping({
layer: layer,
targets: [layer2]
});
t.eq(control.targets.length, 1, "[b] one target layer");
t.ok(control.targets[0].layer == layer2, "[b] target set");
control.destroy();
}
function test_setLayer(t) {
t.plan(4);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping();
control.setLayer(layer);
t.ok(control.layer === layer, "layer properly set");
// confirm that the control is deactivated and reactivated when setting new layer
var log = {
activated: 0,
deactivated: 0
};
control.activate = function() {
log.activated++;
}
control.deactivate = function() {
log.deactivated++;
}
control.active = true;
var layer2 = new OpenLayers.Layer.Vector();
control.setLayer(layer2);
t.eq(log.deactivated, 1, "control deactivated");
t.ok(control.layer === layer2, "layer properly reset");
t.eq(log.activated, 1, "control reactivated");
control.destroy();
}
function test_setTargets(t) {
t.plan(4);
var layer1 = new OpenLayers.Layer.Vector();
var layer2 = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping();
var log = {
addTarget: [],
addTargetLayer: []
};
control.addTarget = function(target) {
log.addTarget.push(target);
};
control.addTargetLayer = function(target) {
log.addTargetLayer.push(target);
};
control.setTargets([layer1, {layer: layer2}]);
t.eq(log.addTargetLayer.length, 1, "setTargetLayer called once");
t.ok(log.addTargetLayer[0] === layer1, "setTargetLayer called with layer1");
t.eq(log.addTarget.length, 1, "setTarget called once");
t.ok(log.addTarget[0].layer === layer2, "setTarget called with layer2");
control.destroy();
}
function test_addTarget(t) {
t.plan(5);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping({
defaults: {
nodeTolerance: 30,
tolerance: 40
}
});
var log = {};
control.addTarget({layer: layer});
t.eq(control.targets.length, 1, "single target");
var target = control.targets[0];
t.ok(target.layer === layer, "correct target layer");
t.eq(target.nodeTolerance, 30, "correct nodeTolerance");
t.eq(target.edgeTolerance, 40, "correct edgeTolerance");
t.eq(target.vertexTolerance, 40, "correct vertexTolerance");
control.destroy();
}
function test_removeTargetLayer(t) {
t.plan(3);
var layer1 = new OpenLayers.Layer.Vector();
var layer2 = new OpenLayers.Layer.Vector();
var layer3 = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping({
targets: [layer1, layer2, layer3]
});
control.removeTargetLayer(layer2);
t.eq(control.targets.length, 2, "correct targets length");
t.ok(control.targets[0].layer === layer1, "layer1 remains");
t.ok(control.targets[1].layer === layer3, "layer3 remains");
control.destroy();
}
function test_activate(t) {
t.plan(4);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping({
layer: layer
});
control.activate();
t.eq(layer.events.listeners.sketchmodified.length, 1, "one sketchmodified listener");
t.ok(layer.events.listeners.sketchmodified[0].func === control.onSketchModified, "correct sketchmodified listener");
t.eq(layer.events.listeners.vertexmodified.length, 1, "one vertexmodified listener");
t.ok(layer.events.listeners.vertexmodified[0].func === control.onVertexModified, "correct vertexmodified listener");
control.destroy();
}
function test_deactivate(t) {
t.plan(2);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Snapping({
layer: layer
});
control.activate();
control.deactivate();
t.eq(layer.events.listeners.sketchmodified.length, 0, "no sketchmodified listeners");
t.eq(layer.events.listeners.vertexmodified.length, 0, "no vertexmodified listeners");
control.destroy();
}
function test_snapping(t) {
t.plan(46);
var map = new OpenLayers.Map("map", {
resolutions: [1],
maxExtent: new OpenLayers.Bounds(0, 0, 100, 100)
});
var layer1 = new OpenLayers.Layer.Vector(null, {
isBaseLayer: true
});
layer1.addFeatures([
new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT(
"LINESTRING(0 0, 10 10, 20 20, 30 30)"
)),
new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT(
"LINESTRING(11 10, 20 10, 30 10)"
))
]);
var layer2 = new OpenLayers.Layer.Vector();
layer2.addFeatures([
new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT(
"LINESTRING(10 10, 20 20, 30 30)"
)),
new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT(
"LINESTRING(21 10, 20 20, 20 30)"
))
]);
map.addLayers([layer1, layer2]);
map.zoomToMaxExtent();
var control = new OpenLayers.Control.Snapping({
layer: layer1,
targets: [layer1, layer2],
defaults: {tolerance: 4}
});
control.activate();
map.addControl(control);
// log beforesnap, snap, and unsnap events
var events = [];
function listener(event) {
events.push(event);
}
control.events.on({
beforesnap: listener,
snap: listener,
unsnap: listener
});
// create a vertex and a convenience method for mocking the drag
var vertex = new OpenLayers.Geometry.Point(-100, -100);
function drag(x, y) {
var px = map.getPixelFromLonLat(new OpenLayers.LonLat(x, y));
layer1.events.triggerEvent("vertexmodified", {
vertex: vertex, pixel: px
});
}
// mock up drag far from features
drag(-100, -100);
t.eq(events.length, 0, "no snapping");
// mock up drag near first node of first feature
drag(0, 1);
t.eq(events.length, 2, "[a] 2 events triggered");
t.eq(events[0].type, "beforesnap", "[a] beforesnap triggered");
t.eq(events[0].snapType, "node", "[a] beforesnap triggered for node");
t.ok(events[0].point === vertex, "[a] beforesnap triggered with vertex");
t.eq(events[0].x, 0, "[a] beforesnap triggered correct x");
t.eq(events[0].y, 0, "[a] beforesnap triggered with correct y");
t.eq(events[1].type, "snap", "[a] snap triggered");
t.eq(events[1].snapType, "node", "[a] snap triggered for node");
t.ok(events[1].point === vertex, "[a] snap triggered with point");
t.eq(events[1].distance, 1, "[a] snap triggered correct distance");
t.ok(events[1].layer === layer1, "[a] snap triggered with correct target layer");
t.eq(vertex.x, 0, "[a] vertex x modified");
t.eq(vertex.y, 0, "[a] vertex y modified");
events = [];
// mock up drag that unsnaps
drag(-100, -50);
t.eq(events.length, 1, "[b] 1 event triggered");
t.eq(events[0].type, "unsnap", "[b] unsnap triggered");
t.ok(events[0].point === vertex, "[b] unsnap triggered with vertex");
t.eq(vertex.x, -100, "[b] vertex x unsnapped");
t.eq(vertex.y, -50, "[b] vertex y unsnapped");
events = [];
// drag near node of second feature in first layer to demonstrate precedence of node snapping
drag(9, 10);
t.eq(events.length, 2, "[c] 2 events triggered");
t.eq(events[0].type, "beforesnap", "[c] beforesnap triggered first");
t.eq(events[1].type, "snap", "[c] snap triggered second");
t.eq(events[1].snapType, "node", "[c] snap to node");
// unsnap & reset
drag(-100, -50);
events = [];
// drag near node of second feature in second layer to demonstrate greedy property
// with greedy true (default) the best target from the first layer with eligible targets is used
drag(22, 10);
t.eq(events.length, 2, "[d] 2 events triggered");
t.eq(events[1].type, "snap", "[d] snap triggered second");
t.eq(events[1].snapType, "vertex", "[d] snap to vertex");
t.ok(events[1].layer === layer1, "[d] snap to vertex in first layer");
t.eq(vertex.x, 20, "[d] vertex x modified");
t.eq(vertex.y, 10, "[d] vertex y modified");
// unsnap & reset
drag(-100, -50);
events = [];
// do the same drag but with greedy false - this will look for best target in all layers
control.greedy = false;
drag(22, 10);
t.eq(events.length, 2, "[d] 2 events triggered");
t.eq(events[1].type, "snap", "[d] snap triggered second");
t.eq(events[1].snapType, "node", "[d] snap to node");
t.ok(events[1].layer === layer2, "[d] snap to node in second layer");
// unsnap & reset
drag(-100, -50);
control.greedy = true;
events = [];
// demonstrate snapping on sketchstarted
var p = new OpenLayers.Geometry.Point(0, 1);
layer1.events.triggerEvent("sketchstarted", {
vertex: p,
feature: new OpenLayers.Feature.Vector(p)
});
t.eq(events.length, 2, "[sketchstarted] 2 events triggered");
t.eq(events[0].type, "beforesnap", "[sketchstarted] beforesnap triggered");
t.eq(events[0].snapType, "node", "[sketchstarted] beforesnap triggered for node");
t.ok(events[0].point === p, "[sketchstarted] beforesnap triggered with vertex");
t.eq(events[0].x, 0, "[sketchstarted] beforesnap triggered correct x");
t.eq(events[0].y, 0, "[sketchstarted] beforesnap triggered with correct y");
t.eq(events[1].type, "snap", "[sketchstarted] snap triggered");
t.eq(events[1].snapType, "node", "[sketchstarted] snap triggered for node");
t.ok(events[1].point === p, "[sketchstarted] snap triggered with point");
t.eq(events[1].distance, 1, "[sketchstarted] snap triggered correct distance");
t.ok(events[1].layer === layer1, "[sketchstarted] snap triggered with correct target layer");
t.eq(p.x, 0, "[sketchstarted] vertex x modified");
t.eq(p.y, 0, "[sketchstarted] vertex y modified");
// reset
events = [];
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 100px; height: 100px;"></div>
</body>
</html>

View File

@ -1,296 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(4);
var layer = new OpenLayers.Layer.Vector();
var control;
// construct with nothing
control = new OpenLayers.Control.Split();
t.ok(control instanceof OpenLayers.Control, "instanceof OpenLayers.Control");
t.ok(control instanceof OpenLayers.Control, "instanceof OpenLayers.Control.Split")
control.destroy();
// construct with a single target layer
control = new OpenLayers.Control.Split({
layer: layer
});
t.ok(control.layer === layer, "target layer properly set");
control.destroy();
// construct with same target and source
control = new OpenLayers.Control.Split({
layer: layer,
source: layer
});
t.ok(control.source === layer, "source layer properly set");
control.destroy();
}
function test_setSource(t) {
t.plan(5);
var layer1 = new OpenLayers.Layer.Vector();
var layer2 = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Split({layer: layer1});
var map = new OpenLayers.Map("map");
map.addLayers([layer1, layer2]);
map.addControl(control);
control.activate();
// confirm sketch hander created
t.ok(control.handler, "sketch handler created");
t.eq(control.handler.active, true, "sketch handler active");
control.setSource(layer1);
t.ok(control.source === layer1, "layer1 properly set");
t.ok(!control.handler, "no more sketch handler");
// activate and switch to new source layer
control.setSource(layer2);
t.ok(control.source === layer2, "layer2 properly set");
map.destroy();
}
function test_activate(t) {
t.plan(8);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Split({layer: layer});
var map = new OpenLayers.Map("map");
map.addLayer(layer);
map.addControl(control);
// test activation with no source layer
control.activate();
t.eq(control.active, true, "control is active");
t.ok(control.handler instanceof OpenLayers.Handler.Path, "line sketch handler created");
t.ok(control.handler.callbacks.done, "done callback set on sketch handler");
t.eq(control.handler.active, true, "sketch handler is active");
// change the source layer - this should call activate again
control.setSource(layer);
t.eq(control.active, true, "control is still active");
t.ok(control.source === layer, "source layer set");
t.ok(layer.events.listeners.sketchcomplete, "sketchcomplete listener registered");
t.ok(layer.events.listeners.afterfeaturemodified, "afterfeaturemodified listener registered");
map.destroy();
}
function test_deactivate(t) {
t.plan(7);
var layer = new OpenLayers.Layer.Vector();
var control = new OpenLayers.Control.Split({layer: layer});
var map = new OpenLayers.Map("map");
map.addLayer(layer);
map.addControl(control);
// activate and check sketch handler
control.activate();
t.ok(control.handler, "sketch handler present");
t.eq(control.handler.active, true, "sketch handler active");
// deactivate and check sketch handler
control.deactivate();
t.eq(control.handler.active, false, "sketch handler deactivated");
// set a source layer
control.setSource(layer);
// activate and check that listeners are registered
control.activate();
t.ok(layer.events.listeners.sketchcomplete, "sketchcomplete listener registered");
t.ok(layer.events.listeners.afterfeaturemodified, "afterfeaturemodified listener registered");
// deactivate and confirm no draw related events
control.deactivate();
t.eq(layer.events.listeners.sketchcomplete.length, 0, "no sketchcomplete listeners");
t.eq(layer.events.listeners.afterfeaturemodified.length, 0, "no afterfeaturemodified listeners");
map.destroy();
}
function test_isEligible(t) {
t.plan(9);
var control = new OpenLayers.Control.Split();
var geometry = OpenLayers.Geometry.fromWKT("LINESTRING(0 1, 1 2)");
var feature = new OpenLayers.Feature.Vector(
geometry,
{foo: "bar"}
);
t.eq(control.isEligible(feature), true, "plain old feature is eligible");
feature.state = OpenLayers.State.DELETE;
t.eq(control.isEligible(feature), false, "feature slated for deletion is not eligible");
delete feature.state;
t.eq(control.isEligible(feature), true, "feature with no state is eligible");
feature.geometry = new OpenLayers.Geometry.Point(1, 1);
t.eq(control.isEligible(feature), false, "feature with point geometry is not eligible");
feature.geometry = new OpenLayers.Geometry.MultiLineString([geometry]);
t.eq(control.isEligible(feature), true, "feature with multilinestring geometry is eligible");
control.feature = feature;
t.eq(control.isEligible(feature), false, "source feature is not eligible as target");
control.feature = new OpenLayers.Feature.Vector();
t.eq(control.isEligible(feature), true, "feature is eligible if different than source feature");
control.targetFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
property: "foo",
value: "bar"
});
t.eq(control.isEligible(feature), false, "feature is not eligible unless it matches filter");
control.targetFilter.value = "baz";
t.eq(control.isEligible(feature), true, "feature is eligible if it matches filter");
control.destroy();
}
function test_considerSplit(t) {
var layer = new OpenLayers.Layer.Vector();
var wkt = OpenLayers.Geometry.fromWKT;
var geoms = {
abc: wkt("LINESTRING(0 0, 2 2)"),
ab: wkt("LINESTRING(0 0, 1 1)"),
bc: wkt("LINESTRING(1 1, 2 2)"),
dbe: wkt("LINESTRING(2 0, 0 2)"),
db: wkt("LINESTRING(2 0, 1 1)"),
be: wkt("LINESTRING(1 1, 0 2)")
};
var Feature = OpenLayers.Feature.Vector;
var feats = {
abc: new Feature(geoms.abc),
ab: new Feature(geoms.ab),
bc: new Feature(geoms.bc),
dbe: new Feature(geoms.dbe),
db: new Feature(geoms.db),
be: new Feature(geoms.be)
};
function feature(id, options) {
var f = OpenLayers.Util.extend(feats[id].clone(), options);
// for testing, we want to check when features are destroyed
f.destroy = function() {
f.state = "destroyed";
}
return f;
}
var DELETE = OpenLayers.State.DELETE;
var INSERT = OpenLayers.State.INSERT;
var UPDATE = OpenLayers.State.UPDATE;
var cases = [{
targets: [
feature("abc")
],
source: feature("dbe"),
splits: [{
original: feature("abc", {state: "destroyed"}),
features: [feature("ab", {state: INSERT}), feature("bc", {state: INSERT})]
}, {
original: feature("dbe", {state: "destroyed"}),
features: [feature("db", {state: INSERT}), feature("be", {state: INSERT})]
}]
}, {
options: {deferDelete: true},
targets: [
feature("abc", {state: INSERT})
],
source: feature("dbe"),
splits: [{
original: feature("abc", {state: "destroyed"}),
features: [feature("ab", {state: INSERT}), feature("bc", {state: INSERT})]
}, {
original: feature("dbe", {state: DELETE}),
features: [feature("db", {state: INSERT}), feature("be", {state: INSERT})]
}]
}, {
options: {deferDelete: true},
targets: [
feature("abc", {state: UPDATE})
],
source: feature("dbe", {state: INSERT}),
splits: [{
original: feature("abc", {state: DELETE}),
features: [feature("ab", {state: INSERT}), feature("bc", {state: INSERT})]
}, {
original: feature("dbe", {state: "destroyed"}),
features: [feature("db", {state: INSERT}), feature("be", {state: INSERT})]
}]
}];
var count = 0;
var c, control, options, log, event, split;
for(var i=0; i<cases.length; ++i) {
c = cases[i];
++count; // test number of splits
for(var j=0; j<c.splits.length; ++j) {
split = c.splits[j];
++count; // test original state
++count; // test original geometry
++count; // test number of parts
for(var k=0; k<split.features.length; ++k) {
++count; // test part state
++count; // test part geometry
}
}
}
t.plan(count);
for(var i=0; i<cases.length; ++i) {
c = cases[i];
log = {events: []};
options = OpenLayers.Util.extend({layer: layer, source: layer}, c.options);
control = new OpenLayers.Control.Split(options);
control.events.on({
split: function(e) {
log.events.push(e);
}
});
layer.features = c.targets;
control.considerSplit(c.source);
t.eq(log.events.length, c.splits.length, "case " + i + ": correct number of split events");
for(var j=0; j<log.events.length; ++j) {
event = log.events[j];
split = c.splits[j];
t.eq(event.original.state, split.original.state, "case " + i + " split " + j + ": correct original state");
t.geom_eq(event.original.geometry, split.original.geometry, "case " + i + " split " + j + ": correct original geometry");
t.eq(event.features.length, split.features.length, "case " + i + " split " + j + ": correct number of parts");
for(var k=0; k<split.features.length; ++k) {
t.eq(event.features[k].state, split.features[k].state, "case " + i + " split " + j + " feature " + k + ": correct state");
t.geom_eq(event.features[k].geometry, split.features[k].geometry, "case " + i + " split " + j + " feature " + k + ": correct geometry");
}
}
control.destroy();
}
}
</script>
</head>
<body>
<div id="map" style="width: 100px; height: 100px;"></div>
</body>
</html>

View File

@ -1,278 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(5);
var options = {
url: 'http://localhost/wms',
layers: ["foo"],
formatOptions: {
foo: "bar"
}
};
var control = new OpenLayers.Control.WMSGetFeatureInfo(options);
t.ok(control instanceof OpenLayers.Control.WMSGetFeatureInfo,
"new OpenLayers.Control.WMSGetFeatureInfo returns an instance");
t.eq(control.url, 'http://localhost/wms',
"constructor sets url correctly");
t.eq(control.layers, ["foo"],
"constructor layers"
);
t.ok(control.format instanceof OpenLayers.Format.WMSGetFeatureInfo, "format created");
t.eq(control.format.foo, "bar", "format options used")
}
function test_destroy(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var click = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
layers: ["foo"]
});
var hover = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
layers: ["foo"],
hover: true
});
click.handler.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on click handler");
}
hover.handler.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on hover handler");
}
click.destroy();
hover.destroy();
}
function test_click(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
// mock up active control
var control = new OpenLayers.Control.WMSGetFeatureInfo();
map.addControl(control);
control.activate();
control.request = function(position) {
t.eq(position.x, 50,
"x position is as expected");
t.eq(position.y, 50,
"y position is as expected");
}
control.getInfoForClick({xy: {x: 50, y: 50}});
control.getInfoForHover({xy: {x: 50, y: 50}});
}
function test_activate(t) {
t.plan(4);
var map = new OpenLayers.Map("map");
var click = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
featureType: 'type',
featureNS: 'http://localhost/ns',
layers: 'ns:type'
});
var hover = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
featureType: 'type',
featureNS: 'http://localhost/ns',
layers: 'ns:type',
hover: true
});
map.addControl(click);
map.addControl(hover);
t.ok(!click.handler.active,
"click handler is not active prior to activating control");
t.ok(!hover.handler.active,
"hover handler is not active prior to activating control");
click.activate();
hover.activate();
t.ok(click.handler.active,
"click handler is active after activating control");
t.ok(hover.handler.active,
"hover handler is active after activating control");
}
function test_deactivate(t) {
t.plan(2);
var map = new OpenLayers.Map("map");
var click = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
featureType: 'type',
featureNS: 'http://localhost/ns',
layers: 'ns:type'
});
var hover = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost/wms',
featureType: 'type',
featureNS: 'http://localhost/ns',
layers: 'ns:type'
});
map.addControl(click);
map.addControl(hover);
click.activate();
hover.activate();
click.handler.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on click handler");
OpenLayers.Handler.Click.prototype.deactivate.apply(this, arguments);
}
hover.handler.deactivate = function() {
t.ok(true,
"control.deactivate calls deactivate on hover handler");
OpenLayers.Handler.Hover.prototype.deactivate.apply(this, arguments);
}
click.deactivate();
hover.deactivate();
}
// Verify that things work all right when we combine different types for the STYLES and LAYERS
// params in the WMS Layers involved
function test_mixedParams(t) {
t.plan(2);
var map = new OpenLayers.Map("map", {
getExtent: function() {return(new OpenLayers.Bounds(-180,-90,180,90));}
}
);
var a = new OpenLayers.Layer.WMS("dummy","http://localhost/wms", {
layers: "a,b,c,d",
styles: "a,b,c,d"
});
var b = new OpenLayers.Layer.WMS("dummy","http://localhost/wms", {
layers: ["a","b","c","d"],
styles: ["a","b","c","d"]
});
var c = new OpenLayers.Layer.WMS("dummy","http://localhost/wms", {
layers: ["a","b","c","d"]
});
var d = new OpenLayers.Layer.WMS("dummy","http://localhost/wms", {
layers: "a,b,c,d"
});
var click = new OpenLayers.Control.WMSGetFeatureInfo({
featureType: 'type',
featureNS: 'ns',
layers: [a, b, c, d]
});
map.addControl(click);
var log = {};
var _request = OpenLayers.Request.GET;
OpenLayers.Request.GET = function(options) {
log.options = options;
};
click.activate();
click.getInfoForClick({xy: {x: 50, y: 50}});
OpenLayers.Request.GET = _request;
t.eq(
log.options && log.options.url,
"http://localhost/wms",
"url from first layer used"
);
t.eq(
log.options && log.options.params.styles.join(","),
"a,b,c,d,a,b,c,d,,,,,,,,",
"Styles merged correctly"
);
}
function test_urlMatches(t) {
t.plan(5);
var control = new OpenLayers.Control.WMSGetFeatureInfo({
url: "http://host/wms?one=1&two=2"
});
t.ok(!control.urlMatches("foo"), "doesn't match garbage");
t.ok(control.urlMatches("http://host:80/wms?two=2&one=1"), "matches equivalent url");
// give the control more urls to match from
control.layerUrls = ["http://a.host/wms", "http://b.host/wms"];
t.ok(control.urlMatches("http://host:80/wms?two=2&one=1"), "still matches equivalent url");
t.ok(control.urlMatches("http://a.host:80/wms"), "matches equivalent of first of layerUrls");
t.ok(control.urlMatches("http://b.host:80/wms"), "matches equivalent of second of layerUrls");
}
function test_layerUrls(t) {
t.plan(4);
var map = new OpenLayers.Map({
div: "map",
getExtent: function() {
return new OpenLayers.Bounds(-180,-90,180,90);
}
});
var a = new OpenLayers.Layer.WMS(
null, "http://a.mirror/wms", {layers: "a"}
);
var b = new OpenLayers.Layer.WMS(
null, "http://b.mirror/wms", {layers: "b"}
);
var c = new OpenLayers.Layer.WMS(
null, ["http://c.mirror/wms", "http://d.mirror/wms"], {layers: "c"}
);
var control = new OpenLayers.Control.WMSGetFeatureInfo({
url: "http://host/wms",
layers: [a, b, c]
});
map.addControl(control);
control.activate();
// log calls to GET
var log;
var _request = OpenLayers.Request.GET;
OpenLayers.Request.GET = function(options) {
log.options = options;
};
// control url doesn't match layer urls, no request issued
log = {};
control.getInfoForClick({xy: {x: 50, y: 50}});
t.ok(!log.options, "no url match, no request issued");
// give control a list of urls to match
log = {};
control.layerUrls = ["http://a.mirror/wms", "http://b.mirror/wms"];
control.getInfoForClick({xy: {x: 50, y: 50}});
t.eq(log.options && log.options.url, "http://host/wms", "some match, request issued");
t.eq(log.options && log.options.params["query_layers"].join(","), "a,b", "selected layers queried");
// show that a layer can be matched if it has a urls array itself (first needs to be matched)
log = {};
control.layerUrls = ["http://c.mirror/wms"];
control.getInfoForClick({xy: {x: 50, y: 50}});
t.eq(log.options && log.options.params["query_layers"].join(","), "c", "layer with urls array can be queried");
// clean up
OpenLayers.Request.GET = _request;
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 400px; height: 250px;"/>
</body>
</html>

View File

@ -1,457 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var isMozilla = (navigator.userAgent.indexOf("compatible") == -1);
var map;
var a;
function test_Events_constructor (t) {
var mapDiv = OpenLayers.Util.getElement('map');
var obj = {result: 0};
var eventTypes = ["doThingA", "doThingB", "doThingC"];
var browserTypes = OpenLayers.Events.prototype.BROWSER_EVENTS;
var totalTests = 4 + 2*eventTypes.length + 2*browserTypes.length;
t.plan( totalTests );
events = new OpenLayers.Events(obj, mapDiv, eventTypes);
t.ok( events instanceof OpenLayers.Events, "new OpenLayers.Control returns object" );
t.ok(events.object ==obj, " 'object' property correctly set");
t.ok(events.element == mapDiv, " 'element' property correctly set");
for (var i = 0; i < browserTypes.length; i++) {
var type = browserTypes[i];
t.ok( events.listeners[type] instanceof Array, "browser event: " + type + " correctly registered" );
t.ok( OpenLayers.Util.indexOf(events.eventTypes, type) != -1, "browser type " + type + "' correctly added to eventTypes array");
}
for (var i = 0; i < eventTypes.length; i++) {
var type = eventTypes[i];
t.ok( events.listeners[type] instanceof Array, "custom event: " + type + " correctly registered");
t.ok( OpenLayers.Util.indexOf(events.eventTypes, type) != -1, "eventType " + type + "' correctly added to eventTypes array");
}
// default/nulls
events = new OpenLayers.Events(null, null, null);
t.ok( events.listeners != null,
"init of Events with null object/element/eventTypes still creates listeners array" );
}
function test_Events_register(t){
t.plan(4);
var ev = {
'object': {},
'listeners': {
'listenerA': {
'push': function(options){
gObjA = options.obj;
gFuncA = options.func;
}
},
'listenerB': {
'push': function(options){
gObjB = options.obj;
gFuncB = options.func;
}
}
},
'eventTypes': ['listenerA', 'listenerB']
};
var type = null;
var object = null;
var func = null;
//func null
gObjA = null; gFuncA = null; gObjB = null; gFuncB = null;
OpenLayers.Events.prototype.register.apply(ev, [type, object, func]);
t.ok((gObjA == null) && (gFuncA == null) &&
(gObjB == null) && (gFuncB == null), "no push called func null");
//valid func, type not in ev.eventTypes
func = function() {};
gObjA = null; gFuncA = null; gObjB = null; gFuncB = null;
OpenLayers.Events.prototype.register.apply(ev, [type, object, func]);
t.ok((gObjA == null) && (gFuncA == null) &&
(gObjB == null) && (gFuncB == null), "no push called func null");
//valid func, type in ev.eventTypes, null obj
type = 'listenerA';
gObjA = null; gFuncA = null; gObjB = null; gFuncB = null;
OpenLayers.Events.prototype.register.apply(ev, [type, object, func]);
t.ok((gObjA == ev.object) && (gFuncA == func) &&
(gObjB == null) && (gFuncB == null), "push called on listenerA's mock array when type passed in 'listenerA'. events.object taken since obj is null.");
//valid func, type in ev.eventTypes, valid obj
type = 'listenerB';
object = {};
gObjA = null; gFuncA = null; gObjB = null; gFuncB = null;
OpenLayers.Events.prototype.register.apply(ev, [type, object, func]);
t.ok((gObjA == null) && (gFuncA == null) &&
(gObjB == object) && (gFuncB == func), "push called on listenerB's mock array when type passed in 'listenerB'.");
}
function test_Events_register_unregister(t) {
t.plan( 18 );
var mapDiv = OpenLayers.Util.getElement('map');
var obj = {result: 0};
var eventTypes = ["doThingA", "doThingB", "doThingC"];
events = new OpenLayers.Events(obj, mapDiv, eventTypes);
var func = function () { this.result++ }
events.register( "doThingA", obj, func );
var listenerList = events.listeners["doThingA"];
t.eq( listenerList.length, 1, "register correctly adds to event.listeners" );
t.ok( listenerList[0].obj == obj, "obj property correctly registered");
t.ok( listenerList[0].func == func, "func property correctly registered");
var func2 = function () { this.result-- }
events.register( "doThingA", obj, func2 );
var listenerList = events.listeners["doThingA"];
t.eq( listenerList.length, 2, "register correctly appends new callback to event.listeners[doThingA]" );
t.ok( listenerList[1].obj == obj, "obj property correctly registered");
t.ok( listenerList[1].func == func2, "func property correctly registered");
var func3 = function () { this.result = this.result + 3; }
events.register( "doThingA", null, func3 );
var listenerList = events.listeners["doThingA"];
t.eq( listenerList.length, 3, "register correctly appends new callback to event.listeners[doThingA] even when obj passed in is null" );
t.ok( listenerList[2].obj == obj, "obj is correctly set to Events.object default when null is passed in.");
t.ok( listenerList[2].func == func3, "func property correctly registered");
events.register( "doThingA", obj, null);
var listenerList = events.listeners["doThingA"];
t.eq( listenerList.length, 3, "register correctly does not append null callback to event.listeners[doThingA] even when obj passed in is null" );
events.register( "chicken", obj, func);
t.ok( events.listeners["chicken"] == null, "register() does nothing on attempt to register un-enabled event");
events.unregister("doThingA", obj, null);
var listenerList = events.listeners["doThingA"];
t.eq( listenerList.length, 3, "trying to unregister a null callback does nothing -- but doesnt crash :-)" );
events.unregister("doThingA", obj, func);
var found = false;
for (var i = 0; i < listenerList.length; i++) {
var listener = listenerList[i];
if (listener.obj == obj && listener.func == func) {
found = true;
}
}
t.ok( (listenerList.length == 2) && !found, "unregister correctly removes callback" );
events.unregister("doThingA", null, func3);
var found = false;
for (var i = 0; i < listenerList.length; i++) {
var listener = listenerList[i];
if (listener.obj == obj && listener.func == func) {
found = true;
}
}
t.ok( (listenerList.length == 1) && !found, "unregister correctly removes callback when no obj specified" );
var func4 = function () { this.result = "chicken"; }
events.unregister("doThingA", obj, func4);
t.ok( (listenerList.length == 1), "unregister does not bomb if you try to remove an unregistered callback" );
var obj2 = { chicken: 151 };
events.unregister("doThingA", obj2, func2);
t.ok( (listenerList.length == 1), "unregister does not bomb or accidntally remove if you try to remove a valid callback on a valid event type, but with the wrong context object" );
events.unregister("doThingA", obj, null);
t.ok( (listenerList.length == 1), "unregister does not bomb if you try to remove a null callback" );
events.unregister("chicken", null, func3);
t.ok( events.listeners["chicken"] == null, "unregistering an event that is not enabled does not wierdly enable it -- or cause a script error")
}
function test_Events_remove(t) {
t.plan( 2 );
var mapDiv = OpenLayers.Util.getElement('map');
var obj = {result: 0};
var eventTypes = ["doThingA", "doThingB", "doThingC"];
events = new OpenLayers.Events(obj, mapDiv, eventTypes);
var func = function () { this.result++ }
var func2 = function () { this.result-- }
var func3 = function () { this.result = this.result + 3; }
events.register( "doThingA", obj, func );
events.register( "doThingA", obj, func2 );
events.register( "doThingA", null, func3 );
events.remove("doThingA");
t.eq( events.listeners["doThingA"].length, 0, "remove() correctly clears the event listeners" );
events.remove("chicken");
t.ok( events.listeners["chicken"] == null, "remove on non-enabled event does not break or accidentally enable the event");
}
function test_Events_triggerEvent(t) {
t.plan(13);
var mapDiv = OpenLayers.Util.getElement('map');
var obj = {result: 0};
var eventTypes = ["doThingA", "doThingB", "doThingC"];
events = new OpenLayers.Events(obj, mapDiv, eventTypes);
var func = function () { this.result++ }
events.register( "doThingA", obj, func );
events.triggerEvent("doThingA", {});
t.eq( obj.result, 1, "result is 1 after we call triggerEvent" );
events.triggerEvent("doThingA");
t.eq( obj.result, 2, "result is 2 after we call triggerEvent with no event" );
var funcB = function() { this.FUNK = "B"; return false; }
events.register( "doThingA", obj, funcB);
events.triggerEvent("doThingA");
t.ok ((obj.result == 3) && (obj.FUNK == "B"), "executing multiple callbacks works")
var funcZ = function() { this.FUNK = "Z"; }
events.register( "doThingA", obj, funcZ);
events.triggerEvent("doThingA");
t.ok ((obj.result == 4) && (obj.FUNK == "B"), "executing multiple callbacks works, and when one returns false, it stops chain correctly")
var func2 = function() { this.result = this.result + 10; }
events.register( "doThingB", null, func2);
events.triggerEvent("doThingB");
t.eq( obj.result, 14, "passing a null object default gets set correctly");
//no specific t.ok for this one, but if it breaks, you will know it.
events.triggerEvent("chicken");
events = new OpenLayers.Events(null, mapDiv, eventTypes);
// a is global variable (context-irrelevant)
a = 0;
var func = function () { a = 5; }
events.register( "doThingC", null, func );
events.triggerEvent("doThingC");
t.eq(a, 5, "if Events has no object set and an event is registered also with no object, triggerEvent() calls it without trying to set the context to null");
// trigger events with additional arguments
eventTypes = ["something"];
events = new OpenLayers.Events(null, null, eventTypes);
var instance = {id: Math.random()};
var listener = function(obj) {
t.eq(this.id, instance.id,
"listener called with proper scope");
t.eq(arguments.length, 1,
"listener called with a single argument");
t.eq(typeof arguments, "object",
"listener called with an object");
t.eq(obj.foo, evt.foo,
"foo property set on the layer");
};
events.register("something", instance, listener);
var evt = {
id: Math.random(),
"foo": "bar"
};
events.triggerEvent("something", evt);
events.unregister("something", instance, listener);
// test return from triggerEvent
var listener1 = function() {
return "foo";
}
var listener2 = function() {
return false;
}
var listener3 = function() {
t.fail("never call me again!");
}
events.register("something", instance, listener1);
var ret = events.triggerEvent("something", evt);
t.eq(ret, "foo", "correct return from single listener");
events.register("something", instance, listener2);
ret = events.triggerEvent("something", evt);
t.eq(ret, false, "correct return for two listeners");
events.register("something", instance, listener3);
ret = events.triggerEvent("something", evt);
t.eq(ret, false, "correct return for three listeners where second cancels");
events.unregister("something", instance, listener1);
events.unregister("something", instance, listener2);
events.unregister("something", instance, listener3);
}
function test_Events_destroy (t) {
t.plan(2);
var div = OpenLayers.Util.getElement('test');
var obj = {};
var events = new OpenLayers.Events(obj, div);
// +1 because of blocking dragstart in attachToElement()
t.eq(OpenLayers.Event.observers[div._eventCacheID].length,
OpenLayers.Events.prototype.BROWSER_EVENTS.length + 1,
"construction creates new arrayin hash, registers appropriate events");
events.destroy();
events = null;
t.eq(OpenLayers.Event.observers["test"], null,
"destruction removes the event observer from hash");
}
function test_Event(t) {
t.plan(24);
var div = OpenLayers.Util.getElement('test');
var name = "mouseover";
var func = function() {};
//1st elem 1st listener
OpenLayers.Event.observe(div, name, func);
var cacheID = div._eventCacheID;
t.ok(cacheID, "element given new cache id");
var elementObservers = OpenLayers.Event.observers[cacheID];
t.ok(elementObservers, "new cache bucket made for event");
t.eq(elementObservers.length, 1, "one listener registered");
var listener = elementObservers[0];
t.ok(listener.element == div, "element registered");
t.eq(listener.name, name, "name registered");
t.ok(listener.observer == func, "function registered");
t.eq(listener.useCapture, false, "useCapture defaults to false");
//1st elem 2nd listener
name = "mouseout";
var newFunc = function() {};
OpenLayers.Event.observe(div, name, newFunc, true);
var newCacheID = div._eventCacheID;
t.eq(newCacheID, cacheID, "element's cache id not overridden");
t.eq(elementObservers.length, 2, "listener added to existing bucket");
var listener = elementObservers[1];
t.ok(listener.element == div, "element registered");
t.eq(listener.name, name, "name registered");
t.ok(listener.observer == newFunc, "function registered");
t.eq(listener.useCapture, true, "useCapture correctly registered");
//2st elem 1st listener
div = OpenLayers.Util.getElement('test2');
OpenLayers.Event.observe(div, name, func);
var cacheID = div._eventCacheID;
t.ok(cacheID, "new element given new cache id");
t.ok(cacheID != newCacheID, "new cache id is unique");
elementObservers = OpenLayers.Event.observers[cacheID];
t.ok(elementObservers, "new cache bucket made for event");
t.eq(elementObservers.length, 1, "one listener registered");
var listener = elementObservers[0];
t.ok(listener.element == div, "element registered");
t.eq(listener.name, name, "name registered");
t.ok(listener.observer == func, "function registered");
t.eq(listener.useCapture, false, "useCapture defaults to false");
//stopObservingElement by element
OpenLayers.Event.stopObservingElement(div);
elementObservers = OpenLayers.Event.observers[cacheID];
t.ok(elementObservers == null, "stopObservingElement by elem works");
//stopObservingElement by id
OpenLayers.Event.stopObservingElement("test");
elementObservers = OpenLayers.Event.observers[newCacheID];
t.ok(elementObservers == null, "stopObservingElement by id works");
//unloadCache by element
OpenLayers.Event.observe(div, name, func);
OpenLayers.Event.unloadCache();
elementObservers = OpenLayers.Event.observers[cacheID];
t.ok(elementObservers == null, "stopObservingElement by elem works");
}
function test_Events_addEventType(t) {
t.plan( 8 );
var mapDiv = OpenLayers.Util.getElement('map');
var obj = {result: 0};
var eventTypes = ["doThingA", "doThingB"];
events = new OpenLayers.Events(obj, mapDiv, eventTypes);
t.eq( events.listeners["doThingA"].length, 0, "event type passed as passed as param to OpenLayers.Events constructor correctly set up" );
t.eq( events.listeners["doThingB"].length, 0, "event type passed as passed as param to OpenLayers.Events constructor correctly set up" );
var newEventType = "onFoo";
t.ok( events.listeners[newEventType] == null, "event type not yet registered has null entry in listeners array");
t.ok( OpenLayers.Util.indexOf(events.eventTypes, newEventType) == -1, "event type not yet registered not in eventTypes array");
events.addEventType(newEventType);
t.eq( events.listeners[newEventType].length, 0, "event type passed to addEventType correctly set up" );
t.ok( OpenLayers.Util.indexOf(events.eventTypes, newEventType) != -1, "event type passed to addEventType in eventTypes array");
var func = function () {};
events.register( "doThingA", obj, func );
t.eq( events.listeners["doThingA"].length, 1, "listener correctly registered" );
events.addEventType("doThingsA");
t.eq( events.listeners["doThingA"].length, 1, "event type passed to addEventType correctly does nothing if clashes with already defined event type" );
}
/** HACK HACK HACK Deprecated This test should be removed in 3.0 **/
function test_Events_globalEventObject(t) {
t.plan(1);
t.ok(Event.stop, "a stop() function exists on the global JS Event object, if indeed it exists. This is legacy deprecated and will be gone in 3.0");
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
<div id="test"></div>
<div id="test2"></div>
</body>
</html>

View File

@ -1,21 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
// Ensure that we continue to work if silly Javascript frameworks
// extend object.
Object.prototype.foo = function() { }
function test_Events_Object_Extension(t) {
t.plan(1)
map = new OpenLayers.Map("map");
t.ok(true, "Map created if object prototype is extended.");
}
</script>
</head>
<body>
<div id="map" style="width: 600px; height: 300px;"/>
</body>
</html>

View File

@ -1,200 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var isMozilla = (navigator.userAgent.indexOf("compatible") == -1);
var map;
var feature, layer;
function test_Feature_constructor (t) {
t.plan( 7 );
var layer = {};
var lonlat = new OpenLayers.LonLat(2,1);
var iconURL = 'http://boston.openguides.org/features/ORANGE.png';
var iconSize = new OpenLayers.Size(12, 17);
var data = { iconURL: iconURL,
iconSize: iconSize
};
feature = new OpenLayers.Feature(layer, lonlat, data);
t.ok( feature instanceof OpenLayers.Feature, "new OpenLayers.Feature returns Feature object" );
t.eq( feature.layer, layer, "feature.layer set correctly" );
t.ok(OpenLayers.String.startsWith(feature.id, "OpenLayers.Feature_"),
"feature.id set correctly");
t.ok( feature.lonlat.equals(lonlat), "feature.lonlat set correctly" );
t.eq( feature.data.iconURL, iconURL, "feature.data.iconURL set correctly" );
t.ok( feature.data.iconSize.equals(iconSize), "feature.data.iconSize set correctly" );
t.ok( feature.popupClass == OpenLayers.Popup.AnchoredBubble, "default popupClass is AnchoredBubble");
}
function test_Feature_createPopup (t) {
t.plan(1);
var layer = {};
var lonlat = new OpenLayers.LonLat(2,1);
var iconURL = 'http://boston.openguides.org/features/ORANGE.png';
var iconSize = new OpenLayers.Size(12, 17);
var data = { iconURL: iconURL,
iconSize: iconSize,
'overflow':'auto'
};
feature = new OpenLayers.Feature(layer, lonlat, data);
popup = feature.createPopup();
//Safari 3 separates style overflow into overflow-x and overflow-y
var prop = (OpenLayers.Util.getBrowserName() == 'safari') ? 'overflowX' : 'overflow';
t.eq(popup.contentDiv.style[prop], "auto", 'overflow on popup is correct');
}
function test_Feature_createMarker (t) {
t.plan(1);
t.ok(true);
/*
t.plan( 11 );
feature = new OpenLayers.Feature("myfeature", new OpenLayers.LonLat(2,1),
{
iconURL:'http://boston.openguides.org/features/ORANGE.png',
iconW: 12,
iconH: 17
});
layer = new OpenLayers.Layer.Markers('Marker Layer');
t.ok( feature instanceof OpenLayers.Feature, "new OpenLayers.Feature returns Feature object" );
t.ok( layer instanceof OpenLayers.Layer.Markers, "Layer is a marker layer" );
feature.createMarker(layer);
t.ok( feature.marker instanceof OpenLayers.Marker,
"createMarker sets a marker property to a marker" );
t.ok( layer.markers[0] === feature.marker,
"First marker in layer is the feature marker" );
t.ok( feature.marker.lonlat instanceof OpenLayers.LonLat,
"createMarker sets a marker lontlat property to a lonlat" );
t.ok( layer.markers[0].lonlat === feature.lonlat,
"First marker in the layer matches feature lonlat" );
t.ok( feature.marker.icon instanceof OpenLayers.Icon,
"createMarker sets a marker icon property to an icon" );
t.eq( feature.marker.icon.url,
"http://boston.openguides.org/features/ORANGE.png",
"createMarker sets marker url correctly" );
var map = new OpenLayers.Map('map');
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0,0),0);
t.ok( map.layers[0] == layer,
"Marker layer added to map okay." );
if (!isMozilla)
t.ok( true, "skipping element test outside of Mozilla");
else
t.ok( map.layers[0].div.firstChild instanceof HTMLImageElement,
"layer div firstChild is an image" );
t.eq( map.layers[0].div.firstChild.src,
"http://boston.openguides.org/features/ORANGE.png",
"Layer div img contains correct url" );
*/
}
function test_Feature_onScreen(t) {
t.plan( 2 );
var map = new OpenLayers.Map("map");
var url = "http://octo.metacarta.com/cgi-bin/mapserv";
var wms = new OpenLayers.Layer.WMS(name, url);
map.addLayer(wms);
var layer = new OpenLayers.Layer("foo");
map.addLayer(layer);
map.zoomToExtent(new OpenLayers.Bounds(-50,-50,50,50));
//onscreen feature
var feature1 = new OpenLayers.Feature(layer,
new OpenLayers.LonLat(0,0));
t.ok( feature1.onScreen(), "feature knows it's onscreen" );
//onscreen feature
var feature2 = new OpenLayers.Feature(layer,
new OpenLayers.LonLat(100,100));
t.ok( !feature2.onScreen(), "feature knows it's offscreen" );
}
function test_Feature_createPopup(t) {
t.plan(11);
//no lonlat
var f = {
'popup': null
};
var ret = OpenLayers.Feature.prototype.createPopup.apply(f, []);
t.ok((ret == f.popup) && (f.popup == null), "if no 'lonlat' set on feature, still returns reference to this.popup (though it is null)");
f.popupClass = OpenLayers.Class({
initialize: function(id, lonlat, size, contentHTML, anchor, closeBox) {
t.eq(id, "Campion_popup", "correctly generates new popup id from feature's id");
t.eq(lonlat, f.lonlat, "correctly passes feature's lonlat to popup constructor");
t.eq(size, f.data.popupSize, "correctly passes feature's data.popupSize to popup constructor");
t.eq(contentHTML, f.data.popupContentHTML, "correctly passes feature's data.popupContentHTML to popup constructor");
t.eq(anchor, g_ExpectedAnchor, "passes correct anchor to popup constructor");
t.eq(closeBox, g_CloseBox, "correctly relays closeBox argument to popup constructor");
}
});
//valid lonlat but no anchor
f.popup = null;
f.id = "Campion";
f.lonlat = {};
f.data = {
'popupSize': {},
'popupContentHTML': {}
};
g_ExpectedAnchor = null;
g_CloseBox = {};
ret = OpenLayers.Feature.prototype.createPopup.apply(f, [g_CloseBox]);
t.ok((ret == f.popup) && (f.popup != null), "a valid popup has been set and returned")
t.ok( f.popup.feature == f, "popup's 'feature' property correctly set");
//valid lonlat with anchor
f.marker = {
'icon': {}
};
g_ExpectedAnchor = f.marker.icon;
ret = OpenLayers.Feature.prototype.createPopup.apply(f, [g_CloseBox]);
t.ok((ret == f.popup) && (f.popup != null), "a valid popup has been set and returned")
t.ok( f.popup.feature == f, "popup's 'feature' property correctly set");
}
function test_Feature_destroyPopup(t) {
t.plan(2);
var f = {
'popup': {
'feature': {},
'destroy': function() {
t.ok(true, "default destroyPopup() calls popup.destroy");
}
}
};
OpenLayers.Feature.prototype.destroyPopup.apply(f, []);
t.ok(f.popup == null, "popup property nullified on destroy");
}
</script>
</head>
<body>
<div id="map" style="width: 500px; height: 300px;"></div>
</body>
</html>

View File

@ -1,136 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
var feature;
function test_Feature_Vector_constructor(t) {
t.plan(3);
var geometry = new OpenLayers.Geometry();
geometry.id = Math.random();
var style = {foo: "bar"};
var attributes = {bar: "foo"};
feature = new OpenLayers.Feature.Vector(geometry, attributes, style);
t.ok(feature instanceof OpenLayers.Feature.Vector,
"new OpenLayers.Feature.Vector returns Feature.Vector object" );
t.eq(feature.attributes, attributes,
"attributes property set properly" );
t.eq(feature.geometry.id, geometry.id,
"geometry.property set properly" );
}
function test_Feature_onScreen(t) {
t.plan(6);
var line = new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(0, 0),
new OpenLayers.Geometry.Point(10, 20)
]);
var feature = new OpenLayers.Feature.Vector(line);
feature.layer = {
map: {
getExtent: function() {
return new OpenLayers.Bounds(5, 5, 10, 10);
}
}
};
t.eq(feature.onScreen(), true,
"intersecting feature returns true for intersection");
t.eq(feature.onScreen(true), true,
"intersecting feature returns true for bounds only");
// move the line so only the bounds intersects
line.move(0, 5);
t.eq(feature.onScreen(), false,
"bounds-only feature returns false for intersection");
t.eq(feature.onScreen(true), true,
"bounds-only feature returns true for bounds only");
// move the line so bounds does not intersect
line.move(0, 10);
t.eq(feature.onScreen(), false,
"off-screen feature returns false for intersection");
t.eq(feature.onScreen(true), false,
"off-screen feature returns false for bounds only");
}
function test_Feature_Vector_clone(t) {
t.plan(6);
var geometry = new OpenLayers.Geometry.Point(Math.random(),
Math.random());
var style = {foo: "bar"};
var attributes = {bar: "foo"};
feature = new OpenLayers.Feature.Vector(geometry, attributes, style);
var clone = feature.clone();
t.ok(clone instanceof OpenLayers.Feature.Vector,
"new OpenLayers.Feature.Vector returns Feature.Vector object");
t.eq(clone.attributes, attributes,
"attributes property set properly");
t.eq(clone.style, style,
"style property set properly");
t.eq(clone.geometry.x, geometry.x,
"geometry.x property set properly");
t.eq(clone.geometry.y, geometry.y,
"geometry.y property set properly");
feature = new OpenLayers.Feature.Vector();
clone = feature.clone();
t.ok(clone instanceof OpenLayers.Feature.Vector,
"clone can clone geometry-less features");
}
function test_Feature_Vector_move(t) {
t.plan(3);
var oldx = 26;
var oldy = 14;
var newx = 6;
var newy = 4;
var res = 10;
var geometry = new OpenLayers.Geometry.Point(oldx,
oldy);
var drawn = false;
feature = new OpenLayers.Feature.Vector(geometry);
feature.layer = {
getViewPortPxFromLonLat : function(lonlat){
return new OpenLayers.Pixel(lonlat.lon,lonlat.lat);
},
map: {
getResolution: function(){
return res;
}
},
drawFeature: function(){
drawn = true;
}
}
var pixel = new OpenLayers.Pixel(newx,newy)
feature.move(pixel);
geometry = feature.geometry;
t.ok(drawn, "The feature is redrawn after the move");
t.eq(geometry.x, res * (newx - oldx) + oldx, "New geometry has proper x coordinate");
t.eq(geometry.y, res * (oldy - newy) + oldy, "New geometry has proper y coordinate");
}
</script>
</head>
<body>
<div id="map" style="width: 500px; height: 300px;"></div>
</body>
</html>

View File

@ -1,21 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var options = {'foo': 'bar'};
var filter = new OpenLayers.Filter(options);
t.ok(filter instanceof OpenLayers.Filter,
"new OpenLayers.Filter returns object" );
t.eq(filter.foo, "bar", "constructor sets options correctly");
t.eq(typeof filter.evaluate, "function", "filter has an evaluate function");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,207 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var options = {'foo': 'bar'};
var filter = new OpenLayers.Filter.Comparison(options);
t.ok(filter instanceof OpenLayers.Filter.Comparison,
"new OpenLayers.Filter.Comparison returns object" );
t.eq(filter.foo, "bar", "constructor sets options correctly");
t.eq(typeof filter.evaluate, "function", "filter has an evaluate function");
}
function test_destroy(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Comparison();
filter.destroy();
t.eq(filter.symbolizer, null, "symbolizer hash nulled properly");
}
function test_value2regex(t) {
t.plan(4);
var filter = new OpenLayers.Filter.Comparison({
property: "foo",
value: "*b?r\\*\\?*",
type: OpenLayers.Filter.Comparison.LIKE});
filter.value2regex("*", "?", "\\");
t.eq(filter.value, ".*b.r\\*\\?.*", "Regular expression generated correctly.");
filter.value = "%b.r!%!.%";
filter.value2regex("%", ".", "!");
t.eq(filter.value, ".*b.r\\%\\..*", "Regular expression with different wildcard and escape chars generated correctly.");
filter.value = "!!";
filter.value2regex();
t.eq(filter.value, "\\!", "!! successfully unescaped to \\!");
// Big one.
filter.value = "!!c!!!d!e";
filter.value2regex();
t.eq(filter.value, "\\!c\\!\\d\\e", "!!c!!!d!e successfully unescaped to \\!c\\!\\d\\e");
}
function test_regex2value(t) {
t.plan(8);
function r2v(regex) {
return OpenLayers.Filter.Comparison.prototype.regex2value.call(
{value: regex}
);
}
t.eq(r2v("foo"), "foo", "doesn't change string without special chars");
t.eq(r2v("foo.*foo"), "foo*foo", "wildCard replaced");
t.eq(r2v("foo.foo"), "foo.foo", "singleChar replaced");
t.eq(r2v("foo\\\\foo"), "foo\\foo", "escape removed");
t.eq(r2v("foo!foo"), "foo!!foo", "escapes !");
t.eq(r2v("foo\\*foo"), "foo!*foo", "replaces escape on *");
t.eq(r2v("foo\\.foo"), "foo!.foo", "replaces escape on .");
t.eq(r2v("foo\\\\.foo"), "foo\\.foo", "unescapes only \\ before .");
}
function test_evaluate(t) {
var cases = [{
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "area",
lowerBoundary: 1000,
upperBoundary: 4999
}),
context: {area: 999},
expect: false
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "area",
lowerBoundary: 1000,
upperBoundary: 4999
}),
context: {area: 1000},
expect: true
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "area",
lowerBoundary: 1000,
upperBoundary: 4999
}),
context: {area: 4999},
expect: true
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "area",
lowerBoundary: 1000,
upperBoundary: 4999
}),
context: {area: 5000},
expect: false
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "area",
lowerBoundary: 1000,
upperBoundary: 4999
}),
context: {area: 999},
expect: false
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "prop",
value: "Foo"
}),
context: {prop: "Foo"},
expect: true
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "prop",
value: "Foo"
}),
context: {prop: "foo"},
expect: false
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
matchCase: true,
property: "prop",
value: "Foo"
}),
context: {prop: "foo"},
expect: false
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
property: "prop",
value: "foo"
}),
context: {prop: "FOO"},
expect: true
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
matchCase: true,
property: "prop",
value: "foo"
}),
context: {prop: "FOO"},
expect: true
}, {
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
matchCase: false,
property: "prop",
value: "foo"
}),
context: {prop: "FOO"},
expect: false
}];
t.plan(cases.length);
var c;
for(var i=0; i<cases.length; ++i) {
c = cases[i];
t.eq(c.filter.evaluate(c.context), c.expect, "case " + i + ": " + c.filter.type);
}
}
function test_clone(t) {
t.plan(3);
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "prop",
value: "val"
});
var clone = filter.clone();
// modify the original
filter.type = OpenLayers.Filter.Comparison.NOT_EQUAL_TO;
t.eq(clone.type, OpenLayers.Filter.Comparison.EQUAL_TO, "clone has proper type");
t.eq(clone.property, "prop", "clone has proper property");
t.eq(clone.value, "val", "clone has proper value");
filter.destroy();
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,67 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var options = {'foo': 'bar'};
var filter = new OpenLayers.Filter.FeatureId(options);
t.ok(filter instanceof OpenLayers.Filter.FeatureId,
"new OpenLayers.Filter.FeatureId returns object" );
t.eq(filter.foo, "bar", "constructor sets options correctly");
t.eq(typeof filter.evaluate, "function", "filter has an evaluate function");
}
function test_destroy(t) {
t.plan(1);
var filter = new OpenLayers.Filter.FeatureId();
filter.destroy();
t.eq(filter.symbolizer, null, "symbolizer hash nulled properly");
}
function test_evaluate(t) {
t.plan(3);
var filter = new OpenLayers.Filter.FeatureId(
{fids: ["fid_1", "fid_3"]});
var filterResults = {
"fid_1" : true,
"fid_2" : false,
"fid_3" : true};
for (var i in filterResults) {
var feature = new OpenLayers.Feature.Vector();
feature.fid = i;
var result = filter.evaluate(feature);
t.eq(result, filterResults[i], "feature "+i+" evaluates to "+result.toString()+" correctly.");
feature.destroy();
}
}
function test_clone(t) {
t.plan(1);
var filter = new OpenLayers.Filter.FeatureId({
fids: [1, 2, 3]
});
var clone = filter.clone();
// modify the original
filter.fids.push(4);
t.eq(clone.fids.length, 3, "clone has proper fids length");
filter.destroy();
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,75 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var options = {'foo': 'bar'};
var filter = new OpenLayers.Filter.Logical(options);
t.ok(filter instanceof OpenLayers.Filter.Logical,
"new OpenLayers.Filter.Logical returns object" );
t.eq(filter.foo, "bar", "constructor sets options correctly");
t.eq(typeof filter.evaluate, "function", "filter has an evaluate function");
}
function test_destroy(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Logical();
filter.destroy();
t.eq(filter.filters, null, "filters array nulled properly");
}
function test_evaluate(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.NOT});
filter.filters.push(new OpenLayers.Filter());
var feature = new OpenLayers.Feature.Vector();
t.eq(filter.evaluate(feature.attributes), false,
"feature evaluates to false correctly.");
}
function test_clone(t) {
t.plan(2);
var filter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND,
filters: [
new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "prop1",
value: "val1"
}),
new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
property: "prop2",
value: "val2"
})
]
});
var clone = filter.clone();
// modify the original
filter.type = OpenLayers.Filter.Logical.OR;
filter.filters[0].value = "nada";
t.eq(clone.type, OpenLayers.Filter.Logical.AND, "clone has proper type");
t.eq(clone.filters[0].value, "val1", "clone has cloned child filters");
filter.destroy();
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,103 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_constructor(t) {
t.plan(3);
var options = {'foo': 'bar'};
var filter = new OpenLayers.Filter.Spatial(options);
t.ok(filter instanceof OpenLayers.Filter.Spatial,
"new OpenLayers.Filter.Spatial returns object" );
t.eq(filter.foo, "bar", "constructor sets options correctly");
t.eq(typeof filter.evaluate, "function", "filter has an evaluate function");
}
function test_destroy(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Spatial();
filter.destroy();
t.eq(filter.symbolizer, null, "symbolizer hash nulled properly");
}
function test_evaluate(t) {
t.plan(4);
var filer, feature, res, geom, bounds;
bounds = new OpenLayers.Bounds(0, 0, 10, 10);
filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.BBOX,
value: bounds
});
// 1 test
feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(2, 2));
res = filter.evaluate(feature);
t.eq(res, true,
"evaluates returns correct value when feature intersects bounds");
// 1 test
feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(20, 20));
res = filter.evaluate(feature);
t.eq(res, false,
"evaluates returns correct value when feature does not intersect bounds");
// 1 test
geom = bounds.toGeometry();
feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(2, 2));
filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.INTERSECTS,
value: geom
});
res = filter.evaluate(feature);
t.eq(res, true,
"evaluates returns correct value when feature intersects bounds");
// 1 test
geom = bounds.toGeometry();
feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(20, 20));
filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.INTERSECTS,
value: geom
});
res = filter.evaluate(feature);
t.eq(res, false,
"evaluates returns correct value when feature does not intersect bounds");
}
function test_clone(t) {
t.plan(2);
var bounds = new OpenLayers.Bounds(0, 0, 10, 10);
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.BBOX,
value: bounds
});
var clone = filter.clone();
// modify the original
filter.value.bottom = -100;
t.eq(clone.type, OpenLayers.Filter.Spatial.BBOX, "clone has proper type");
t.eq(clone.value.toBBOX(), "0,0,10,10", "clone has proper value");
filter.destroy();
clone.destroy();
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,23 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Format_constructor(t) {
t.plan(5);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format(options);
t.ok(format instanceof OpenLayers.Format,
"new OpenLayers.Format returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
t.eq(format.options, options, "format.options correctly set");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,277 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var axl_image_response = '<?xml version="1.0" encoding="UTF-8"?><ARCXML version="1.1"><RESPONSE><IMAGE><ENVELOPE minx="-2471.42857142857" miny="0" maxx="105671.428571429" maxy="75700" /><OUTPUT url="http://localhost/output/364826560.png" /></IMAGE></RESPONSE></ARCXML>';
var axl_feature_response = '<?xml version="1.0" encoding="Cp1252"?><ARCXML version="1.1"><RESPONSE><FEATURES><FEATURE><FIELDS><FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e18a454f619" /><FIELD name="LABEL" value="LIBRARY" /><FIELD name="Y_COORD" value="39.57" /><FIELD name="X_COORD" value="-104.24" /><FIELD name="#SHAPE#" value="[Geometry]" /><FIELD name="OBJECTID" value="1" /><FIELD name="shape.area" value="0" /><FIELD name="shape.len" value="0" /></FIELDS></FEATURE><FEATURE><FIELDS><FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e81a454f619" /><FIELD name="LABEL" value="LIBRARY2" /><FIELD name="Y_COORD" value="39.75" /><FIELD name="X_COORD" value="-104.42" /><FIELD name="#SHAPE#" value="[Geometry]" /><FIELD name="OBJECTID" value="2" /><FIELD name="shape.area" value="0" /><FIELD name="shape.len" value="0" /></FIELDS></FEATURE><FEATURECOUNT count="2" hasmore="false" /><ENVELOPE minx="-678853.220047791" miny="1810.22081371862" maxx="-678853.220047791" maxy="1810.22081371862"/></FEATURES></RESPONSE></ARCXML>';
//
// creating a new arcxml format creates an object that has a read and write function
//
function test_Format_ArcXML_constructor1(t) {
t.plan(4);
var format = new OpenLayers.Format.ArcXML();
t.ok(format instanceof OpenLayers.Format.ArcXML,
"new OpenLayers.Format.ArcXML returns object" );
t.ok(format.request, null, "no options creates a null request");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
//
// creating a new arcxml format with a set of options for an image request
// creates a request child object, and a get_image grandchild.
//
function test_Format_ArcXML_constructor2(t) {
t.plan(6);
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var format = new OpenLayers.Format.ArcXML( options );
t.ok(format instanceof OpenLayers.Format.ArcXML,
"new OpenLayers.Format.ArcXML returns object" );
t.ok(format.request instanceof OpenLayers.Format.ArcXML.Request,
"constructor with 'image' requesttype generates a request");
t.ok( format.request.get_image !== null, "get_image property exists" );
t.ok( format.request.get_feature === null, "get_feature property does not exists" );
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
//
// creating a new arcxml format with a set of options for a feature request
// creates a request child object, and a get_feature grandchild
//
function test_Format_ArcXML_constructor3(t) {
t.plan(6);
var options = {
requesttype:'feature'
};
var format = new OpenLayers.Format.ArcXML( options );
t.ok(format instanceof OpenLayers.Format.ArcXML,
"new OpenLayers.Format.ArcXML returns object" );
t.ok(format.request instanceof OpenLayers.Format.ArcXML.Request,
"constructor with 'feature' requesttype generates a request");
t.ok( format.request.get_feature !== null, "get_feature property exists" );
t.ok( format.request.get_image === null, "get_image property does not exists" );
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
//
// read in a known good axl image response
//
function test_Format_ArcXML_read1(t) {
t.plan(4);
var f = new OpenLayers.Format.ArcXML();
var response = f.read(axl_image_response);
t.ok(response !== null, "get_image response object is not null" );
t.ok(response.image !== null, "get_image image tag is not null");
t.ok(response.image.envelope !== null, "get_image image envelope tag is not null");
t.ok(response.image.output !== null, "get_image image output tag is not null");
}
//
// read in a known good axl feature response
//
function test_Format_ArcXML_read2(t) {
t.plan(10);
var f = new OpenLayers.Format.ArcXML();
var response = f.read(axl_feature_response);
t.ok(response !== null, "get_feature response object is not null" );
t.ok(response.features !== null, "get_feature features tag is not null");
t.ok(response.features.envelope !== null, "get_feature envelope tag is not null");
t.eq(response.features.featurecount, "2", "feature count is 2" );
// test the second feature parsed
// <FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e81a454f619" />
// <FIELD name="LABEL" value="LIBRARY2" />
// <FIELD name="Y_COORD" value="39.75" />
// <FIELD name="X_COORD" value="-104.42" />
// <FIELD name="#SHAPE#" value="[Geometry]" />
// <FIELD name="OBJECTID" value="2" />
// <FIELD name="shape.area" value="0" />
// <FIELD name="shape.len" value="0" />
t.eq( response.features.feature[1].attributes['UNIQUE_ID'], "514504b5-0458-461d-b540-8e81a454f619", "field 1 for feature 2 is correct" );
t.eq( response.features.feature[1].attributes['LABEL'], "LIBRARY2", "field 2 for feature 2 is correct" );
t.eq( response.features.feature[1].attributes['Y_COORD'], "39.75", "field 3 for feature 2 is correct" );
t.eq( response.features.feature[1].attributes['X_COORD'], "-104.42", "field 4 for feature 2 is correct" );
t.eq( response.features.feature[1].attributes['#SHAPE#'], "[Geometry]", "field 5 for feature 2 is correct" );
t.eq( response.features.feature[1].attributes['OBJECTID'], "2", "field 6 for feature 2 is correct" );
}
//
// cause an error by parsing bad axl
//
function test_Format_ArcXML_parseerror(t) {
t.plan(1);
var f = new OpenLayers.Format.ArcXML();
try {
f.read( '<?xml version="1.0" encoding="Cp1252"?><ARCXML version="1.1"><NO END TAG>' );
t.fail("parsing failed to fail")
} catch (ex) {
t.ok( true, "Exception message indicates parsing error." );
}
}
//
// create an arcxml image request, and verify that it matches a known image request
//
function test_format_ArcXML_write1(t) {
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var truth = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><FEATURECOORDSYS id="4326"/><FILTERCOORDSYS id="4326"/><ENVELOPE minx="-180" miny="-90" maxx="180" maxy="90"/><IMAGESIZE height="256" width="256"/></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
axl_write(t,options,truth);
}
//
// create an arcxml image request that specifies layer visibilities, and
// verify that it matches a known image request
//
function test_format_ArcXML_write2(t) {
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [{
id: "0",
visible: "true"
}],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var truth = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><FEATURECOORDSYS id="4326"/><FILTERCOORDSYS id="4326"/><ENVELOPE minx="-180" miny="-90" maxx="180" maxy="90"/><IMAGESIZE height="256" width="256"/><LAYERLIST><LAYERDEF id="0" visible="true"/></LAYERLIST></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
axl_write(t, options, truth );
}
//
// create an arcxml image request that performs a query for thematic mapping,
// and verify that it matches a known image request
//
function test_format_ArcXML_write3(t) {
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [{
id: "0",
visible: "true",
query: {
where: "COMPANY='AVENCIA'"
}
}],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var truth = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><FEATURECOORDSYS id="4326"/><FILTERCOORDSYS id="4326"/><ENVELOPE minx="-180" miny="-90" maxx="180" maxy="90"/><IMAGESIZE height="256" width="256"/><LAYERLIST><LAYERDEF id="0" visible="true"><QUERY where="COMPANY=\'AVENCIA\'"/></LAYERDEF></LAYERLIST></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
axl_write(t, options, truth );
}
//
// create an arcxml image request that performs a spatial query for thematic mapping,
// and verify that it matches a known image request
//
function test_format_ArcXML_write4(t) {
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [{
id: "0",
visible: "true",
query: {
spatialfilter: true,
where: "COMPANY='AVENCIA'"
}
}],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var truth = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><FEATURECOORDSYS id="4326"/><FILTERCOORDSYS id="4326"/><ENVELOPE minx="-180" miny="-90" maxx="180" maxy="90"/><IMAGESIZE height="256" width="256"/><LAYERLIST><LAYERDEF id="0" visible="true"><SPATIALQUERY where="COMPANY=\'AVENCIA\'"/></LAYERDEF></LAYERLIST></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
axl_write(t, options, truth );
}
//
// create an arcxml image request that performs a thematic map request, and
// verify that it matches a known image request.
//
function test_format_ArcXML_write5(t) {
var options = {
requesttype:'image',
envelope: new OpenLayers.Bounds( -180, -90, 180, 90 ).toArray(),
layers: [{
id: "0",
visible: "true",
query: {
spatialfilter: true,
where: "COMPANY='AVENCIA'"
},
renderer: {
type: 'valuemap',
lookupfield: 'lookup',
ranges: [{
lower: 0,
upper: 10,
symbol: {
type: 'simplepolygon',
fillcolor: '0,0,0'
}
},{
lower: 10,
upper: 20,
symbol: {
type: 'simplepolygon',
fillcolor: '255,255,255'
}
}]
}
}],
tileSize: new OpenLayers.Size( 256,256 ),
featureCoordSys: '4326',
filterCoordSys: '4326'
};
var truth = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><FEATURECOORDSYS id="4326"/><FILTERCOORDSYS id="4326"/><ENVELOPE minx="-180" miny="-90" maxx="180" maxy="90"/><IMAGESIZE height="256" width="256"/><LAYERLIST><LAYERDEF id="0" visible="true"><SPATIALQUERY where="COMPANY=\'AVENCIA\'"/><VALUEMAPRENDERER lookupfield="lookup"><RANGE lower="0" upper="10"><SIMPLEPOLYGONSYMBOL fillcolor="0,0,0"/></RANGE><RANGE lower="10" upper="20"><SIMPLEPOLYGONSYMBOL fillcolor="255,255,255"/></RANGE></VALUEMAPRENDERER></LAYERDEF></LAYERLIST></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
axl_write(t, options, truth );
}
//
// helper function to write some axl, and compare it against a truth axl string
//
function axl_write(t, options, truth) {
t.plan(1);
var f = new OpenLayers.Format.ArcXML( options );
var arcxml = f.write();
t.eq( arcxml, truth, "ArcXML request is correct.");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,69 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var axl_feature_response = '<?xml version="1.0" encoding="Cp1252"?><ARCXML version="1.1"><RESPONSE><FEATURES><FEATURE><FIELDS><FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e18a454f619" /><FIELD name="LABEL" value="LIBRARY" /><FIELD name="Y_COORD" value="39.57" /><FIELD name="X_COORD" value="-104.24" /><FIELD name="#SHAPE#" value="[Geometry]" /><FIELD name="OBJECTID" value="1" /><FIELD name="shape.area" value="0" /><FIELD name="shape.len" value="0" /></FIELDS></FEATURE><FEATURE><FIELDS><FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e81a454f619" /><FIELD name="LABEL" value="LIBRARY2" /><FIELD name="Y_COORD" value="39.75" /><FIELD name="X_COORD" value="-104.42" /><FIELD name="#SHAPE#" value="[Geometry]" /><FIELD name="OBJECTID" value="2" /><FIELD name="shape.area" value="0" /><FIELD name="shape.len" value="0" /></FIELDS></FEATURE><FEATURECOUNT count="2" hasmore="false" /><ENVELOPE minx="-678853.220047791" miny="1810.22081371862" maxx="-678853.220047791" maxy="1810.22081371862"/></FEATURES></RESPONSE></ARCXML>';
//
// creating a new arcxml features format creates an object that has a read and write function
//
function test_initialize(t) {
t.plan(3);
var format = new OpenLayers.Format.ArcXML.Features();
t.ok(format instanceof OpenLayers.Format.ArcXML.Features,
"new OpenLayers.Format.ArcXML.Features returns object" );
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
//
// read in a known good axl feature response
//
function test_read1(t) {
t.plan(8);
var f = new OpenLayers.Format.ArcXML.Features();
var features = f.read(axl_feature_response);
t.ok(features !== null, "features are not null" );
t.eq(features.length, 2, "feature count is 2" );
// test the second feature parsed
// <FIELD name="UNIQUE_ID" value="514504b5-0458-461d-b540-8e81a454f619" />
// <FIELD name="LABEL" value="LIBRARY2" />
// <FIELD name="Y_COORD" value="39.75" />
// <FIELD name="X_COORD" value="-104.42" />
// <FIELD name="#SHAPE#" value="[Geometry]" />
// <FIELD name="OBJECTID" value="2" />
// <FIELD name="shape.area" value="0" />
// <FIELD name="shape.len" value="0" />
t.eq( features[1].attributes['UNIQUE_ID'], "514504b5-0458-461d-b540-8e81a454f619", "field 1 for feature 2 is correct" );
t.eq( features[1].attributes['LABEL'], "LIBRARY2", "field 2 for feature 2 is correct" );
t.eq( features[1].attributes['Y_COORD'], "39.75", "field 3 for feature 2 is correct" );
t.eq( features[1].attributes['X_COORD'], "-104.42", "field 4 for feature 2 is correct" );
t.eq( features[1].attributes['#SHAPE#'], "[Geometry]", "field 5 for feature 2 is correct" );
t.eq( features[1].attributes['OBJECTID'], "2", "field 6 for feature 2 is correct" );
}
//
// cause an error by parsing bad axl
//
function test_parseerror(t) {
t.plan(1);
var f = new OpenLayers.Format.ArcXML.Features();
try {
f.read( '<?xml version="1.0" encoding="Cp1252"?><ARCXML version="1.1"><NO END TAG>' );
t.fail("reading didn't fail");
} catch (ex) {
t.eq( ex.message, "Error parsing the ArcXML request", "Exception message indicates parsing error." );
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,21 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(3);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.Filter(options);
t.ok(format instanceof OpenLayers.Format.Filter,
"new OpenLayers.Format.Filter returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,126 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Intersects(t) {
t.plan(4);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<Intersects>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Polygon xmlns:gml="http://www.opengis.net/gml">' +
'<gml:outerBoundaryIs>' +
'<gml:LinearRing>' +
'<gml:coordinates decimal="." cs="," ts=" ">2488789,289552 2588789,289552 2588789,389552 2488789,389552 2488789,289552</gml:coordinates>' +
'</gml:LinearRing>' +
'</gml:outerBoundaryIs>' +
'</gml:Polygon>' +
'</Intersects>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_0_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.INTERSECTS,
property: "Geometry",
value: OpenLayers.Geometry.fromWKT("POLYGON((2488789 289552, 2588789 289552, 2588789 389552, 2488789 389552, 2488789 289552))")
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.geom_eq(got.value, filter.value, "read correct value");
}
function test_Within(t) {
t.plan(4);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<Within>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Polygon xmlns:gml="http://www.opengis.net/gml">' +
'<gml:outerBoundaryIs>' +
'<gml:LinearRing>' +
'<gml:coordinates decimal="." cs="," ts=" ">2488789,289552 2588789,289552 2588789,389552 2488789,389552 2488789,289552</gml:coordinates>' +
'</gml:LinearRing>' +
'</gml:outerBoundaryIs>' +
'</gml:Polygon>' +
'</Within>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_0_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.WITHIN,
property: "Geometry",
value: OpenLayers.Geometry.fromWKT("POLYGON((2488789 289552, 2588789 289552, 2588789 389552, 2488789 389552, 2488789 289552))")
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.geom_eq(got.value, filter.value, "read correct value");
}
function test_Contains(t) {
t.plan(4);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<Contains>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Polygon xmlns:gml="http://www.opengis.net/gml">' +
'<gml:outerBoundaryIs>' +
'<gml:LinearRing>' +
'<gml:coordinates decimal="." cs="," ts=" ">2488789,289552 2588789,289552 2588789,389552 2488789,389552 2488789,289552</gml:coordinates>' +
'</gml:LinearRing>' +
'</gml:outerBoundaryIs>' +
'</gml:Polygon>' +
'</Contains>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_0_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.CONTAINS,
property: "Geometry",
value: OpenLayers.Geometry.fromWKT("POLYGON((2488789 289552, 2588789 289552, 2588789 389552, 2488789 389552, 2488789 289552))")
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.geom_eq(got.value, filter.value, "read correct value");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,160 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var test_xml =
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:Or>' +
'<ogc:PropertyIsBetween>' +
'<ogc:PropertyName>number</ogc:PropertyName>' +
'<ogc:LowerBoundary>' +
'<ogc:Literal>1064866676</ogc:Literal>' +
'</ogc:LowerBoundary>' +
'<ogc:UpperBoundary>' +
'<ogc:Literal>1065512599</ogc:Literal>' +
'</ogc:UpperBoundary>' +
'</ogc:PropertyIsBetween>' +
'<ogc:PropertyIsLike wildCard="*" singleChar="." escape="!">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>*dog.food!*good</ogc:Literal>' +
'</ogc:PropertyIsLike>' +
'<ogc:Not>' +
'<ogc:PropertyIsLessThanOrEqualTo>' +
'<ogc:PropertyName>FOO</ogc:PropertyName>' +
'<ogc:Literal>5000</ogc:Literal>' +
'</ogc:PropertyIsLessThanOrEqualTo>' +
'</ogc:Not>' +
'</ogc:Or>' +
'</ogc:Filter>';
function test_read(t) {
t.plan(3);
var parser = new OpenLayers.Format.Filter.v1_0_0();
var xml = new OpenLayers.Format.XML();
var filter = parser.read(xml.read(test_xml).documentElement);
t.ok(filter instanceof OpenLayers.Filter.Logical, "instance of correct class");
t.eq(filter.type, OpenLayers.Filter.Logical.OR, "correct type");
t.eq(filter.filters.length, 3, "correct number of child filters");
}
function test_write(t) {
t.plan(1);
// read first - testing that write produces the ogc:Filter element above
var parser = new OpenLayers.Format.Filter.v1_0_0();
var xml = new OpenLayers.Format.XML();
var filter = parser.read(xml.read(test_xml).documentElement);
var node = parser.write(filter);
t.xml_eq(node, test_xml, "filter correctly written");
}
function test_BBOX(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.BBOX,
property: "the_geom",
value: new OpenLayers.Bounds(-180, -90, 180, 90),
projection: "EPSG:4326"
});
var out =
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:BBOX>' +
'<ogc:PropertyName>the_geom</ogc:PropertyName>' +
'<gml:Box xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:4326">' +
'<gml:coordinates decimal="." cs="," ts=" ">-180,-90 180,90</gml:coordinates>' +
'</gml:Box>' +
'</ogc:BBOX>' +
'</ogc:Filter>';
var parser = new OpenLayers.Format.Filter.v1_0_0();
var node = parser.write(filter);
t.xml_eq(node, out, "bbox correctly written");
}
function test_DWithin(t) {
t.plan(6);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<DWithin>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Point xmlns:gml="http://www.opengis.net/gml">' +
'<gml:coordinates decimal="." cs="," ts=" ">2488789,289552</gml:coordinates>' +
'</gml:Point>' +
'<Distance units="m">1000</Distance>' +
'</DWithin>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_0_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.DWITHIN,
property: "Geometry",
value: new OpenLayers.Geometry.Point(2488789,289552),
distance: 1000,
distanceUnits: "m"
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.geom_eq(got.value, filter.value, "read correct value");
t.eq(got.distance, filter.distance, "read correct distance");
t.eq(got.distanceUnits, filter.distanceUnits, "read correct distance units");
}
function test_Intersects(t) {
t.plan(4);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<Intersects>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Box xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:4326">' +
'<gml:coordinates decimal="." cs="," ts=" ">-180,-90 180,90</gml:coordinates>' +
'</gml:Box>' +
'</Intersects>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_0_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.INTERSECTS,
property: "Geometry",
value: new OpenLayers.Bounds(-180, -90, 180, 90),
projection: "EPSG:4326"
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.eq(got.value.toArray(), filter.value.toArray(), "read correct value");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,210 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var test_xml =
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:Or>' +
'<ogc:PropertyIsBetween>' +
'<ogc:PropertyName>number</ogc:PropertyName>' +
'<ogc:LowerBoundary>' +
'<ogc:Literal>1064866676</ogc:Literal>' +
'</ogc:LowerBoundary>' +
'<ogc:UpperBoundary>' +
'<ogc:Literal>1065512599</ogc:Literal>' +
'</ogc:UpperBoundary>' +
'</ogc:PropertyIsBetween>' +
'<ogc:PropertyIsLike wildCard="*" singleChar="." escape="!">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>*dog.food!*good</ogc:Literal>' +
'</ogc:PropertyIsLike>' +
'<ogc:Not>' +
'<ogc:PropertyIsLessThanOrEqualTo>' +
'<ogc:PropertyName>FOO</ogc:PropertyName>' +
'<ogc:Literal>5000</ogc:Literal>' +
'</ogc:PropertyIsLessThanOrEqualTo>' +
'</ogc:Not>' +
'<ogc:PropertyIsEqualTo matchCase="true">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'<ogc:PropertyIsEqualTo matchCase="false">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Or>' +
'</ogc:Filter>';
function test_read(t) {
t.plan(3);
var parser = new OpenLayers.Format.Filter.v1_1_0();
var xml = new OpenLayers.Format.XML();
var filter = parser.read(xml.read(test_xml).documentElement);
t.ok(filter instanceof OpenLayers.Filter.Logical, "instance of correct class");
t.eq(filter.type, OpenLayers.Filter.Logical.OR, "correct type");
t.eq(filter.filters.length, 5, "correct number of child filters");
}
function test_write(t) {
t.plan(1);
// read first - testing that write produces the ogc:Filter element above
var parser = new OpenLayers.Format.Filter.v1_1_0();
var xml = new OpenLayers.Format.XML();
var filter = parser.read(xml.read(test_xml).documentElement);
var node = parser.write(filter);
t.xml_eq(node, test_xml, "filter correctly written");
}
function test_matchCase(t) {
var parser = new OpenLayers.Format.Filter.v1_1_0();
var xml = new OpenLayers.Format.XML();
var cases = [{
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsEqualTo>' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Filter>',
exp: true
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsEqualTo matchCase="1">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Filter>',
exp: true
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsEqualTo matchCase="true">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Filter>',
exp: true
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsEqualTo matchCase="0">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Filter>',
exp: false
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsEqualTo matchCase="0">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsEqualTo>' +
'</ogc:Filter>',
exp: false
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsNotEqualTo matchCase="true">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsNotEqualTo>' +
'</ogc:Filter>',
exp: true
}, {
str:
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:PropertyIsNotEqualTo matchCase="false">' +
'<ogc:PropertyName>cat</ogc:PropertyName>' +
'<ogc:Literal>dog</ogc:Literal>' +
'</ogc:PropertyIsNotEqualTo>' +
'</ogc:Filter>',
exp: false
}];
t.plan(cases.length);
var filter, c;
for(var i=0; i<cases.length; ++i) {
c = cases[i];
filter = parser.read(xml.read(c.str).documentElement);
t.eq(filter.matchCase, c.exp, "case " + i);
}
}
function test_BBOX(t) {
t.plan(1);
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.BBOX,
property: "the_geom",
value: new OpenLayers.Bounds(-180, -90, 180, 90),
projection: "EPSG:4326"
});
var out =
'<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">' +
'<ogc:BBOX>' +
'<ogc:PropertyName>the_geom</ogc:PropertyName>' +
'<gml:Envelope xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:4326">' +
'<gml:lowerCorner>-180 -90</gml:lowerCorner>' +
'<gml:upperCorner>180 90</gml:upperCorner>' +
'</gml:Envelope>' +
'</ogc:BBOX>' +
'</ogc:Filter>';
var parser = new OpenLayers.Format.Filter.v1_1_0();
var node = parser.write(filter);
t.xml_eq(node, out, "bbox correctly written");
}
function test_Intersects(t) {
t.plan(4);
var str =
'<Filter xmlns="http://www.opengis.net/ogc">' +
'<Intersects>' +
'<PropertyName>Geometry</PropertyName>' +
'<gml:Envelope xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:4326">' +
'<gml:lowerCorner>-180 -90</gml:lowerCorner>' +
'<gml:upperCorner>180 90</gml:upperCorner>' +
'</gml:Envelope>' +
'</Intersects>' +
'</Filter>';
var format = new OpenLayers.Format.Filter.v1_1_0();
var filter = new OpenLayers.Filter.Spatial({
type: OpenLayers.Filter.Spatial.INTERSECTS,
property: "Geometry",
value: new OpenLayers.Bounds(-180, -90, 180, 90),
projection: "EPSG:4326"
});
// test writing
var node = format.write(filter);
t.xml_eq(node, str, "filter correctly written");
// test reading
var doc = (new OpenLayers.Format.XML).read(str);
var got = format.read(doc.firstChild);
t.eq(got.type, filter.type, "read correct type");
t.eq(got.property, filter.property, "read correct property");
t.eq(got.value.toArray(), filter.value.toArray(), "read correct value");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,420 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Format_GML_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.GML(options);
t.ok(format instanceof OpenLayers.Format.GML,
"new OpenLayers.Format.GML returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_GML_getFid(t) {
t.plan(2);
var parser = new OpenLayers.Format.GML();
data = parser.read(test_content[1]);
t.eq(data[0].fid, '221', 'fid on polygons set correctly (with whitespace)');
t.eq(data[1].fid, '8', 'fid on linestrings set correctly with whitespace');
}
function test_Format_GML_no_clobber(t) {
t.plan(1);
var parser = new OpenLayers.Format.GML();
data = parser.read(test_content[1]);
t.eq(window.i, undefined,
"i is undefined in window scope after reading.");
}
function test_Format_GML_read_3d(t) {
t.plan(2);
var parser = new OpenLayers.Format.GML();
data = parser.read(test_content[0]);
t.eq(data[0].geometry.getBounds().toBBOX(), "-1254041.389712,250906.951598,-634517.119991,762236.29408", "Reading 3d content returns geometry with correct bounds (no 0,0)");
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Reading 3d content returns polygon geometry");
}
function test_Format_GML_write_geoms(t) {
t.plan(5);
var parser = new OpenLayers.Format.GML();
var point = shell_start + serialize_geoms['point'] + shell_end;
data = parser.read(point);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, point, "Point geometry round trips correctly.");
var linestring = shell_start + serialize_geoms['linestring'] + shell_end;
data = parser.read(linestring);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, linestring, "Line geometry round trips correctly.");
var polygon = shell_start + serialize_geoms['polygon'] + shell_end;
data = parser.read(polygon);
var output = parser.write(data);
output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, polygon, "Poly geometry round trips correctly.");
var multipoint = shell_start + serialize_geoms['multipoint'] + shell_end;
data = parser.read(multipoint);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, multipoint, "MultiPoint geometry round trips correctly.");
var multilinestring = shell_start + serialize_geoms['multilinestring'] + shell_end;
data = parser.read(multilinestring);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, multilinestring, "MultiLine geometry round trips correctly.");
}
function test_Format_GML_read_point_geom(t) {
t.plan(3);
var point = shell_start + geoms['point'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(point);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Point", "Point GML returns correct classname");
t.eq(data[0].geometry.x, 1, "x coord correct");
t.eq(data[0].geometry.y, 2, "y coord correct");
}
function test_Format_GML_read_linestring_geom(t) {
t.plan(5);
var line = shell_start + geoms['linestring'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(line);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.LineString", "LineString GML returns correct classname");
t.eq(data[0].geometry.components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[1].y, 5, "second y coord correct");
}
function test_Format_GML_read_polygon_geom(t) {
t.plan(7);
var polygon = shell_start + geoms['polygon'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(polygon);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Polygon GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "second y coord correct");
t.eq(data[0].geometry.components[0].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components.length, 1, "rings length correct");
}
function test_Format_GML_read_multipoint_geom(t) {
t.plan(6);
var multipoint = shell_start + geoms['multipoint'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(multipoint);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.MultiPoint", "MultiPoint GML returns correct classname");
t.eq(data[0].geometry.components[0].x, 1, "x coord correct");
t.eq(data[0].geometry.components[0].y, 2, "y coord correct");
t.eq(data[0].geometry.components.length, 2, "length correct");
t.eq(data[0].geometry.components[1].x, 4, "x coord correct");
t.eq(data[0].geometry.components[1].y, 5, "y coord correct");
}
function test_Format_GML_read_multilinestring_geom(t) {
t.plan(6);
var multilinestring = shell_start + geoms['multilinestring'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(multilinestring);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.MultiLineString", "MultiLineString GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "y coord correct");
t.eq(data[0].geometry.components[0].components.length, 2, "length correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "y coord correct");
}
function test_Format_GML_read_polygon_with_holes_geom(t) {
t.plan(12);
var polygon_with_holes = shell_start + geoms['polygon_with_holes'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(polygon_with_holes);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Polygon GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "second y coord correct");
t.eq(data[0].geometry.components[0].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components[1].components[0].x, 11, "first x coord correct");
t.eq(data[0].geometry.components[1].components[0].y, 12, "first y coord correct");
t.eq(data[0].geometry.components[1].components[1].x, 14, "second x coord correct");
t.eq(data[0].geometry.components[1].components[1].y, 15, "second y coord correct");
t.eq(data[0].geometry.components[1].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components.length, 2, "rings length correct");
}
function test_Format_GML_read_attributes(t) {
t.plan(3);
var parser = new OpenLayers.Format.GML();
data = parser.read(test_content[0]);
t.eq(data[0].attributes['NAME'], "WY", "Simple Attribute data is read correctly.");
t.eq(data[0].attributes['LONGNAME'], "Wyoming", "Attribute data is read from CDATA node correctly.");
t.ok(data[0].attributes['EMPTYATTR'] === null, "Attribute set to null for empty element.");
}
function test_Format_GML_read_envelope_geom(t) {
t.plan(13);
var envelope = shell_start + geoms['envelope'] + shell_end;
var parser = new OpenLayers.Format.GML();
data = parser.read(envelope);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Envelope GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 0, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 1, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 20, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 1, "second y coord correct");
t.eq(data[0].geometry.components[0].components[2].x, 20, "third x coord correct");
t.eq(data[0].geometry.components[0].components[2].y, 21, "third y coord correct");
t.eq(data[0].geometry.components[0].components[3].x, 0, "fouth x coord correct");
t.eq(data[0].geometry.components[0].components[3].y, 21, "fourth y coord correct");
t.eq(data[0].geometry.components[0].components[4].x, 0, "fifth x coord correct");
t.eq(data[0].geometry.components[0].components[4].y, 1, "fifth y coord correct");
t.eq(data[0].geometry.components[0].components.length, 5, "coords length correct");
t.eq(data[0].geometry.components.length, 1, "rings length correct");
}
///////////////////////////////////////////////////////////////
// tests the y x order of gml point
/////////////////////////////////////////////////////////////
function test_Format_GML_read_point_geom_yx(t) {
t.plan(3);
var point = shell_start + geoms_yx['point'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(point);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Point", "Point GML returns correct classname");
t.eq(data[0].geometry.x, 1, "x coord correct");
t.eq(data[0].geometry.y, 2, "y coord correct");
}
function test_Format_GML_read_linestring_geom_yx(t) {
t.plan(5);
var line = shell_start + geoms_yx['linestring'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(line);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.LineString", "LineString GML returns correct classname");
t.eq(data[0].geometry.components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[1].y, 5, "second y coord correct");
}
function test_Format_GML_read_polygon_geom_yx(t) {
t.plan(7);
var polygon = shell_start + geoms_yx['polygon'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(polygon);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Polygon GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "second y coord correct");
t.eq(data[0].geometry.components[0].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components.length, 1, "rings length correct");
}
function test_Format_GML_read_multipoint_geom_yx(t) {
t.plan(6);
var multipoint = shell_start + geoms_yx['multipoint'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(multipoint);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.MultiPoint", "MultiPoint GML returns correct classname");
t.eq(data[0].geometry.components[0].x, 1, "x coord correct");
t.eq(data[0].geometry.components[0].y, 2, "y coord correct");
t.eq(data[0].geometry.components.length, 2, "length correct");
t.eq(data[0].geometry.components[1].x, 4, "x coord correct");
t.eq(data[0].geometry.components[1].y, 5, "y coord correct");
}
function test_Format_GML_read_multilinestring_geom_yx(t) {
t.plan(6);
var multilinestring = shell_start + geoms_yx['multilinestring'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(multilinestring);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.MultiLineString", "MultiLineString GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "y coord correct");
t.eq(data[0].geometry.components[0].components.length, 2, "length correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "y coord correct");
}
function test_Format_GML_read_polygon_with_holes_geom_yx(t) {
t.plan(12);
var polygon_with_holes = shell_start + geoms_yx['polygon_with_holes'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(polygon_with_holes);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Polygon GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 1, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 2, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 4, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 5, "second y coord correct");
t.eq(data[0].geometry.components[0].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components[1].components[0].x, 11, "first x coord correct");
t.eq(data[0].geometry.components[1].components[0].y, 12, "first y coord correct");
t.eq(data[0].geometry.components[1].components[1].x, 14, "second x coord correct");
t.eq(data[0].geometry.components[1].components[1].y, 15, "second y coord correct");
t.eq(data[0].geometry.components[1].components.length, 4, "coords length correct");
t.eq(data[0].geometry.components.length, 2, "rings length correct");
}
function test_Format_GML_read_envelope_geom_yx(t) {
t.plan(13);
var envelope = shell_start + geoms_yx['envelope'] + shell_end;
var parser = new OpenLayers.Format.GML({'xy':false});
data = parser.read(envelope);
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Envelope GML returns correct classname");
t.eq(data[0].geometry.components[0].components[0].x, 0, "first x coord correct");
t.eq(data[0].geometry.components[0].components[0].y, 1, "first y coord correct");
t.eq(data[0].geometry.components[0].components[1].x, 20, "second x coord correct");
t.eq(data[0].geometry.components[0].components[1].y, 1, "second y coord correct");
t.eq(data[0].geometry.components[0].components[2].x, 20, "third x coord correct");
t.eq(data[0].geometry.components[0].components[2].y, 21, "third y coord correct");
t.eq(data[0].geometry.components[0].components[3].x, 0, "fouth x coord correct");
t.eq(data[0].geometry.components[0].components[3].y, 21, "fourth y coord correct");
t.eq(data[0].geometry.components[0].components[4].x, 0, "fifth x coord correct");
t.eq(data[0].geometry.components[0].components[4].y, 1, "fifth y coord correct");
t.eq(data[0].geometry.components[0].components.length, 5, "coords length correct");
t.eq(data[0].geometry.components.length, 1, "rings length correct");
}
function test_Format_GML_write_geoms_yx(t) {
t.plan(5);
var parser = new OpenLayers.Format.GML({'xy':false});
var point_xy = shell_start + serialize_geoms['point'] + shell_end;
var point = shell_start + serialize_geoms_yx['point'] + shell_end;
data = parser.read(point);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, point_xy, "Point geometry round trips correctly.");
var linestring_xy = shell_start + serialize_geoms['linestring'] + shell_end;
var linestring = shell_start + serialize_geoms_yx['linestring'] + shell_end;
data = parser.read(linestring);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, linestring_xy, "Line geometry round trips correctly.");
var polygon_xy = shell_start + serialize_geoms['polygon'] + shell_end;
var polygon = shell_start + serialize_geoms_yx['polygon'] + shell_end;
data = parser.read(polygon);
var output = parser.write(data);
output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, polygon_xy, "Poly geometry round trips correctly.");
var multipoint_xy = shell_start + serialize_geoms['multipoint'] + shell_end;
var multipoint = shell_start + serialize_geoms_yx['multipoint'] + shell_end;
data = parser.read(multipoint);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, multipoint_xy, "MultiPoint geometry round trips correctly.");
var multilinestring_xy = shell_start + serialize_geoms['multilinestring'] + shell_end;
var multilinestring = shell_start + serialize_geoms_yx['multilinestring'] + shell_end;
data = parser.read(multilinestring);
var output = parser.write(data);
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, multilinestring_xy, "MultiLine geometry round trips correctly.");
}
function test_buildGeometryNode_bounds(t) {
t.plan(1);
var parser = new OpenLayers.Format.GML();
var bounds = new OpenLayers.Bounds(-180, -90, 180, 90);
var output, expect;
// test that bounds are written as gml:Box
var output = parser.buildGeometryNode(bounds);
var expect = '<gml:Box xmlns:gml="http://www.opengis.net/gml"><gml:coordinates decimal="." cs="," ts=" ">-180,-90 180,90</gml:coordinates></gml:Box>';
t.xml_eq(output, expect, "[xy true] Bounds correctly written as gml:Box");
}
var test_content = ['<?xml version="1.0" encoding="utf-8" ?>\n<ogr:FeatureCollection\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xsi:schemaLocation="http://ogr.maptools.org/ testoutput.xsd"\n xmlns:ogr="http://ogr.maptools.org/"\n xmlns:gml="http://www.opengis.net/gml">\n <gml:boundedBy>\n <gml:Box>\n <gml:coord><gml:X>-1254041.389711702</gml:X><gml:Y>250906.9515983529</gml:Y></gml:coord>\n <gml:coord><gml:X>-634517.1199908922</gml:X><gml:Y>762236.2940800377</gml:Y></gml:coord>\n </gml:Box>\n </gml:boundedBy> \n <gml:featureMember>\n <ogr:states fid="F0">\n <ogr:geometryProperty><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>-634517.11999089224,691849.77929356066,0 -653761.64509297756,471181.53429472551,0 -673343.60852865304,250906.9515983529,0 -1088825.734430399,299284.85108220269,0 -1254041.3897117018,324729.27754874947,0 -1235750.4212498858,434167.33911316615,0 -1190777.7803201093,704392.96327195223,0 -1181607.835811228,762236.29408003774,0 -634517.11999089224,691849.77929356066,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>\n <ogr:NAME>WY</ogr:NAME>\n <ogr:EMPTYATTR/><ogr:LONGNAME><![CDATA[Wyoming]]></ogr:LONGNAME>\n </ogr:states>\n </gml:featureMember>\n</ogr:FeatureCollection>\n',
'<wfs:FeatureCollection' +
' xmlns:fs="http://example.com/featureserver"' +
' xmlns:wfs="http://www.opengis.net/wfs"' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:ogc="http://www.opengis.net/ogc"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengeospatial.net//wfs/1.0.0/WFS-basic.xsd">' +
' ' +
'' +
' <gml:featureMember>' +
' \n<fs:scribble fid="221">' +
' <fs:geometry>' +
' <gml:Polygon>' +
' ' +
' <gml:outerBoundaryIs><gml:LinearRing>' +
' <gml:coordinates>149.105072021,-35.1816558838 149.100608826,-35.1844024658 149.098892212,-35.1898956299 149.105072021,-35.1816558838</gml:coordinates>' +
' </gml:LinearRing></gml:outerBoundaryIs>' +
' ' +
' </gml:Polygon>' +
' </fs:geometry>' +
' <fs:title>random test features</fs:title>' +
' </fs:scribble>' +
'</gml:featureMember> ' +
' <gml:featureMember><fs:scribble fid="8"> <fs:geometry> <gml:Point><gml:coordinates>-81.38671875,27.0703125</gml:coordinates></gml:Point> </fs:geometry> ' +
' <fs:down>south</fs:down><fs:title>Florida</fs:title> </fs:scribble></gml:featureMember>' +
'</wfs:FeatureCollection>'
];
var shell_start = '<wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs"><gml:featureMember xmlns:gml="http://www.opengis.net/gml"><feature:features xmlns:feature="http://mapserver.gis.umn.edu/mapserver" fid="221"><feature:geometry>';
if (OpenLayers.Util.getBrowserName() == "opera") {
shell_start = '<wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs"><gml:featureMember xmlns:gml="http://www.opengis.net/gml"><feature:features fid="221" xmlns:feature="http://mapserver.gis.umn.edu/mapserver"><feature:geometry>';
}
var shell_end = '</feature:geometry></feature:features></gml:featureMember></wfs:FeatureCollection>';
var serialize_geoms = {
'point': '<gml:Point><gml:coordinates decimal="." cs="," ts=" ">1,2</gml:coordinates></gml:Point>',
'linestring': '<gml:LineString><gml:coordinates decimal="." cs="," ts=" ">1,2 4,5</gml:coordinates></gml:LineString>',
'polygon': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates decimal="." cs="," ts=" ">1,2 4,5 3,6 1,2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>',
'multipoint': '<gml:MultiPoint><gml:pointMember><gml:Point><gml:coordinates decimal="." cs="," ts=" ">1,2</gml:coordinates></gml:Point></gml:pointMember><gml:pointMember><gml:Point><gml:coordinates decimal="." cs="," ts=" ">4,5</gml:coordinates></gml:Point></gml:pointMember></gml:MultiPoint>',
'multilinestring': '<gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates decimal="." cs="," ts=" ">1,2 4,5</gml:coordinates></gml:LineString></gml:lineStringMember><gml:lineStringMember><gml:LineString><gml:coordinates decimal="." cs="," ts=" ">11,12 14,15</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString>'
};
var geoms = {
'point': '<gml:Point><gml:coordinates>1,2,3</gml:coordinates></gml:Point>',
'linestring': '<gml:LineString><gml:coordinates>1,2,3 4,5,6</gml:coordinates></gml:LineString>',
'polygon': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>1,2 4,5 3,6 1,2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>',
'polygon_with_holes': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>1,2 4,5 3,6 1,2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs><gml:innerBoundaryIs><gml:LinearRing><gml:coordinates>11,12 14,15 13,16 11,12</gml:coordinates></gml:LinearRing></gml:innerBoundaryIs></gml:Polygon>',
'multipoint': '<gml:MultiPoint><gml:Point><gml:coordinates>1,2,3</gml:coordinates></gml:Point><gml:Point><gml:coordinates>4,5,6</gml:coordinates></gml:Point></gml:MultiPoint>',
'multilinestring': '<gml:MultiLineString><gml:LineString><gml:coordinates>1,2,3 4,5,6</gml:coordinates></gml:LineString><gml:LineString><gml:coordinates>11,12,13 14,15,16</gml:coordinates></gml:LineString></gml:MultiLineString>',
'envelope': '<gml:Envelope><gml:lowerCorner>0 1</gml:lowerCorner><gml:upperCorner>20 21</gml:upperCorner></gml:Envelope>' // ,
// 'multipolygon_with_holes': '<gml:MultiPolygon><gml:Polygon><gml:outerBoundaryIs>1,2 4,5 3,6 1,2</gml:outerBoundaryIs><gml:innerBoundaryIs>11,12 14,15 13,16 11,12</gml:innerBoundaryIs></gml:Polygon><gml:Polygon><gml:outerBoundaryIs>101,102 104,105 103,106 101,102</gml:outerBoundaryIs><gml:innerBoundaryIs>111,112 114,115 113,116 111,112</gml:innerBoundaryIs></gml:Polygon></gml:MultiPolygon>'
};
//
// The following data has the (x y) reordered to (y x), in 3 dimensions it goes from (x y z) to (y x z)
//
var serialize_geoms_yx = {
'point': '<gml:Point><gml:coordinates decimal="." cs="," ts=" ">2,1</gml:coordinates></gml:Point>',
'linestring': '<gml:LineString><gml:coordinates decimal="." cs="," ts=" ">2,1 5,4</gml:coordinates></gml:LineString>',
'polygon': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates decimal="." cs="," ts=" ">2,1 5,4 6,3 2,1</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>',
'multipoint': '<gml:MultiPoint><gml:pointMember><gml:Point><gml:coordinates decimal="." cs="," ts=" ">2,1</gml:coordinates></gml:Point></gml:pointMember><gml:pointMember><gml:Point><gml:coordinates decimal="." cs="," ts=" ">5,4</gml:coordinates></gml:Point></gml:pointMember></gml:MultiPoint>',
'multilinestring': '<gml:MultiLineString><gml:lineStringMember><gml:LineString><gml:coordinates decimal="." cs="," ts=" ">2,1 5,4</gml:coordinates></gml:LineString></gml:lineStringMember><gml:lineStringMember><gml:LineString><gml:coordinates decimal="." cs="," ts=" ">12,11 15,14</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString>'
};
var geoms_yx = {
'point': '<gml:Point><gml:coordinates>2,1,3</gml:coordinates></gml:Point>',
'linestring': '<gml:LineString><gml:coordinates>2,1,3 5,4,6</gml:coordinates></gml:LineString>',
'polygon': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>2,1 5,4 6,3 2,1</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>',
'polygon_with_holes': '<gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>2,1 5,4 6,3 2,1</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs><gml:innerBoundaryIs><gml:LinearRing><gml:coordinates>12,11 15,14 16,13 12,11</gml:coordinates></gml:LinearRing></gml:innerBoundaryIs></gml:Polygon>',
'multipoint': '<gml:MultiPoint><gml:Point><gml:coordinates>2,1,3</gml:coordinates></gml:Point><gml:Point><gml:coordinates>5,4,6</gml:coordinates></gml:Point></gml:MultiPoint>',
'multilinestring': '<gml:MultiLineString><gml:LineString><gml:coordinates>2,1,3 5,4,6</gml:coordinates></gml:LineString><gml:LineString><gml:coordinates>12,11,13 15,14,16</gml:coordinates></gml:LineString></gml:MultiLineString>',
'envelope': '<gml:Envelope><gml:lowerCorner>1 0</gml:lowerCorner><gml:upperCorner>21 20</gml:upperCorner></gml:Envelope>'
};
</script>
</head>
<body>
</body>
</html>

View File

@ -1,39 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var gpx_data = '<?xml version="1.0" encoding="ISO-8859-1"?><gpx version="1.1" creator="Memory-Map 5.1.3.715 http://www.memory-map.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"><wpt lat="51.3697845627" lon="-0.1853562259"><name>Mark</name><sym><![CDATA[Flag]]></sym><type><![CDATA[Marks]]></type></wpt><rte><name><![CDATA[Route8]]></name><type><![CDATA[Route]]></type><rtept lat="51.3761803674" lon="-0.1829991904"><name><![CDATA[WP0801]]></name><sym><![CDATA[Dot]]></sym><type><![CDATA[Waypoints]]></type></rtept><rtept lat="51.3697894659" lon="-0.1758887005"><name><![CDATA[WP0802]]></name><sym><![CDATA[Dot]]></sym><type><![CDATA[Waypoints]]></type></rtept><rtept lat="51.3639790884" lon="-0.1833202965"><name><![CDATA[WP0803]]></name><sym><![CDATA[Dot]]></sym><type><![CDATA[Waypoints]]></type></rtept><rtept lat="51.3567607069" lon="-0.1751119509"><name><![CDATA[WP0804]]></name><sym><![CDATA[Dot]]></sym><type><![CDATA[Waypoints]]></type></rtept></rte><trk><name><![CDATA[Track]]></name><type><![CDATA[Track]]></type><trkseg><trkpt lat="51.3768216433" lon="-0.1721292044"></trkpt><trkpt lat="51.3708337670" lon="-0.1649230916"></trkpt><trkpt lat="51.3644368725" lon="-0.1736741378"></trkpt><trkpt lat="51.3576354272" lon="-0.1662595250"></trkpt></trkseg></trk></gpx>';
function test_Format_GPX_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.GPX(options);
t.ok(format instanceof OpenLayers.Format.GPX,
"new OpenLayers.Format.GPX returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_GPX_read(t) {
t.plan(4);
var f = new OpenLayers.Format.GPX();
var features = f.read(gpx_data);
t.eq(features.length, 3, "Number of features read is correct");
t.eq(features[2].geometry.toString(), "POINT(-0.1853562259 51.3697845627)", "waypoint feature correctly created");
t.eq(features[0].geometry.toString(), "LINESTRING(-0.1721292044 51.3768216433,-0.1649230916 51.370833767,-0.1736741378 51.3644368725,-0.166259525 51.3576354272)", "track feature correctly created");
t.eq(features[1].geometry.toString(), "LINESTRING(-0.1829991904 51.3761803674,-0.1758887005 51.3697894659,-0.1833202965 51.3639790884,-0.1751119509 51.3567607069)", "route feature correctly created");
}
function test_format_GPX_read_attributes(t) {
t.plan(2);
var f = new OpenLayers.Format.GPX();
var features = f.read(gpx_data);
t.eq(features[2].attributes['name'], "Mark", "Text attribute node read correctly.");
t.eq(features[2].attributes['sym'], "Flag", "CDATA attribute node read correctly.");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,416 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var poly_content = '{"type": "FeatureCollection", "features": [{"geometry": {"type": "Polygon", "coordinates": [[[-131.484375, -5.9765625], [-112.5, -58.0078125], [-32.34375, -50.2734375], [-114.609375, 52.3828125], [-167.34375, -35.5078125], [-146.953125, -57.3046875], [-139.921875, -34.1015625], [-131.484375, -5.9765625]]]}, "type": "Feature", "id": 562, "properties": {"strokeColor": "red", "title": "Feature 2", "author": "Your Name Here"}}]}';
var null_geom_feature = '{"type":"Feature","id":573,"properties":{"strokeColor":"blue","title":"Feature 5","author":"Your Name Here"},"geometry":null}';
var point_feature = '{"geometry": {"type": "Point", "coordinates": [94.21875, 72.94921875]}, "type": "Feature", "id": 573, "properties": {"strokeColor": "blue", "title": "Feature 5", "author": "Your Name Here"}}';
var line_feature = '{"type": "FeatureCollection", "features": [{"geometry": {"type": "LineString", "coordinates": [[-27.0703125, 59.4140625], [-77.6953125, 20.7421875], [30.5859375, -36.2109375], [67.1484375, 34.8046875]]}, "type": "Feature", "id": 559, "properties": {"strokeColor": "red", "title": "Feature 1", "author": "Your Name Here"}}]}';
var multiple_features = '{"type": "FeatureCollection", "features": [{"geometry": {"type": "Point", "coordinates": [-91.0546875, 43.9453125]}, "type": "Feature", "id": 577, "properties": {"strokeColor": "red", "title": "Feature 2", "image": "foo.gif", "author": "Your Name Here"}}, {"geometry": {"type": "LineString", "coordinates": [[91.40625, -1.40625], [116.015625, -42.890625], [153.28125, -28.125], [108.984375, 11.25], [75.234375, 8.4375], [76.640625, 9.140625], [67.5, -36.5625], [67.5, -35.859375]]}, "type": "Feature", "id": 576, "properties": {"strokeColor": "red", "title": "Feature 1", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [139.5703125, 57.48046875]}, "type": "Feature", "id": 575, "properties": {"strokeColor": "blue", "title": "Feature 7", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [107.2265625, 82.44140625]}, "type": "Feature", "id": 574, "properties": {"strokeColor": "blue", "title": "Feature 6", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [94.21875, 72.94921875]}, "type": "Feature", "id": 573, "properties": {"strokeColor": "blue", "title": "Feature 5", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [116.3671875, 61.69921875]}, "type": "Feature", "id": 572, "properties": {"strokeColor": "blue", "title": "Feature 4", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [145.8984375, 73.65234375]}, "type": "Feature", "id": 571, "properties": {"strokeColor": "blue", "title": "Feature 3", "author": "Your Name Here"}}, {"geometry": {"type": "Polygon", "coordinates": [[[32.34375, 52.20703125], [87.1875, 70.13671875], [122.6953125, 37.44140625], [75.234375, 42.36328125], [40.078125, 42.36328125], [28.828125, 48.33984375], [18.6328125, 56.77734375], [23.203125, 65.56640625], [32.34375, 52.20703125]]]}, "type": "Feature", "id": 570, "properties": {"strokeColor": "blue", "title": "Feature 2", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [62.578125, -53.4375]}, "type": "Feature", "id": 569, "properties": {"strokeColor": "red", "title": "Feature 3", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [121.640625, 16.875]}, "type": "Feature", "id": 568, "properties": {"strokeColor": "red", "title": "Feature 6", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [135.703125, 8.4375]}, "type": "Feature", "id": 567, "properties": {"strokeColor": "red", "title": "Feature 4", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [137.109375, 48.515625]}, "type": "Feature", "id": 566, "properties": {"strokeColor": "red", "title": "Feature 274", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [0, 5]}, "type": "Feature", "id": 565, "properties": {}}, {"geometry": {"type": "Point", "coordinates": [0, 5]}, "type": "Feature", "id": 564, "properties": {}}, {"geometry": {"type": "Point", "coordinates": [0, 5]}, "type": "Feature", "id": 563, "properties": {}}, {"geometry": {"type": "Polygon", "coordinates": [[[-131.484375, -5.9765625], [-112.5, -58.0078125], [-32.34375, -50.2734375], [-114.609375, 52.3828125], [-167.34375, -35.5078125], [-146.953125, -57.3046875], [-139.921875, -34.1015625], [-131.484375, -5.9765625]]]}, "type": "Feature", "id": 562, "properties": {"strokeColor": "red", "title": "Feature 2", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [48.8671875, -15.8203125]}, "type": "Feature", "id": 560, "properties": {"strokeColor": "red", "title": "Feature 2", "author": "Your Name Here"}}, {"geometry": {"type": "LineString", "coordinates": [[-27.0703125, 59.4140625], [-77.6953125, 20.7421875], [30.5859375, -36.2109375], [67.1484375, 34.8046875]]}, "type": "Feature", "id": 559, "properties": {"strokeColor": "red", "title": "Feature 1", "author": "Your Name Here"}}, {"geometry": {"type": "Point", "coordinates": [12.65625, 16.5234375]}, "type": "Feature", "id": 558, "properties": {"styleUrl": "#allstyle", "title": "Feature 1", "strokeColor": "red", "author": "Your Name Here"}}]}';
var parser = new OpenLayers.Format.GeoJSON();
var data;
function test_Format_GeoJSON_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.GeoJSON(options);
t.ok(format instanceof OpenLayers.Format.GeoJSON,
"new OpenLayers.Format.GeoJSON returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_GeoJSON_null_geom(t) {
t.plan(2);
var f = new OpenLayers.Format.GeoJSON();
var fs = f.read(null_geom_feature);
t.ok(fs[0].geometry == null, "Reading feature with null geom works okay");
t.eq(f.write(fs[0]), null_geom_feature, "round trip null okay");
}
function test_Format_GeoJSON_valid_type(t) {
t.plan(14);
OpenLayers.Console.error = function(error) { window.global_error = error;};
var types = ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "Box", "GeometryCollection"];
for (var i = 0; i < types.length; i++) {
t.ok(parser.isValidType({'type':types[i]}, "Geometry"), "Geometry with type " + types[i] + " is valid");
}
t.ok(!parser.isValidType({'type':"foo"}, "Geometry"), "Geometry with type foo is not valid");
t.eq(global_error, "Unsupported geometry type: foo", "error message set correctly for 'foo' geom.");
t.ok(parser.isValidType({}, "FeatureCollection"), "Feature collection type is always valid");
t.ok(parser.isValidType({'type':"GeometryCollection"}, "GeometryCollection"), "Geometry Collection type is valid");
t.ok(!parser.isValidType({'type':"GeometryCollection2"}, "GeometryCollection"), "Geometry Collection 2 type is invalid");
t.eq(global_error, "Cannot convert types from GeometryCollection2 to GeometryCollection", "error message set correctly for bad geometrycollection type");
}
function test_Format_GeoJSON_point(t) {
t.plan(3);
data = parser.read(point_feature);
t.eq(data[0].fid, 573, "Fid is correct on point feature");
t.eq(data[0].geometry.x, 94.21875, 'Reading point feature gives correct x');
data = parser.read(point_feature, "Feature");
t.eq(data.fid, 573, 'Reading point feature with type gives feature instead of array of features ');
}
function test_Format_GeoJSON_line(t) {
t.plan(5);
data = parser.read(line_feature);
t.eq(data[0].fid, 559, "Fid is correct on line feature");
t.eq(data[0].geometry.components.length, 4, 'Reading line feature gives correct length');
t.eq(data[0].geometry.CLASS_NAME, 'OpenLayers.Geometry.LineString', 'Reading line feature gives correct class');
t.eq(data[0].geometry.components[0].x, -27.0703125, 'Reading line feature gives correct x');
t.eq(data[0].geometry.components[0].y, 59.4140625, 'Reading line feature gives correct y');
}
function test_Format_GeoJSON_poly(t) {
t.plan(2);
data = parser.read(poly_content);
t.eq(data[0].fid, 562, "poly id is correct");
t.eq(data[0].geometry.components[0].components.length, 8,
'Reading polygon first ring on feature from featurecollection gives correct length');
}
function test_Format_GeoJSON_multipoint(t) {
t.plan(5);
var multipoint = {
"type": "MultiPoint",
"coordinates": [
[100.0, 0.0], [101.0, 1.0]
]
};
data = parser.read(multipoint, "Geometry");
t.eq(data.components.length, 2,
"Right number of components");
t.eq(data.components[0].CLASS_NAME, "OpenLayers.Geometry.Point", "First component is point");
t.eq(data.components[1].CLASS_NAME, "OpenLayers.Geometry.Point", "Second component is point");
t.eq(data.components[1].x, 101, "x of second component is right");
t.eq(data.components[1].y, 1, "y of second component is right");
}
function test_Format_GeoJSON_multiline(t) {
t.plan(3);
var multiline = {
"type": "MultiLineString",
"coordinates": [
[ [100.0, 0.0], [101.0, 1.0] ],
[ [102.0, 2.0], [103.0, 3.0] ]
]
};
data = parser.read(multiline, "Geometry");
t.eq(data.CLASS_NAME, "OpenLayers.Geometry.MultiLineString", "Correct class retrieved");
t.eq(data.components[0].components[0].CLASS_NAME, "OpenLayers.Geometry.Point", "correct type of components");
t.eq(data.components[0].CLASS_NAME, "OpenLayers.Geometry.LineString", "correct type of components");
}
function test_Format_GeoJSON_multipol(t) {
t.plan(2);
var multipol = {
"type": "MultiPolygon",
"coordinates": [
[
[ [102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ]
],
[
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
[ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]
]
]
};
OpenLayers.Console.error = function(error) { window.global_error = error; };
data = parser.read(multipol, "Geometry");
t.eq(data.CLASS_NAME, "OpenLayers.Geometry.MultiPolygon", "Correct class retrieved");
t.eq(data.components[1].components[0].components[0].CLASS_NAME, "OpenLayers.Geometry.Point", "correct type of components");
}
function test_Format_GeoJSON_box(t) {
t.plan(6);
var box = {
"type": "Box",
"coordinates": [[100.0, 0.0], [101.0, 1.0]]
};
var poly = parser.read(box, "Geometry");
t.eq(poly.CLASS_NAME, "OpenLayers.Geometry.Polygon", "Box creates polygon");
t.eq(poly.components[0].components[1].x, 101, "x of lower right is correct");
t.eq(poly.components[0].components[1].y, 0, "y of lower right is correct");
t.eq(poly.components[0].components[3].x, 100, "x of upper left is correct");
t.eq(poly.components[0].components[3].y, 1, "y of upper left is correct");
box = parser.write(poly );
t.ok(box.search("Polygon") != -1 , "Serializes back to polygon");
}
// This test is from the geom_collection example on geojson spec.
function test_Format_GeoJSON_collection(t) {
t.plan(12);
var geomcol = {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [100.0, 0.0]
},
{
"type": "LineString",
"coordinates": [
[101.0, 0.0], [102.0, 1.0]
]
}
]
};
data = parser.read(geomcol, "Geometry");
t.eq(data.CLASS_NAME, "OpenLayers.Geometry.Collection",
"GeometryCollection deserialized into geometry.collection");
t.eq(data.components[0].CLASS_NAME, "OpenLayers.Geometry.Point",
"First geom is correct type");
t.eq(data.components[0].x, 100,
"First geom in geom collection has correct x");
t.eq(data.components[0].y, 0,
"First geom in geom collection has correct x");
t.eq(data.components[1].CLASS_NAME, "OpenLayers.Geometry.LineString",
"Second geom in geom collection is point linestring");
t.eq(data.components[1].components.length, 2,
"linestring is correct length");
t.eq(data.components[1].components[1].x, 102,
"linestring is correct x end");
t.eq(data.components[1].components[1].y, 1,
"linestring is correct y end");
data = parser.read(geomcol, "FeatureCollection");
t.eq(data[0].CLASS_NAME, "OpenLayers.Feature.Vector",
"GeometryCollection can be read in as a feature collection");
t.eq(data[0].geometry.CLASS_NAME, "OpenLayers.Geometry.Collection",
"feature contains the correct geometry type");
var feature = {
"type": "Feature",
"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [100.0, 0.0]
},
{
"type": "LineString",
"coordinates": [
[101.0, 0.0], [102.0, 1.0]
]
}
]
},
"properties": {
"prop0": "value0",
"prop1": "value1"
}
};
data = parser.read(feature, "Feature");
t.eq(data.geometry.CLASS_NAME, "OpenLayers.Geometry.Collection", "Geometry of feature is a collection");
var l = new OpenLayers.Layer.Vector();
l.addFeatures(data);
t.ok(true, "adding a feature with geomcollection to layer doesn't cause error.");
}
function test_Format_GeoJSON_multipleFeatures(t) {
t.plan(2);
var feats = parser.read(multiple_features);
t.eq(feats.length, 19, "parsing a feature collection returns the correct number of features.");
var types = {'Point':0, 'LineString':0, 'Polygon':0};
for(var i = 0; i < feats.length; i++) {
var type = feats[i].geometry.CLASS_NAME.replace("OpenLayers.Geometry.", "");
types[type]++;
}
t.eq(types, {'Point':15, 'Polygon': 2, 'LineString':2}, "Correct number of each type");
}
function test_Format_GeoJSON_writeWithCRS(t) {
t.plan(2);
var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,2));
feature.fid = 0;
var output = '{"type":"Feature","id":0,"properties":{},"geometry":{"type":"Point","coordinates":[1,2]},"crs":{"type":"OGC","properties":{"urn":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}';
var layer = new OpenLayers.Layer.Vector();
layer.projection = "EPSG:4326";
feature.layer = layer;
var parser = new OpenLayers.Format.GeoJSON();
var test_out = parser.write(feature);
t.eq(test_out, output, "Output is equal for vector with layer in EPSG:4326 ");
feature.layer.projection = "EPSG:2805";
output = '{"type":"Feature","id":0,"properties":{},"geometry":{"type":"Point","coordinates":[1,2]},"crs":{"type":"EPSG","properties":{"code":2805}}}';
test_out = parser.write(feature);
t.eq(test_out, output, "Output is equal for vector with point");
}
function test_Format_GeoJSON_write(t) {
t.plan(10);
var line_object = {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "LineString",
"coordinates": [
[-27.0703125, 59.4140625],
[-77.6953125, 20.7421875],
[30.5859375, -36.2109375],
[67.1484375, 34.8046875]
]
},
"type": "Feature",
"id": 559,
"properties": {
"strokeColor": "red",
"title": "Feature 1",
"author": "Your Name Here"
}
}
]
};
data = parser.read(line_object);
out = parser.write(data);
serialized = '{"type":"FeatureCollection","features":[{"type":"Feature","id":559,"properties":{"strokeColor":"red","title":"Feature 1","author":"Your Name Here"},"geometry":{"type":"LineString","coordinates":[[-27.0703125,59.4140625],[-77.6953125,20.7421875],[30.5859375,-36.2109375],[67.1484375,34.8046875]]}}]}';
t.eq(out, serialized, "input and output on line collections are the same");
var serialize_tests = [
[
new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,2)),
'{"type":"Feature","id":0,"properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}'
],
[
new OpenLayers.Geometry.Point(1,2),
'{"type":"Point","coordinates":[1,2]}'
],
[
new OpenLayers.Geometry.MultiPoint([
new OpenLayers.Geometry.Point(1,2)
]),
'{"type":"MultiPoint","coordinates":[[1,2]]}'
],
[
new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(1,2),
new OpenLayers.Geometry.Point(3,4)
]),
'{"type":"LineString","coordinates":[[1,2],[3,4]]}'
],
[
new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(1,2),
new OpenLayers.Geometry.Point(3,4),
new OpenLayers.Geometry.Point(5,6)
])
]),
'{"type":"Polygon","coordinates":[[[1,2],[3,4],[5,6],[1,2]]]}'
],
[
new OpenLayers.Geometry.Collection([
new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(1,2),
new OpenLayers.Geometry.Point(3,4),
new OpenLayers.Geometry.Point(5,6)
])
]),
new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(1,2),
new OpenLayers.Geometry.Point(3,4)
]),
new OpenLayers.Geometry.Point(1,2)
]),
'{"type":"GeometryCollection","geometries":[{"type":"Polygon","coordinates":[[[1,2],[3,4],[5,6],[1,2]]]},{"type":"LineString","coordinates":[[1,2],[3,4]]},{"type":"Point","coordinates":[1,2]}]}'
]
];
serialize_tests[0][0].fid = 0;
multiline = new OpenLayers.Geometry.MultiLineString([serialize_tests[3][0], serialize_tests[3][0]]);
serialize_tests.push([multiline, '{"type":"MultiLineString","coordinates":[[[1,2],[3,4]],[[1,2],[3,4]]]}']);
multipolygon = new OpenLayers.Geometry.MultiPolygon([serialize_tests[4][0], serialize_tests[4][0]]);
serialize_tests.push([multipolygon, '{"type":"MultiPolygon","coordinates":[[[[1,2],[3,4],[5,6],[1,2]]],[[[1,2],[3,4],[5,6],[1,2]]]]}']);
serialize_tests.push([ [ serialize_tests[0][0] ], '{"type":"FeatureCollection","features":[{"type":"Feature","id":0,"properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}]}' ]);
for (var i = 0; i < serialize_tests.length; i++) {
var input = serialize_tests[i][0];
var output = serialize_tests[i][1];
test_out = parser.write(input);
t.eq(test_out, output, "Serializing " + input.toString() + " saved correctly.");
}
}
function test_Format_GeoJSON_read_object(t) {
t.plan(1);
var line_object = {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "LineString",
"coordinates": [
[-27.0703125, 59.4140625],
[-77.6953125, 20.7421875],
[30.5859375, -36.2109375],
[67.1484375, 34.8046875]
]
},
"type": "Feature",
"id": 559,
"properties": {
"strokeColor": "red",
"title": "Feature 1",
"author": "Your Name Here"
}
}
]
};
data = parser.read(line_object);
t.eq(data[0].fid, 559, "Can read data from an object correctly.");
}
function test_Format_GeoJSON_read_attributes(t) {
t.plan(3);
var parser = new OpenLayers.Format.GeoJSON();
data = parser.read(line_feature);
t.eq(data[0].attributes['strokeColor'], 'red', 'read strokeColor attribute properly');
t.eq(data[0].attributes['title'], 'Feature 1', 'read title attribute properly');
t.eq(data[0].attributes['author'], 'Your Name Here', 'read author attribute properly');
}
function test_read_bbox(t) {
t.plan(8);
var f;
parser = new OpenLayers.Format.GeoJSON();
// 4 tests
f = '{"geometry": {"type": "Point", "coordinates": [94.21875, 72.94921875], "bbox": [94.21875, 72.94921875, 94.21875, 72.94921875]}, "type": "Feature", "id": 573, "properties": {}, "bbox": [95.0, 73.0]}';
data = parser.read(f);
t.eq(data[0].bounds.left, 94.21875, "read left bound is correct");
t.eq(data[0].bounds.bottom, 72.94921875, "read bottom left bound is correct");
t.eq(data[0].bounds.right, 94.21875, "read right bound is correct");
t.eq(data[0].bounds.top, 72.94921875, "read top left bound is correct");
// 4 tests
f = '{"geometry": {"type": "Point", "coordinates": [94.21875, 72.94921875]}, "type": "Feature", "id": 573, "properties": {}, "bbox": [95.0, 73.0, 96.0, 74.0]}';
data = parser.read(f);
t.eq(data[0].bounds.left, 95.0, "read left bound is correct");
t.eq(data[0].bounds.bottom, 73.0, "read bottom left bound is correct");
t.eq(data[0].bounds.right, 96.0, "read right bound is correct");
t.eq(data[0].bounds.top, 74.0, "read top left bound is correct");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,105 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Format_GeoRSS_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.GeoRSS(options);
t.ok(format instanceof OpenLayers.Format.GeoRSS,
"new OpenLayers.Format.GeoRSS returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_GeoRSS_serializeline(t) {
t.plan(1);
var parser = new OpenLayers.Format.GeoRSS();
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var point2 = new OpenLayers.Geometry.Point(-112.04, 45.68);
var l = new OpenLayers.Geometry.LineString([point, point2]);
var f = new OpenLayers.Feature.Vector(l);
var data = parser.write([f]);
t.xml_eq(data, '<rss xmlns="http://backend.userland.com/rss2"><item><title></title><description></description><georss:line xmlns:georss="http://www.georss.org/georss">45.68 -111.04 45.68 -112.04</georss:line></item></rss>', 'GeoRSS serializes a line correctly');
}
function test_Format_GeoRSS_box(t) {
t.plan(4);
var xml = '<rss xmlns="http://backend.userland.com/rss2"><item><title></title><description></description><georss:box xmlns:georss="http://www.georss.org/georss">45.68 -112.04 47.68 -111.04</georss:box></item></rss>';
var format = new OpenLayers.Format.GeoRSS();
var features = format.read(xml);
t.eq(features.length, 1, "one feature returned");
t.eq(features[0].geometry.components[0].components.length, 5, "polygon returned");
t.eq(features[0].geometry.components[0].components[0].x, -112.04, "polygon returned with correct first x");
t.eq(features[0].geometry.components[0].components[0].y, 45.68, "polygon returned with correct first y");
}
function test_Format_GeoRSS_w3cgeo(t) {
t.plan(2);
var parser = new OpenLayers.Format.GeoRSS();
var data = parser.read('<rss xmlns="http://backend.userland.com/rss2" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"><item><geo:long>-1</geo:long><geo:lat>1</geo:lat></item></rss>');
t.eq(data[0].geometry.x, -1, "w3c geo x read correctly");
t.eq(data[0].geometry.y, 1, "w3c geo y read correctly");
}
function test_Format_GeoRSS_reproject_null(t) {
t.plan(1);
var parser = new OpenLayers.Format.GeoRSS({'internalProjection':new OpenLayers.Projection("EPSG:4326"), 'externalProjection': new OpenLayers.Projection("EPSG:4326")});
var data = parser.read('<rss xmlns="http://backend.userland.com/rss2" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"><item></item></rss>');
t.eq(data.length, 1, "Parsing items with null geometry and reprojection doesn't fail");
}
function test_Format_GeoRSS_roundtrip(t) {
t.plan(input.length);
var parser = new OpenLayers.Format.GeoRSS();
for(var i=0; i < input.length; i++) {
var feed = shell_start+input[i]+shell_end;
var data = parser.read(feed);
var out = parser.write(data);
var expected_result = output[i];
t.xml_eq(out, expected_result, "Output gave expected value");
}
}
function test_Format_GeoRSS_gml_roundtrip(t) {
t.plan(input_gml.length);
var parser = new OpenLayers.Format.GeoRSS();
for(var i=0; i < input_gml.length; i++) {
var feed = shell_start_gml+input_gml[i]+shell_end_gml;
var data = parser.read(feed);
var out = parser.write(data);
var expected_result = output_gml[i];
t.xml_eq(out, expected_result, "Output gave expected value");
}
}
var shell_start = '<feed xmlns="http://www.w3.org/2005/Atom" \n xmlns:georss="http://www.georss.org/georss">\n <title>scribble</title>\n <id>http://featureserver.org/featureserver.cgi/scribble?format=atom</id>\n <author><name>FeatureServer</name></author>\n';
var shell_end = '</feed>';
var input = ['<entry><id>http://featureserver.org/featureserver.cgi/scribble/562.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/562.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:polygon>-5.9765625 -131.484375 -58.0078125 -112.5 -50.2734375 -32.34375 52.3828125 -114.609375 -35.5078125 -167.34375 -57.3046875 -146.953125 -34.1015625 -139.921875 -5.9765625 -131.484375</georss:polygon></entry>',
'<entry><id>http://featureserver.org/featureserver.cgi/scribble/796.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/796.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: 00ccff&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:point>75.5859375 15.46875</georss:point></entry>',
'<entry><id>http://featureserver.org/featureserver.cgi/scribble/794.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/794.atom"/><title>Feature 5</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 5&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:line>28.828125 32.6953125 49.921875 34.8046875 39.375 58.0078125 39.375 58.0078125 40.078125 58.0078125 41.484375 58.0078125 43.59375 58.0078125 45.703125 58.7109375 47.8125 58.7109375 49.21875 58.7109375 51.328125 59.4140625 52.03125 59.4140625 54.140625 60.8203125 56.25 61.5234375 56.25 62.2265625 57.65625 62.2265625 57.65625 62.9296875 58.359375 63.6328125 58.359375 65.0390625 58.359375 65.7421875 59.0625 66.4453125 59.0625 67.1484375 59.0625 68.5546875 59.765625 69.9609375 59.765625 72.0703125 59.765625 73.4765625 59.765625 76.2890625 59.765625 78.3984375 59.765625 79.8046875 59.765625 81.9140625 59.765625 83.3203125 59.0625 84.7265625 59.0625 86.8359375 58.359375 87.5390625 58.359375 88.2421875 56.953125 89.6484375 56.25 91.0546875 54.84375 93.8671875 52.03125 96.6796875 51.328125 98.7890625 50.625 100.1953125 49.21875 102.3046875 48.515625 103.7109375 47.8125 104.4140625 47.109375 105.8203125 46.40625 106.5234375 46.40625 107.9296875 45.703125 109.3359375 45 110.7421875 43.59375 112.8515625 43.59375 114.2578125 43.59375 114.9609375 42.890625 117.0703125 42.890625 117.7734375 42.1875 118.4765625 42.1875 119.1796875 42.1875 119.8828125</georss:line></entry>'
];
var output= ['<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/562.atom</link><georss:polygon xmlns:georss="http://www.georss.org/georss">-5.9765625 -131.484375 -58.0078125 -112.5 -50.2734375 -32.34375 52.3828125 -114.609375 -35.5078125 -167.34375 -57.3046875 -146.953125 -34.1015625 -139.921875 -5.9765625 -131.484375</georss:polygon></item></rss>',
'<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: 00ccff&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/796.atom</link><georss:point xmlns:georss="http://www.georss.org/georss">75.5859375 15.46875</georss:point></item></rss>',
'<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 5</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 5&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/794.atom</link><georss:line xmlns:georss="http://www.georss.org/georss">28.828125 32.6953125 49.921875 34.8046875 39.375 58.0078125 39.375 58.0078125 40.078125 58.0078125 41.484375 58.0078125 43.59375 58.0078125 45.703125 58.7109375 47.8125 58.7109375 49.21875 58.7109375 51.328125 59.4140625 52.03125 59.4140625 54.140625 60.8203125 56.25 61.5234375 56.25 62.2265625 57.65625 62.2265625 57.65625 62.9296875 58.359375 63.6328125 58.359375 65.0390625 58.359375 65.7421875 59.0625 66.4453125 59.0625 67.1484375 59.0625 68.5546875 59.765625 69.9609375 59.765625 72.0703125 59.765625 73.4765625 59.765625 76.2890625 59.765625 78.3984375 59.765625 79.8046875 59.765625 81.9140625 59.765625 83.3203125 59.0625 84.7265625 59.0625 86.8359375 58.359375 87.5390625 58.359375 88.2421875 56.953125 89.6484375 56.25 91.0546875 54.84375 93.8671875 52.03125 96.6796875 51.328125 98.7890625 50.625 100.1953125 49.21875 102.3046875 48.515625 103.7109375 47.8125 104.4140625 47.109375 105.8203125 46.40625 106.5234375 46.40625 107.9296875 45.703125 109.3359375 45 110.7421875 43.59375 112.8515625 43.59375 114.2578125 43.59375 114.9609375 42.890625 117.0703125 42.890625 117.7734375 42.1875 118.4765625 42.1875 119.1796875 42.1875 119.8828125</georss:line></item></rss>'
];
var shell_start_gml = '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:gml="http://www.opengis.net/gml" xmlns:georss="http://www.georss.org/georss"> <title>scribble</title><id>http://featureserver.org/featureserver.cgi/scribble?format=atom</id><author><name>FeatureServer</name></author>';
var shell_end_gml = '</feed>';
var input_gml = ['<entry><id>http://featureserver.org/featureserver.cgi/scribble/111.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/111.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:where><gml:Point><gml:pos>0 10</gml:pos></gml:Point></georss:where></entry>',
'<entry><id>http://featureserver.org/featureserver.cgi/scribble/111.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/111.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:where><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>110,-50 110,-10 155,-10 155,-50 110,-50</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></georss:where></entry>',
'<entry><id>http://featureserver.org/featureserver.cgi/scribble/111.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/111.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:where><gml:LineString><gml:coordinates>0,10 10,20</gml:coordinates></gml:LineString></georss:where></entry>',
'<entry><id>http://featureserver.org/featureserver.cgi/scribble/111.atom</id><link href="http://featureserver.org/featureserver.cgi/scribble/111.atom"/><title>Feature 2</title><content type="html">&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</content><georss:where><gml:Envelope><gml:lowerCorner>0 1</gml:lowerCorner><gml:upperCorner>20 21</gml:upperCorner></gml:Envelope></georss:where></entry>'
];
var output_gml = ['<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/111.atom</link><georss:point xmlns:georss="http://www.georss.org/georss">0 10</georss:point></item></rss>',
'<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/111.atom</link><georss:polygon xmlns:georss="http://www.georss.org/georss">110 -50 110 -10 155 -10 155 -50 110 -50</georss:polygon></item></rss>',
'<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/111.atom</link><georss:line xmlns:georss="http://www.georss.org/georss">0 10 10 20</georss:line></item></rss>',
'<rss xmlns="http://backend.userland.com/rss2"><item><title>Feature 2</title><description>&lt;b&gt;strokeColor&lt;/b&gt;: red&lt;br /&gt;&lt;b&gt;title&lt;/b&gt;: Feature 2&lt;br /&gt;&lt;b&gt;author&lt;/b&gt;: Your Name Here</description><link>http://featureserver.org/featureserver.cgi/scribble/111.atom</link><georss:polygon xmlns:georss="http://www.georss.org/georss">0 1 0 21 20 21 20 1 0 1</georss:polygon></item></rss>'
];
</script>
</head>
<body>
</body>
</html>

View File

@ -1,53 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Format_JSON_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.JSON(options);
t.ok(format instanceof OpenLayers.Format.JSON,
"new OpenLayers.Format.JSON returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_JSON_parser(t) {
t.plan(2);
var format = new OpenLayers.Format.JSON();
var data = format.read('{"a":["b"], "c":1}');
var obj = {"a":["b"], "c":1};
t.eq(obj['a'], data['a'], "element with array parsed correctly.");
t.eq(obj['c'], data['c'], "element with number parsed correctly.");
}
function test_Format_JSON_writer(t) {
t.plan(1);
var format = new OpenLayers.Format.JSON();
var data = format.write({"a":["b"], "c":1});
var obj = '{"a":["b"],"c":1}';
t.eq(data, obj, "writing data to json works.");
}
function test_keepData(t) {
t.plan(2);
var options = {'keepData': true};
var format = new OpenLayers.Format.JSON(options);
format.read('{"a":["b"], "c":1}');
t.ok(format.data != null, 'data property is not null after read with keepData=true');
t.eq(format.data.c,1,'keepData keeps the right data');
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,213 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var test_content = '<kml xmlns="http://earth.google.com/kml/2.0"><Folder><name>OpenLayers export</name><description>Vector geometries from OpenLayers</description><Placemark id="KML.Polygon"><name>OpenLayers.Feature.Vector_344</name><description>A KLM Polygon</description><Polygon><outerBoundaryIs><LinearRing><coordinates>5.001370157823406,49.26855713824488 8.214706453896161,49.630662409673505 8.397385910100951,48.45172350357396 5.001370157823406,49.26855713824488</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark><Placemark id="KML.LineString"><name>OpenLayers.Feature.Vector_402</name><description>A KML LineString</description><LineString><coordinates>5.838523393080493,49.74814616928052 5.787079558782349,48.410795432216574 8.91427702008381,49.28932499608202</coordinates></LineString></Placemark><Placemark id="KML.Point"><name>OpenLayers.Feature.Vector_451</name><description>A KML Point</description><Point><coordinates>6.985073041685488,49.8682250149058</coordinates></Point></Placemark><Placemark id="KML.MultiGeometry"><name>SF Marina Harbor Master</name><description>KML MultiGeometry</description><MultiGeometry><LineString><coordinates>-122.4425587930444,37.80666418607323 -122.4428379594768,37.80663578323093</coordinates></LineString><LineString><coordinates>-122.4425509770566,37.80662588061205 -122.4428340530617,37.8065999493009</coordinates></LineString></MultiGeometry></Placemark></Folder></kml>';
var test_style = '<kml xmlns="http://earth.google.com/kml/2.0"> <Placemark> <Style> <LineStyle> <color>870000ff</color> <width>10</width> </LineStyle> </Style> <LineString> <coordinates> -112,36 -113,37 </coordinates> </LineString> </Placemark></kml>';
var test_style_fill = '<kml xmlns="http://earth.google.com/kml/2.0"> <Placemark> <Style> <PolyStyle> <fill>0</fill> <color>870000ff</color> <width>10</width> </PolyStyle> </Style> <LineString> <coordinates> -112,36 -113,37 </coordinates> </LineString> </Placemark></kml>';
var test_nl = '<kml xmlns="http://earth.google.com/kml/2.2"> <Document> <NetworkLink> <Link> <href>http://maker.geocommons.com/maps/1717/overlays/0</href> </Link> </NetworkLink> </Document></kml>';
function test_Format_KML_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.KML(options);
t.ok(format instanceof OpenLayers.Format.KML,
"new OpenLayers.Format.KML returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_KML_read(t) {
t.plan(5);
var features = (new OpenLayers.Format.KML()).read(this.test_content);
t.eq(features.length, 4, "Number of features read is correct");
t.ok(features[0].geometry.toString() == "POLYGON((5.001370157823406 49.26855713824488,8.214706453896161 49.630662409673505,8.397385910100951 48.45172350357396,5.001370157823406 49.26855713824488))", "polygon feature geometry correctly created");
t.ok(features[1].geometry.toString() == "LINESTRING(5.838523393080493 49.74814616928052,5.787079558782349 48.410795432216574,8.91427702008381 49.28932499608202)", "linestring feature geometry correctly created");
t.ok(features[2].geometry.toString() == "POINT(6.985073041685488 49.8682250149058)", "point feature geometry correctly created");
t.ok(features[3].geometry.CLASS_NAME == "OpenLayers.Geometry.Collection",
"read geometry collection");
}
function test_Format_KML_readCdataAttributes_20(t) {
t.plan(2);
var cdata = '<kml xmlns="http://earth.google.com/kml/2.0"><Document><Placemark><name><![CDATA[Pezinok]]></name><description><![CDATA[Full of text.]]></description><styleUrl>#rel1.0</styleUrl><Point> <coordinates>17.266666, 48.283333</coordinates></Point></Placemark></Document></kml>';
var features = (new OpenLayers.Format.KML()).read(cdata);
t.eq(features[0].attributes.description, "Full of text.", "Description attribute in cdata read correctly");
t.eq(features[0].attributes.name, "Pezinok", "title attribute in cdata read correctly");
}
function test_Format_KML_networklink(t) {
t.plan(1);
var f = new OpenLayers.Format.KML({'maxDepth':1});
f.fetchLink = function(url) {
t.eq(url, "http://maker.geocommons.com/maps/1717/overlays/0", "network link fetched a link correctly.");
return '';
}
f.read(test_nl);
}
function test_Format_KML_readCdataAttributes_21(t) {
t.plan(2);
var cdata = '<kml xmlns="http://earth.google.com/kml/2.1"><Document><Placemark><name><![CDATA[Pezinok]]></name><description><![CDATA[Full of text.]]></description><styleUrl>#rel1.0</styleUrl><Point> <coordinates>17.266666, 48.283333</coordinates></Point></Placemark></Document></kml>';
var features = (new OpenLayers.Format.KML()).read(cdata);
t.eq(features[0].attributes.description, "Full of text.", "Description attribute in cdata read correctly");
t.eq(features[0].attributes.name, "Pezinok", "title attribute in cdata read correctly");
}
function test_Format_KML_write(t) {
// make sure id, name, and description are preserved
t.plan(1);
var kmlExpected = this.test_content;
var options = {
folderName: "OpenLayers export",
foldersDesc: "Vector geometries from OpenLayers"
}
var format = new OpenLayers.Format.KML(options);
var features = format.read(kmlExpected);
var kmlOut = format.write(features);
var kmlOut = kmlOut.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(kmlOut, kmlExpected, "correctly writes an KML doc string");
}
function test_Format_KML_write_multis(t) {
/**
* KML doesn't have a representation for multi geometries of a
* specific type. KML MultiGeometry maps to OL Geometry.Collection.
* Because of this, multi-geometries in OL can't make a round trip
* through KML (an OL MultiPoint maps to a KML MultiGeometry
* containing points, which maps back to an OL Collection containing
* points). So we need to acceptance tests for the writing of
* multi-geometries specifically instead of relying on the round-trip
* write test above.
*/
t.plan(3);
var format = new OpenLayers.Format.KML({foldersDesc: "test output"});
var multi, feature, output, expected;
// test multipoint
var multi = new OpenLayers.Geometry.MultiPoint([
new OpenLayers.Geometry.Point(0, 1)
]);
feature = new OpenLayers.Feature.Vector(multi, {name: "test name"});
output = format.write(feature);
expected = '<kml xmlns="http://earth.google.com/kml/2.0"><Folder><name>OpenLayers export</name><description>test output</description><Placemark><name>test name</name><description>No description available</description><MultiGeometry><Point><coordinates>0,1</coordinates></Point></MultiGeometry></Placemark></Folder></kml>';
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, expected, "multipoint correctly written");
// test multilinestring
var multi = new OpenLayers.Geometry.MultiLineString([
new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(1, 0),
new OpenLayers.Geometry.Point(0, 1)
])
]);
feature = new OpenLayers.Feature.Vector(multi, {name: "test name"});
output = format.write(feature);
expected = '<kml xmlns="http://earth.google.com/kml/2.0"><Folder><name>OpenLayers export</name><description>test output</description><Placemark><name>test name</name><description>No description available</description><MultiGeometry><LineString><coordinates>1,0 0,1</coordinates></LineString></MultiGeometry></Placemark></Folder></kml>';
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, expected, "multilinestring correctly written");
// test multipolygon
var multi = new OpenLayers.Geometry.MultiPolygon([
new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(0, 0),
new OpenLayers.Geometry.Point(1, 0),
new OpenLayers.Geometry.Point(0, 1)
])
])
]);
feature = new OpenLayers.Feature.Vector(multi, {name: "test name"});
output = format.write(feature);
expected = '<kml xmlns="http://earth.google.com/kml/2.0"><Folder><name>OpenLayers export</name><description>test output</description><Placemark><name>test name</name><description>No description available</description><MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>0,0 1,0 0,1 0,0</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry></Placemark></Folder></kml>';
var output = output.replace(/<\?[^>]*\?>/, ''); // Remove XML Prolog
t.eq(output, expected, "multilinestring correctly written");
}
function test_Format_KML_extractStyle(t) {
t.plan(1);
var f = new OpenLayers.Format.KML();
var features = f.read(test_style);
t.ok(features[0].style == undefined, "KML Feature has no style with extractStyle false");
}
function test_Format_KML_extractStyleFill(t) {
t.plan(2);
var f = new OpenLayers.Format.KML({extractStyles: true});
var features = f.read(test_style);
t.eq(features[0].style.fillColor, "#ff0000", "default fill is set");
var features = f.read(test_style_fill);
t.eq(features[0].style.fillColor, "none", "KML Feature has none fill");
}
function test_Format_KML_getStyle(t) {
t.plan(1);
var style = {t: true};
var f = new OpenLayers.Format.KML();
f.styles = {test: style};
var gotStyle = f.getStyle('test');
gotStyle.t = false;
t.ok(style.t, "getStyle returns copy of style rather than reference");
}
function test_Format_KML_extendedData(t) {
t.plan(2);
var f = new OpenLayers.Format.KML();
var features = f.read(OpenLayers.Util.getElement("kml_extendeddata").value);
t.eq(features[0].attributes.all_bridges.value, "3030", "read value from extendeddata correctly.");
t.eq(features[0].attributes.all_bridges.displayName, "all bridges", "read displayName from extendeddata correctly.");
}
</script>
</head>
<body>
<textarea id="kml_extendeddata" style="display:none">
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<Placemark>
<styleUrl>#default</styleUrl>
<ExtendedData>
<Data name='all_bridges'>
<displayName><![CDATA[all bridges]]></displayName>
<value><![CDATA[3030]]></value>
</Data>
<Data name='latitude'>
<displayName><![CDATA[latitude]]></displayName>
<value><![CDATA[43]]></value>
</Data>
<Data name='longitude'>
<displayName><![CDATA[longitude]]></displayName>
<value><![CDATA[-107.55]]></value>
</Data>
<Data name='functionally_obsolete__percent'>
<displayName><![CDATA[functionally obsolete, percent]]></displayName>
<value><![CDATA[8]]></value>
</Data>
<Data name='structurally_deficient__percent'>
<displayName><![CDATA[structurally deficient, percent]]></displayName>
<value><![CDATA[13]]></value>
</Data>
<Data name='state'>
<displayName><![CDATA[state]]></displayName>
<value><![CDATA[Wyoming]]></value>
</Data>
</ExtendedData>
<Point>
<coordinates>-107.55,43.0</coordinates>
</Point>
</Placemark>
</Document>
</kml>
</textarea>
</body>
</html>

View File

@ -1,101 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script src="../data/osm.js"></script>
<script type="text/javascript">
function test_Format_OSM_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.OSM(options);
t.ok(format instanceof OpenLayers.Format.OSM,
"new OpenLayers.Format.OSM returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_OSM_node(t) {
t.plan(4);
var f = new OpenLayers.Format.OSM();
var features = f.read(osm_test_data['node']);
var feat = features[0];
t.eq(feat.attributes, {}, "attributes is empty");
t.eq(feat.osm_id, 200545, "internal osm_id property set correctly");
t.eq(feat.geometry.x, -1.8166417, "lon is correct");
t.eq(feat.geometry.y, 52.5503033, "lat is correct");
}
function test_Format_OSM_node_with_tags(t) {
t.plan(5);
var f = new OpenLayers.Format.OSM();
var features = f.read(osm_test_data['node_with_tags']);
var feat = features[0];
t.eq(feat.attributes, {'a':'b'}, "attributes match");
t.eq(feat.osm_id, 200545, "internal osm_id property set correctly");
t.eq(feat.fid, "node.200545", "OSM-based FID set correctly.");
t.eq(feat.geometry.x, -1.8166417, "lon is correct");
t.eq(feat.geometry.y, 52.5503033, "lat is correct");
}
function test_Format_OSM_way(t) {
t.plan(8);
var f = new OpenLayers.Format.OSM();
var features = f.read(osm_test_data['way']);
t.eq(features.length, 1, "One feature");
var feat = features[0];
t.eq(feat.osm_id, 4685537, "OSM ID set correctly.");
t.eq(feat.fid, "way.4685537", "OSM-based FID set correctly.");
t.eq(feat.geometry.CLASS_NAME, "OpenLayers.Geometry.Polygon", "returned as polygon");
t.eq(feat.geometry.components[0].components.length, 11, "Correct number of components");
t.eq(feat.geometry.components[0].components[0].osm_id, 29783472, "OSM ID set on components");
t.eq(feat.geometry.toString(), "POLYGON((-1.8164007 52.5501836,-1.8170311 52.5506035,-1.8164092 52.5509559,-1.8169385 52.5513103,-1.8159626 52.5517893,-1.8145067 52.5518461,-1.8143197 52.5511883,-1.8141177 52.5506446,-1.8151451 52.5501275,-1.8157703 52.5505521,-1.8164007 52.5501836))", "WKT of feature is correct");
t.eq(feat.attributes.landuse, "school", "landuse attribute correct");
}
function test_Format_OSM_node_way(t) {
t.plan(5)
var f = new OpenLayers.Format.OSM();
var features = f.read(osm_test_data['node_way']);
t.eq(features.length, 1, "One feature");
var feat = features[0];
t.eq(feat.osm_id, 21329267, "OSM ID set correctly");
t.eq(feat.attributes.highway, "unclassified", "highway attribute is correct.");
t.eq(feat.geometry.CLASS_NAME, "OpenLayers.Geometry.LineString", "returned as linestring");
t.eq(feat.geometry.components.length, 12, "correct number of segments");
}
function test_Format_OSM_node_way_checkTags(t) {
t.plan(9)
var f = new OpenLayers.Format.OSM({'checkTags': true});
var features = f.read(osm_test_data['node_way']);
t.eq(features.length, 3, "multiple features");
var feat = features[1];
t.eq(feat.geometry.CLASS_NAME, "OpenLayers.Geometry.Point", "point class");
t.ok(feat.attributes != {}, "feature has attributes");
var feat = features[2];
t.eq(feat.geometry.CLASS_NAME, "OpenLayers.Geometry.Point", "point class");
t.ok(feat.attributes != {}, "feature has attributes");
feat = features[0];
t.eq(feat.osm_id, 21329267, "OSM ID set correctly");
t.eq(feat.attributes.highway, "unclassified", "highway attribute is correct.");
t.eq(feat.geometry.CLASS_NAME, "OpenLayers.Geometry.LineString", "returned as linestring");
t.eq(feat.geometry.components.length, 12, "correct number of segments");
}
function test_Format_OSM_serialize(t) {
t.plan(4);
var f = new OpenLayers.Format.OSM({'checkTags': true});
for (var key in osm_serialized_data) {
var input = f.read(osm_test_data[key]);
var output = f.write(input);
output = output.replace(/<\?[^>]*\?>/, '');
t.eq(output, osm_serialized_data[key], key + " serialized correctly");
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,36 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var test_content = '<sld:StyledLayerDescriptor xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><sld:NamedLayer><sld:Name>TestLayer</sld:Name><sld:UserStyle><sld:Name>foo</sld:Name><sld:FeatureTypeStyle><sld:Rule><sld:Name>bar</sld:Name><ogc:Filter></ogc:Filter><sld:PolygonSymbolizer><sld:Fill><sld:CssParameter name="fill"><ogc:Literal>blue</ogc:Literal></sld:CssParameter></sld:Fill></sld:PolygonSymbolizer></sld:Rule></sld:FeatureTypeStyle></sld:UserStyle></sld:NamedLayer></sld:StyledLayerDescriptor>';
function test_Format_SLD_constructor(t) {
t.plan(3);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.SLD(options);
t.ok(format instanceof OpenLayers.Format.SLD,
"new OpenLayers.Format.SLD returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
}
function test_Format_SLD_read(t) {
t.plan(4);
var sld = new OpenLayers.Format.SLD().read(this.test_content);
var testLayer = sld.namedLayers["TestLayer"];
var userStyles = testLayer.userStyles;
t.eq(userStyles[0].name, "foo", "SLD correctly reads a UserStyle named 'foo'");
t.eq(userStyles[0].rules.length, 1, "The number of rules for the UserStyle is correct");
t.eq(userStyles[0].rules[0].name, "bar", "The first rule's name is 'bar'");
t.eq(userStyles[0].rules[0].symbolizer.Polygon.fillColor, "blue", "The fillColor for the Polygon symbolizer is correct");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,49 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_basic(t) {
t.plan(5);
var format = new OpenLayers.Format.Text({extractStyles: true});
var features = format.read(OpenLayers.Util.getElement("content").value);
t.eq(features[0].style.externalGraphic, format.defaultStyle.externalGraphic, "style is set to defaults if no style props set in text file");
var features = format.read(OpenLayers.Util.getElement("contentMarker").value);
t.eq(features[0].style.externalGraphic, "../../img/marker.png", "marker set correctly by default.");
var features = format.read(OpenLayers.Util.getElement("content2").value);
t.eq(features.length, 2, "two features read");
t.eq(features[0].style.externalGraphic, "marker.png", "marker set correctly from data.");
// t.eq(format.defaultStyle.externalGraphic, "../../img/marker.png", "defaultStyle externalGraphic not changed by pulling from data");
var format = new OpenLayers.Format.Text({extractStyles: false});
var features = format.read(OpenLayers.Util.getElement("content2").value);
t.eq(features[0].style, null, "extractStyles: false results in null style property, even with style properties used");
}
function test_extra(t) {
t.plan(1);
var format = new OpenLayers.Format.Text();
var features = format.read(OpenLayers.Util.getElement("content3").value);
t.eq(features[0].attributes.whee, "chicken", "extra attributes are stored for later use");
}
</script>
</head>
<body>
<textarea id="content">
point
5,5
</textarea>
<textarea id="contentMarker">
point iconSize
5,5 8,8
</textarea>
<textarea id="content2">
point icon
5,5 marker.png
10,10 marker2.png
</textarea>
<textarea id="content3">
point whee
5,5 chicken
</textarea>
</body>
</html>

View File

@ -1,81 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script>
function test_wfs_update_node(t) {
t.plan(2);
var expected = readXML("Update");
var updateFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(1,2),
{foo: "bar"});
updateFeature.fid = "fid.42";
updateFeature.state = OpenLayers.State.UPDATE;
var format = new OpenLayers.Format.WFS({
'featureNS':'http://www.openplans.org/topp',
'featureName': 'states',
'geometryName': 'the_geom',
'featurePrefix': 'topp'
}, {options:{}});
var updateNode = format.update(updateFeature);
t.xml_eq(updateNode, expected, "update node matches expected XML value.");
var format = new OpenLayers.Format.WFS({
'featurePrefix': 'topp'
}, {options:{typename: 'states', 'featureNS': 'http://www.openplans.org/topp', 'geometry_column': 'the_geom' }});
var updateNode = format.update(updateFeature);
t.xml_eq(updateNode, expected, "update node matches expected XML value.");
}
function test_wfs_delete_node(t) {
t.plan(2);
var expected = readXML("Delete");
var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.state = OpenLayers.State.DELETE;
feature.fid = "fid.37";
var format = new OpenLayers.Format.WFS({
'featureNS':'http://www.openplans.org/topp',
'featureName': 'states',
'featurePrefix': 'topp'
}, {options:{}});
var deleteNode = format.remove(feature);
t.xml_eq(deleteNode, expected, "delete node matches expected XML value.");
var format = new OpenLayers.Format.WFS({
'featurePrefix': 'topp'
}, {options:{typename: 'states', 'featureNS': 'http://www.openplans.org/topp'}});
var deleteNode = format.remove(feature);
t.xml_eq(deleteNode, expected, "delete node matches expected XML value.");
}
function readXML(id) {
var xml = document.getElementById(id).firstChild.nodeValue;
return new OpenLayers.Format.XML().read(xml).documentElement;
}
</script>
</head>
<body>
<div id="Update"><!--
<wfs:Update xmlns:wfs="http://www.opengis.net/wfs" typeName="topp:states" xmlns:topp="http://www.openplans.org/topp">
<wfs:Property>
<wfs:Name>the_geom</wfs:Name>
<wfs:Value>
<gml:Point xmlns:gml="http://www.opengis.net/gml">
<gml:coordinates decimal="." cs="," ts=" ">1,2</gml:coordinates>
</gml:Point>
</wfs:Value>
</wfs:Property>
<wfs:Property>
<wfs:Name>foo</wfs:Name>
<wfs:Value>bar</wfs:Value>
</wfs:Property>
<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
<ogc:FeatureId fid="fid.42"/>
</ogc:Filter>
</wfs:Update>
--></div>
<div id="Delete"><!--
<wfs:Delete xmlns:wfs="http://www.opengis.net/wfs" typeName="topp:states" xmlns:topp="http://www.openplans.org/topp">
<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
<ogc:FeatureId fid="fid.37"/>
</ogc:Filter>
</wfs:Delete>
--></div>
</body>
</html>

View File

@ -1,43 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_read(t) {
t.plan(4);
var _v1_0_0 = OpenLayers.Format.WFSCapabilities.v1_0_0.prototype.read;
var _v1_1_0 = OpenLayers.Format.WFSCapabilities.v1_1_0.prototype.read;
var parser = new OpenLayers.Format.WFSCapabilities();
// version 1.0.0
var text =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<wfs:WFS_Capabilities version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs"></wfs:WFS_Capabilities>';
OpenLayers.Format.WFSCapabilities.v1_0_0.prototype.read = function() {
t.ok(true, "Version 1.0.0 detected");
return {};
}
var res = parser.read(text);
t.eq(res.version, "1.0.0", "version 1.0.0 written to result object");
OpenLayers.Format.WFSCapabilities.v1_1_0.prototype.read = _v1_1_0;
// version 1.1.0
var text =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<wfs:WFS_Capabilities version="1.1.0" xmlns:wfs="http://www.opengis.net/wfs"></wfs:WFS_Capabilities>';
OpenLayers.Format.WFSCapabilities.v1_1_0.prototype.read = function() {
t.ok(true, "Version 1.1.0 detected");
return {};
}
var res = parser.read(text);
t.eq(res.version, "1.1.0", "version 1.1.0 written to result object");
OpenLayers.Format.WFSCapabilities.v1_1_0.prototype.read = _v1_1_0;
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,381 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_read_WFSDescribeFeatureType(t) {
t.plan(39);
var parser = new OpenLayers.Format.WFSDescribeFeatureType();
// single typeName from UMN Mapserver
var text =
'<?xml version="1.0" encoding="ISO-8859-1" ?>' +
'<schema' +
' targetNamespace="http://mapserver.gis.umn.edu/mapserver" ' +
' xmlns:rws="http://mapserver.gis.umn.edu/mapserver" ' +
' xmlns:ogc="http://www.opengis.net/ogc"' +
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
' xmlns="http://www.w3.org/2001/XMLSchema"' +
' xmlns:gml="http://www.opengis.net/gml"' +
' elementFormDefault="qualified" version="0.1" >' +
' <import namespace="http://www.opengis.net/gml"' +
' schemaLocation="http://schemas.opengis.net/gml/2.1.2/feature.xsd" />' +
' <element name="AAA64" ' +
' type="rws:AAA64Type" ' +
' substitutionGroup="gml:_Feature" />' +
' <complexType name="AAA64Type">' +
' <complexContent>' +
' <extension base="gml:AbstractFeatureType">' +
' <sequence>' +
' <element name="geometry" type="gml:MultiLineStringPropertyType" minOccurs="0" maxOccurs="1"/>' +
' <element name="OBJECTID" type="string"/>' +
' <element name="ROUTE" type="string"/>' +
' <element name="ROUTE_CH" type="string"/>' +
' <element name="COUNT" type="string"/>' +
' <element name="BEHEERDER" type="string"/>' +
' <element name="LENGTH" type="string"/>' +
' <element name="SHAPE" type="string"/>' +
' <element name="SE_ANNO_CAD_DATA" type="string"/>' +
' </sequence>' +
' </extension>' +
' </complexContent>' +
' </complexType>' +
'</schema>';
var res = parser.read(text);
t.eq(res.featureTypes.length, 1,
"There is only 1 typename, so length should be 1");
t.eq(res.featureTypes[0].properties[0].type, 'gml:MultiLineStringPropertyType',
"The first attribute is of type multi line string");
t.eq(res.featureTypes[0].properties[2].name, 'ROUTE',
"The third attribute is named ROUTE");
t.eq(res.featureTypes[0].properties[2].type, 'string',
"The third attribute is of type string");
// three typeNames in one response from UMN Mapserver
text =
'<?xml version="1.0" encoding="ISO-8859-1" ?>' +
'<schema' +
' targetNamespace="http://mapserver.gis.umn.edu/mapserver" ' +
' xmlns:rws="http://mapserver.gis.umn.edu/mapserver" ' +
' xmlns:ogc="http://www.opengis.net/ogc"' +
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
' xmlns="http://www.w3.org/2001/XMLSchema"' +
' xmlns:gml="http://www.opengis.net/gml"' +
' elementFormDefault="qualified" version="0.1" >' +
' <import namespace="http://www.opengis.net/gml"' +
' schemaLocation="http://schemas.opengis.net/gml/2.1.2/feature.xsd" />' +
' <element name="KGNAT.VKUNSTWERK" ' +
' type="rws:KGNAT.VKUNSTWERKType" ' +
' substitutionGroup="gml:_Feature" />' +
' <complexType name="KGNAT.VKUNSTWERKType">' +
' <complexContent>' +
' <extension base="gml:AbstractFeatureType">' +
' <sequence>' +
' <element name="geometry" type="gml:MultiPolygonPropertyType" minOccurs="0" maxOccurs="1"/>' +
' <element name="OBJECTID" type="string"/>' +
' <element name="OBJECTSUBCATEGORIE" type="string"/>' +
' <element name="DIENSTCODE" type="string"/>' +
' <element name="DISTRICTNAAM" type="string"/>' +
' <element name="CODEBPN" type="string"/>' +
' <element name="WSD" type="string"/>' +
' <element name="SUBCAT" type="string"/>' +
' <element name="ZIJDE" type="string"/>' +
' <element name="KM" type="string"/>' +
' <element name="ELEMENTCODE" type="string"/>' +
' <element name="COMPLEXCODE" type="string"/>' +
' <element name="BEHEEROBJECTCODE" type="string"/>' +
' <element name="BEGINDATUM" type="string"/>' +
' <element name="NAAMCONTACTPERSOON" type="string"/>' +
' <element name="KMTOT" type="string"/>' +
' <element name="HOOFDWATERSYSTEEM" type="string"/>' +
' <element name="WATERSYSTEEMNAAM" type="string"/>' +
' <element name="OBJECTNAAM" type="string"/>' +
' <element name="HERKOMST" type="string"/>' +
' <element name="BEHEERSREGIME" type="string"/>' +
' <element name="VERSIE" type="string"/>' +
' <element name="KWALITEITSNIVEAU" type="string"/>' +
' <element name="STICHTINGSJAAR" type="string"/>' +
' <element name="OBJECTTYPE" type="string"/>' +
' <element name="OPMERKING" type="string"/>' +
' <element name="OPPERVLAKTE" type="string"/>' +
' <element name="SE_ANNO_CAD_DATA" type="string"/>' +
' <element name="SHAPE" type="string"/>' +
' </sequence>' +
' </extension>' +
' </complexContent>' +
' </complexType>' +
' <element name="KGNAT.LKUNSTWERK" ' +
' type="rws:KGNAT.LKUNSTWERKType" ' +
' substitutionGroup="gml:_Feature" />' +
' <complexType name="KGNAT.LKUNSTWERKType">' +
' <complexContent>' +
' <extension base="gml:AbstractFeatureType">' +
' <sequence>' +
' <element name="geometry" type="gml:MultiLineStringPropertyType" minOccurs="0" maxOccurs="1"/>' +
' <element name="OBJECTID" type="string"/>' +
' <element name="OBJECTSUBCATEGORIE" type="string"/>' +
' <element name="DIENSTCODE" type="string"/>' +
' <element name="DISTRICTNAAM" type="string"/>' +
' <element name="CODEBPN" type="string"/>' +
' <element name="WSD" type="string"/>' +
' <element name="SUBCAT" type="string"/>' +
' <element name="ZIJDE" type="string"/>' +
' <element name="KM" type="string"/>' +
' <element name="ELEMENTCODE" type="string"/>' +
' <element name="COMPLEXCODE" type="string"/>' +
' <element name="BEHEEROBJECTCODE" type="string"/>' +
' <element name="BEGINDATUM" type="string"/>' +
' <element name="NAAMCONTACTPERSOON" type="string"/>' +
' <element name="KMTOT" type="string"/>' +
' <element name="HOOFDWATERSYSTEEM" type="string"/>' +
' <element name="WATERSYSTEEMNAAM" type="string"/>' +
' <element name="OBJECTNAAM" type="string"/>' +
' <element name="HERKOMST" type="string"/>' +
' <element name="BEHEERSREGIME" type="string"/>' +
' <element name="VERSIE" type="string"/>' +
' <element name="KWALITEITSNIVEAU" type="string"/>' +
' <element name="STICHTINGSJAAR" type="string"/>' +
' <element name="OBJECTTYPE" type="string"/>' +
' <element name="OPMERKING" type="string"/>' +
' <element name="LENGTE" type="string"/>' +
' <element name="SE_ANNO_CAD_DATA" type="string"/>' +
' <element name="SHAPE" type="string"/>' +
' </sequence>' +
' </extension>' +
' </complexContent>' +
' </complexType>' +
' <element name="KGNAT.PKUNSTWERK" ' +
' type="rws:KGNAT.PKUNSTWERKType" ' +
' substitutionGroup="gml:_Feature" />' +
' <complexType name="KGNAT.PKUNSTWERKType">' +
' <complexContent>' +
' <extension base="gml:AbstractFeatureType">' +
' <sequence>' +
' <element name="geometry" type="gml:MultiPointPropertyType" minOccurs="0" maxOccurs="1"/>' +
' <element name="OBJECTID" type="string"/>' +
' <element name="OBJECTSUBCATEGORIE" type="string"/>' +
' <element name="DIENSTCODE" type="string"/>' +
' <element name="DISTRICTNAAM" type="string"/>' +
' <element name="CODEBPN" type="string"/>' +
' <element name="WSD" type="string"/>' +
' <element name="SUBCAT" type="string"/>' +
' <element name="ZIJDE" type="string"/>' +
' <element name="KM" type="string"/>' +
' <element name="ELEMENTCODE" type="string"/>' +
' <element name="COMPLEXCODE" type="string"/>' +
' <element name="BEHEEROBJECTCODE" type="string"/>' +
' <element name="BEGINDATUM" type="string"/>' +
' <element name="NAAMCONTACTPERSOON" type="string"/>' +
' <element name="KMTOT" type="string"/>' +
' <element name="HOOFDWATERSYSTEEM" type="string"/>' +
' <element name="WATERSYSTEEMNAAM" type="string"/>' +
' <element name="OBJECTNAAM" type="string"/>' +
' <element name="HERKOMST" type="string"/>' +
' <element name="BEHEERSREGIME" type="string"/>' +
' <element name="VERSIE" type="string"/>' +
' <element name="KWALITEITSNIVEAU" type="string"/>' +
' <element name="STICHTINGSJAAR" type="string"/>' +
' <element name="OBJECTTYPE" type="string"/>' +
' <element name="OPMERKING" type="string"/>' +
' <element name="X" type="string"/>' +
' <element name="Y" type="string"/>' +
' <element name="SE_ANNO_CAD_DATA" type="string"/>' +
' <element name="SHAPE" type="string"/>' +
' </sequence>' +
' </extension>' +
' </complexContent>' +
' </complexType>' +
'</schema>';
parser = new OpenLayers.Format.WFSDescribeFeatureType();
res = parser.read(text);
t.eq(res.featureTypes.length, 3,
"There are 3 typenames, so length should be 3");
t.eq(res.featureTypes[0].typeName, 'KGNAT.VKUNSTWERK',
"There name of the first typename is KGNAT.VKUNSTWERK");
t.eq(res.featureTypes[2].properties.length, 30,
"We expect 30 attributes in the third typename");
t.eq(res.featureTypes[2].properties[1].name, 'OBJECTID',
"The second attribute has name OBJECTID");
t.eq(res.featureTypes[2].properties[1].type, 'string',
"The second attribute has type string");
t.eq(res.targetNamespace, 'http://mapserver.gis.umn.edu/mapserver',
"The targetNamespace should be http://mapserver.gis.umn.edu/mapserver");
t.eq(res.targetPrefix, 'rws', "the targetPrefix should be rws");
// response from Ionic WFS, taken from:
// http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA?service=WFS&request=DescribeFeatureType&version=1.0.0&typename=wfs:highways
text =
"<?xml version='1.0' encoding='utf-8' ?>" +
' <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml" xmlns:wfs="http://www.ionicsoft.com/wfs" targetNamespace="http://www.ionicsoft.com/wfs" xmlns:xlink="http://www.w3.org/1999/xlink" elementFormDefault="qualified" version="0.1">' +
' <xsd:import namespace="http://www.opengis.net/gml" schemaLocation="http://schemas.opengis.net/gml/2.1.2/feature.xsd"/>' +
' <xsd:element name="highways" substitutionGroup="gml:_Feature" type="wfs:highways"/>' +
' <xsd:complexType name="highways">' +
' <xsd:complexContent>' +
' <xsd:extension base="gml:AbstractFeatureType">' +
' <xsd:sequence>' +
' <xsd:element name="ROUTE_" minOccurs="0" nillable="true" type="xsd:int"/>' +
' <xsd:element name="ROUTE_ID" minOccurs="0" nillable="true" type="xsd:int"/>' +
' <xsd:element name="RT_NUMBER" minOccurs="0" nillable="true" type="xsd:string"/>' +
' <xsd:element name="GEOMETRY" minOccurs="0" nillable="true" type="gml:GeometryAssociationType"/>' +
' </xsd:sequence>' +
' </xsd:extension>' +
' </xsd:complexContent>' +
' </xsd:complexType>' +
' </xsd:schema>';
parser = new OpenLayers.Format.WFSDescribeFeatureType();
res = parser.read(text);
t.eq(res.featureTypes.length, 1,
"There is 1 typename, so length should be 1");
t.eq(res.featureTypes[0].typeName, "highways",
"The name of the typename is highways");
t.eq(res.featureTypes[0].properties.length, 4,
"We expect 4 attributes in the first typename");
t.eq(res.featureTypes[0].properties[1].name, 'ROUTE_ID',
"The second attribute has name ROUTE_ID");
t.eq(res.featureTypes[0].properties[1].type, 'xsd:int',
"The second attribute has type integer");
t.eq(parseInt(res.featureTypes[0].properties[1].minOccurs), 0,
"The second attribute has minOccurs 0");
t.eq(res.targetNamespace, 'http://www.ionicsoft.com/wfs',
"The targetNamespace should be http://www.ionicsoft.com/wfs");
t.eq(res.targetPrefix, 'wfs', "the targetPrefix should be wfs");
// GeoServer tests
function geoServerTests(text) {
parser = new OpenLayers.Format.WFSDescribeFeatureType();
res = parser.read(text);
t.eq(res.featureTypes.length, 1,
"There is 1 typename, so length should be 1");
t.eq(res.featureTypes[0].typeName, "railroads",
"The name of the typeName is railroads");
t.eq(res.featureTypes[0].properties.length, 2,
"We expect 2 attributes in the typename");
t.eq(res.featureTypes[0].properties[0].name, 'cat',
"The first attribute has name cat");
t.eq(res.featureTypes[0].properties[0].type.split(":")[1], 'long',
"The first attribute has type long with a prefix");
t.eq(res.featureTypes[0].properties[0].localType, 'long',
"The first attribute has localType long");
t.eq(res.targetNamespace, 'http://opengeo.org',
"The targetNamespace should be http://opengeo.org");
t.eq(res.targetPrefix, 'opengeo', "the targetPrefix should be opengeo");
}
// Read Geoserver WFS 1.0.0 response
// Taken from: http://demo.opengeo.org/geoserver/wfs?service=WFS&request=DescribeFeatureType&typename=opengeo:railroads&version=1.0.0
text =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<xs:schema targetNamespace="http://opengeo.org" xmlns:opengeo="http://opengeo.org" xmlns:gml="http://www.opengis.net/gml" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0">' +
' <xs:import namespace="http://www.opengis.net/gml" schemaLocation="http://demo.opengeo.org:80/geoserver/schemas/gml/2.1.2.1/feature.xsd"/>' +
' <xs:complexType xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema" name="railroads_Type">' +
' <xs:complexContent>' +
' <xs:extension base="gml:AbstractFeatureType">' +
' <xs:sequence>' +
' <xs:element name="cat" minOccurs="0" nillable="true" type="xs:long"/>' +
' <xs:element name="the_geom" minOccurs="0" nillable="true" type="gml:MultiLineStringPropertyType"/>' +
' </xs:sequence>' +
' </xs:extension>' +
' </xs:complexContent>' +
' </xs:complexType>' +
' <xs:element name="railroads" type="opengeo:railroads_Type" substitutionGroup="gml:_Feature"/>' +
'</xs:schema>';
geoServerTests(text);
// Read GeoServer WFS 1.1.0 response
// taken from http://demo.opengeo.org/geoserver/wfs?service=WFS&request=DescribeFeatureType&typename=opengeo:railroads&version=1.1.0
text =
'<?xml version="1.0" encoding="UTF-8"?>' +
' <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml" xmlns:opengeo="http://opengeo.org" elementFormDefault="qualified" targetNamespace="http://opengeo.org">' +
' <xsd:import namespace="http://www.opengis.net/gml" schemaLocation="http://demo.opengeo.org:80/geoserver/wfs/schemas/gml/3.1.1/base/gml.xsd"/>' +
' <xsd:complexType name="railroadsType">' +
' <xsd:complexContent>' +
' <xsd:extension base="gml:AbstractFeatureType">' +
' <xsd:sequence>' +
' <xsd:element maxOccurs="1" minOccurs="0" name="cat" nillable="true" type="xsd:long"/>' +
' <xsd:element maxOccurs="1" minOccurs="0" name="the_geom" nillable="true" type="gml:MultiLineStringPropertyType"/>' +
' </xsd:sequence>' +
' </xsd:extension>' +
' </xsd:complexContent>' +
' </xsd:complexType>' +
' <xsd:element name="railroads" substitutionGroup="gml:_Feature" type="opengeo:railroadsType"/>' +
' </xsd:schema>';
geoServerTests(text);
// Another GeoServer response with type restrictions
// taken from http://sigma.openplans.org/geoserver/wfs?service=WFS&request=DescribeFeatureType&typename=topp:states&version=1.0.0
text = '<?xml version="1.0" encoding="UTF-8"?><xs:schema targetNamespace="http://www.openplans.org/topp" xmlns:topp="http://www.openplans.org/topp" xmlns:gml="http://www.opengis.net/gml" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0"><xs:import namespace="http://www.opengis.net/gml" schemaLocation="http://sigma.openplans.org:80/geoserver/schemas/gml/2.1.2.1/feature.xsd"/><xs:complexType xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema" name="states_Type"><xs:complexContent><xs:extension base="gml:AbstractFeatureType"><xs:sequence><xs:element name="the_geom" minOccurs="0" nillable="true" type="gml:MultiPolygonPropertyType"/><xs:element name="STATE_NAME" minOccurs="0" nillable="true"><xs:simpleType><xs:restriction base="xs:string"><xs:maxLength value="25"/></xs:restriction></xs:simpleType></xs:element><xs:element name="STATE_FIPS" minOccurs="0" nillable="true"><xs:simpleType><xs:restriction base="xs:string"><xs:maxLength value="2"/></xs:restriction></xs:simpleType></xs:element><xs:element name="SUB_REGION" minOccurs="0" nillable="true"><xs:simpleType><xs:restriction base="xs:string"><xs:maxLength value="7"/></xs:restriction></xs:simpleType></xs:element><xs:element name="STATE_ABBR" minOccurs="0" nillable="true"><xs:simpleType><xs:restriction base="xs:string"><xs:maxLength value="2"/></xs:restriction></xs:simpleType></xs:element><xs:element name="LAND_KM" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="WATER_KM" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="PERSONS" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="FAMILIES" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="HOUSHOLD" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="MALE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="FEMALE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="WORKERS" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="DRVALONE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="CARPOOL" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="PUBTRANS" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="EMPLOYED" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="UNEMPLOY" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="SERVICE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="MANUAL" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="P_MALE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="P_FEMALE" minOccurs="0" nillable="true" type="xs:double"/><xs:element name="SAMP_POP" minOccurs="0" nillable="true" type="xs:double"/></xs:sequence></xs:extension></xs:complexContent></xs:complexType><xs:element name="states" type="topp:states_Type" substitutionGroup="gml:_Feature"/></xs:schema>';
parser = new OpenLayers.Format.WFSDescribeFeatureType();
res = parser.read(text);
t.eq(res.featureTypes[0].properties[1].name, "STATE_NAME",
"name of 2nd property of 1st featureType should be 'STATE_NAME'");
t.eq(res.featureTypes[0].properties[1].type, "xs:string",
"type of 2nd property of 1st featureType should be 'xs:string'");
t.eq(res.featureTypes[0].properties[1].localType, "string",
"localType of 2nd property of 1st featureType should be 'string'");
t.eq(res.featureTypes[0].properties[1].restriction.maxLength, "25",
"the maxLength restriction should be 25");
}
function test_readRestriction(t) {
t.plan(2);
var text =
'<restriction xmlns="http://www.w3.org/2001/XMLSchema" base="xs:string">' +
' <enumeration value="One"/>' +
' <enumeration value="Two"/>' +
'</restriction>';
var doc = OpenLayers.Format.XML.prototype.read(text).documentElement;
var obj = {};
new OpenLayers.Format.WFSDescribeFeatureType().readRestriction(doc, obj);
t.eq(obj.enumeration.length, 2, "enumeration has a length of 2");
t.eq(obj.enumeration[1], "Two", "2nd enumeration value is 'Two'");
// other functionality of readRestriction already tested in the last
// GeoServer example above
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,23 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(2);
var format = new OpenLayers.Format.WFST();
t.ok(format instanceof OpenLayers.Format.WFST.v1_0_0, "constructor returns instance with default versioned format");
format = new OpenLayers.Format.WFST({
version: "1.1.0"
});
t.ok(format instanceof OpenLayers.Format.WFST.v1_1_0, "constructor returns instance with custom versioned format");
}
</script>
</head>
<body>
<div id="map" style="width:512px; height:256px"> </div>
</body>
</html>

View File

@ -1,244 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var points = [];
for(var i=0; i<12; ++i) {
points.push(new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(Math.random() * 100,
Math.random() * 100))
);
}
var multipoint = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiPoint([
points[0].geometry,
points[1].geometry,
points[2].geometry
])
);
var linestrings = [
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.LineString([
points[0].geometry,
points[1].geometry,
points[2].geometry
])
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.LineString([
points[3].geometry,
points[4].geometry,
points[5].geometry
])
)
];
var multilinestring = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiLineString([
linestrings[0].geometry,
linestrings[1].geometry
])
);
var rings = [
new OpenLayers.Geometry.LinearRing([
points[0].geometry,
points[1].geometry,
points[2].geometry
]),
new OpenLayers.Geometry.LinearRing([
points[3].geometry,
points[4].geometry,
points[5].geometry
]),
new OpenLayers.Geometry.LinearRing([
points[6].geometry,
points[7].geometry,
points[8].geometry
]),
new OpenLayers.Geometry.LinearRing([
points[9].geometry,
points[10].geometry,
points[11].geometry
])
];
var polygons = [
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon([rings[0], rings[1]])
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon([rings[2], rings[3]])
)
];
var multipolygon = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.MultiPolygon([
polygons[0].geometry,
polygons[1].geometry
])
);
var collection = [points[0], linestrings[0]];
function test_Format_WKT_constructor(t) {
t.plan(4);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.WKT(options);
t.ok(format instanceof OpenLayers.Format.WKT,
"new OpenLayers.Format.WKT returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
}
function test_Format_WKT_write(t) {
t.plan(7);
var format = new OpenLayers.Format.WKT();
// test a point
t.eq(format.write(points[0]),
"POINT(" + points[0].geometry.x + " " + points[0].geometry.y + ")",
"format correctly writes Point WKT");
// test a multipoint
t.eq(format.write(multipoint),
"MULTIPOINT(" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + ")",
"format correctly writes MultiPoint WKT");
// test a linestring
t.eq(format.write(linestrings[0]),
"LINESTRING(" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + ")",
"format correctly writes LineString WKT");
// test a multilinestring
t.eq(format.write(multilinestring),
"MULTILINESTRING((" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + ")," +
"(" + points[3].geometry.x + " " + points[3].geometry.y + "," +
points[4].geometry.x + " " + points[4].geometry.y + "," +
points[5].geometry.x + " " + points[5].geometry.y + "))",
"format correctly writes MultiLineString WKT");
// test a polygon
t.eq(format.write(polygons[0]),
"POLYGON((" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + "," +
points[0].geometry.x + " " + points[0].geometry.y + ")," +
"(" + points[3].geometry.x + " " + points[3].geometry.y + "," +
points[4].geometry.x + " " + points[4].geometry.y + "," +
points[5].geometry.x + " " + points[5].geometry.y + "," +
points[3].geometry.x + " " + points[3].geometry.y + "))",
"format correctly writes Polygon WKT");
// test a multipolygon
t.eq(format.write(multipolygon),
"MULTIPOLYGON(((" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + "," +
points[0].geometry.x + " " + points[0].geometry.y + ")," +
"(" + points[3].geometry.x + " " + points[3].geometry.y + "," +
points[4].geometry.x + " " + points[4].geometry.y + "," +
points[5].geometry.x + " " + points[5].geometry.y + "," +
points[3].geometry.x + " " + points[3].geometry.y + "))," +
"((" + points[6].geometry.x + " " + points[6].geometry.y + "," +
points[7].geometry.x + " " + points[7].geometry.y + "," +
points[8].geometry.x + " " + points[8].geometry.y + "," +
points[6].geometry.x + " " + points[6].geometry.y + ")," +
"(" + points[9].geometry.x + " " + points[9].geometry.y + "," +
points[10].geometry.x + " " + points[10].geometry.y + "," +
points[11].geometry.x + " " + points[11].geometry.y + "," +
points[9].geometry.x + " " + points[9].geometry.y + ")))",
"format correctly writes MultiPolygon WKT");
// test a geometrycollection
t.eq(format.write(collection),
"GEOMETRYCOLLECTION(POINT(" + points[0].geometry.x + " " + points[0].geometry.y + ")," +
"LINESTRING(" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + "))",
"format correctly writes GeometryCollection WKT");
}
function test_Format_WKT_read(t) {
t.plan(7);
var format = new OpenLayers.Format.WKT();
/**
* Since we're explicitly testing calls to write, the read tests
* just make sure that geometry can make a round trip from read to write.
*/
// test a point
t.ok(points[0].geometry.equals(format.read(format.write(points[0])).geometry),
"format correctly reads Point WKT");
// test a multipoint
t.ok(multipoint.geometry.equals(format.read(format.write(multipoint)).geometry),
"format correctly reads MultiPoint WKT");
// test a linestring
t.ok(linestrings[0].geometry.equals(format.read(format.write(linestrings[0])).geometry),
"format correctly reads LineString WKT");
// test a multilinestring
t.ok(multilinestring.geometry.equals(format.read(format.write(multilinestring)).geometry),
"format correctly reads MultiLineString WKT");
// test a polygon
t.ok(polygons[0].geometry.equals(format.read(format.write(polygons[0])).geometry),
"format correctly reads Polygon WKT");
// test a multipolygon
t.ok(multipolygon.geometry.equals(format.read(format.write(multipolygon)).geometry),
"format correctly reads MultiPolygon WKT");
// test a geometrycollection
t.eq(format.write(collection),
"GEOMETRYCOLLECTION(POINT(" + points[0].geometry.x + " " + points[0].geometry.y + ")," +
"LINESTRING(" + points[0].geometry.x + " " + points[0].geometry.y + "," +
points[1].geometry.x + " " + points[1].geometry.y + "," +
points[2].geometry.x + " " + points[2].geometry.y + "))",
"format correctly writes GeometryCollection WKT");
}
function test_Format_WKT_read_projection(t) {
t.plan(1);
var projections = {
src: new OpenLayers.Projection("EPSG:4326"),
dest: new OpenLayers.Projection("EPSG:900913")
};
var points = {
src: new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(-87.9, 41.9)),
dest: new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(-9784983.2393667, 5146011.6785665))
};
var format = new OpenLayers.Format.WKT({
externalProjection: projections["src"],
internalProjection: projections["dest"]
});
var feature = format.read("GEOMETRYCOLLECTION(POINT(" + points["src"].geometry.x + " " + points["src"].geometry.y + "))")[0];
t.eq(feature.geometry.toString(), points["dest"].geometry.toString(),
"Geometry collections aren't transformed twice when reprojection.");
}
</script>
</head>
<body>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -1,200 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_write_wmc_StyleList(t) {
t.plan(3);
var layer, got, expected;
var parser = new OpenLayers.Format.WMC.v1();
var name = "test";
var url = "http://foo";
// test named style
layer = new OpenLayers.Layer.WMS(name, url, {
styles: "mystyle"
});
got = parser.write_wmc_StyleList(layer);
expected =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<Name>mystyle</Name><Title>Default</Title>" +
"</Style>" +
"</StyleList>";
t.xml_eq(got, expected, "named style correctly written");
layer.destroy();
// test linked style
layer = new OpenLayers.Layer.WMS(name, url, {
sld: "http://linked.sld"
});
got = parser.write_wmc_StyleList(layer);
expected =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<SLD>" +
"<OnlineResource xmlns:xlink='http://www.w3.org/1999/xlink' "+
"xlink:type='simple' " +
"xlink:href='http://linked.sld' />" +
"</SLD>" +
"</Style>" +
"</StyleList>";
t.xml_eq(got, expected, "linked style correctly written");
layer.destroy();
// test inline style
layer = new OpenLayers.Layer.WMS(name, url, {
sld_body:
"<sld:StyledLayerDescriptor version='1.0.0' " +
"xmlns:ogc='http://www.opengis.net/ogc' " +
"xmlns:sld='http://www.opengis.net/sld' " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xsi:schemaLocation='http://www.opengis.net/sld http://schemas.opengeospatial.net/sld/1.0.0/StyledLayerDescriptor.xsd'>" +
"<sld:NamedLayer>" +
"<sld:Name>AAA212</sld:Name>" +
"<sld:UserStyle>" +
"<sld:FeatureTypeStyle>" +
"<sld:Rule>" +
"<sld:TextSymbolizer>" +
"<sld:Label>" +
"<ogc:PropertyName>ZONENR</ogc:PropertyName>" +
"</sld:Label>" +
"<sld:Font>" +
"<sld:CssParameter name='font-family'>Arial</sld:CssParameter>" +
"<sld:CssParameter name='font-size'>10</sld:CssParameter>" +
"</sld:Font>" +
"<sld:Fill>" +
"<sld:CssParameter name='fill'>#FF9900</sld:CssParameter>" +
"</sld:Fill>" +
"</sld:TextSymbolizer>" +
"</sld:Rule>" +
"</sld:FeatureTypeStyle>" +
"</sld:UserStyle>" +
"</sld:NamedLayer>" +
"</sld:StyledLayerDescriptor>"
});
got = parser.write_wmc_StyleList(layer);
expected =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<SLD>" +
"<sld:StyledLayerDescriptor version='1.0.0' " +
"xmlns:sld='http://www.opengis.net/sld' " +
"xmlns:ogc='http://www.opengis.net/ogc' " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xsi:schemaLocation='http://www.opengis.net/sld http://schemas.opengeospatial.net/sld/1.0.0/StyledLayerDescriptor.xsd'>" +
"<sld:NamedLayer>" +
"<sld:Name>AAA212</sld:Name>" +
"<sld:UserStyle>" +
"<sld:FeatureTypeStyle>" +
"<sld:Rule>" +
"<sld:TextSymbolizer>" +
"<sld:Label>" +
"<ogc:PropertyName>ZONENR</ogc:PropertyName>" +
"</sld:Label>" +
"<sld:Font>" +
"<sld:CssParameter name='font-family'>Arial</sld:CssParameter>" +
"<sld:CssParameter name='font-size'>10</sld:CssParameter>" +
"</sld:Font>" +
"<sld:Fill>" +
"<sld:CssParameter name='fill'>#FF9900</sld:CssParameter>" +
"</sld:Fill>" +
"</sld:TextSymbolizer>" +
"</sld:Rule>" +
"</sld:FeatureTypeStyle>" +
"</sld:UserStyle>" +
"</sld:NamedLayer>" +
"</sld:StyledLayerDescriptor>" +
"</SLD>" +
"</Style>" +
"</StyleList>";
t.xml_eq(got, expected, "inline style correctly written");
layer.destroy();
}
function test_read_wmc_StyleList(t) {
t.plan(3);
var xml = new OpenLayers.Format.XML();
var parser = new OpenLayers.Format.WMC.v1();
var node, text, layerInfo;
// test named style
text =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<Name>mystyle</Name><Title>Default</Title>" +
"</Style>" +
"</StyleList>";
node = xml.read(text).documentElement;
layerInfo = {
params: {},
styles: []
};
parser.read_wmc_StyleList(layerInfo, node);
t.eq(layerInfo.params.styles, "mystyle", "named style correctly read");
// test linked style
text =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<SLD>" +
"<OnlineResource xmlns:xlink='http://www.w3.org/1999/xlink' "+
"xlink:type='simple' " +
"xlink:href='http://linked.sld' />" +
"</SLD>" +
"</Style>" +
"</StyleList>";
node = xml.read(text).documentElement;
layerInfo = {
params: {},
styles: []
};
parser.read_wmc_StyleList(layerInfo, node);
t.eq(layerInfo.params.sld, "http://linked.sld", "linked style correctly read");
// test inline style
// any valid xml under the StyledLayerDescriptor node should make the
// round trip from string to node and back
text =
"<StyleList xmlns='http://www.opengis.net/context'>" +
"<Style current='1'>" +
"<SLD>" +
"<sld:StyledLayerDescriptor version='1.0.0' " +
"xmlns:sld='http://www.opengis.net/sld' " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xsi:schemaLocation='http://www.opengis.net/sld http://schemas.opengeospatial.net/sld/1.0.0/StyledLayerDescriptor.xsd'>" +
"<foo>bar<more/></foo>" +
"</sld:StyledLayerDescriptor>" +
"</SLD>" +
"</Style>" +
"</StyleList>";
node = xml.read(text).documentElement;
layerInfo = {
params: {},
styles: []
};
parser.read_wmc_StyleList(layerInfo, node);
var expected =
"<sld:StyledLayerDescriptor version='1.0.0' " +
"xmlns:sld='http://www.opengis.net/sld' " +
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xsi:schemaLocation='http://www.opengis.net/sld http://schemas.opengeospatial.net/sld/1.0.0/StyledLayerDescriptor.xsd'>" +
"<foo xmlns='http://www.opengis.net/context'>bar<more/></foo>" +
"</sld:StyledLayerDescriptor>";
t.xml_eq(layerInfo.params.sld_body, expected, "inline style correctly read");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,74 +0,0 @@
<html>
<head>
<script src="../../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_write_wmc_Layer(t) {
if (OpenLayers.Util.getBrowserName() == "safari") {
t.plan(0);
t.debug_print("Safari has wierd behavior with getElementsByTagNameNS: the result is that we can't run these tests there. Patches welcome.");
return;
}
t.plan(10);
// direct construction of a parser for a unit test
var wmc = new OpenLayers.Format.WMC.v1_1_0();
var sldNS = wmc.namespaces["sld"];
// test that Min/MaxScaleDenominator is not written out when no
// resolution related options are set
var layer = new OpenLayers.Layer.WMS(
"test", "http://foo", {},
{maxExtent: new OpenLayers.Bounds(1, 2, 3, 4)}
);
var node = wmc.write_wmc_Layer(layer);
var minList = wmc.getElementsByTagNameNS(node, sldNS, "MinScaleDenominator");
t.eq(minList.length, 0, "(none) node not written with MinScaleDenominator");
var maxList = wmc.getElementsByTagNameNS(node, sldNS, "MaxScaleDenominator");
t.eq(maxList.length, 0, "(none) node not written with MaxScaleDenominator");
// test that Min/MaxScaleDenominator is written out for explicit
// resolutions array
layer = new OpenLayers.Layer.WMS(
"test", "http://foo", {},
{resolutions: [4, 2, 1], maxExtent: new OpenLayers.Bounds(1, 2, 3, 4)}
);
layer.minScale = Math.random();
layer.maxScale = Math.random();
sldNS = wmc.namespaces["sld"];
node = wmc.write_wmc_Layer(layer);
minList = wmc.getElementsByTagNameNS(node, sldNS, "MinScaleDenominator");
t.eq(minList.length, 1, "(resolutions) node written with MinScaleDenominator");
t.eq(layer.maxScale.toPrecision(10), wmc.getChildValue(minList[0]),
"(resolutions) node written with correct MinScaleDenominator value");
maxList = wmc.getElementsByTagNameNS(node, sldNS, "MaxScaleDenominator");
t.eq(maxList.length, 1, "(resolutions) node written with MaxScaleDenominator");
t.eq(layer.minScale.toPrecision(10), wmc.getChildValue(maxList[0]),
"(resolutions) node written with correct MaxScaleDenominator value");
layer = new OpenLayers.Layer.WMS(
"test", "http://foo", {},
{scales: [4, 2, 1], maxExtent: new OpenLayers.Bounds(1, 2, 3, 4)}
);
layer.minScale = Math.random();
layer.maxScale = Math.random();
node = wmc.write_wmc_Layer(layer);
minList = wmc.getElementsByTagNameNS(node, sldNS, "MinScaleDenominator");
var f = new OpenLayers.Format.XML();
t.eq(minList.length, 1, "(scales) node written with MinScaleDenominator");
t.eq(layer.maxScale.toPrecision(10), wmc.getChildValue(minList[0]),
"(scales) node written with correct MinScaleDenominator value");
maxList = wmc.getElementsByTagNameNS(node, sldNS, "MaxScaleDenominator");
t.eq(maxList.length, 1, "(scales) node written with MaxScaleDenominator");
t.eq(layer.minScale.toPrecision(10), wmc.getChildValue(maxList[0]),
"(scales) node written with correct MaxScaleDenominator value");
}
</script>
</head>
<body>
<div id="map" style="width: 512px; height: 256px;"></div>
</body>
</html>

View File

@ -1,20 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(1);
var format = new OpenLayers.Format.WMSCapabilities({
version: "foo"
});
t.eq(format.version, "foo", "version set on format");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,38 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_read_WMSDescribeLayer(t) {
t.plan(4);
var parser = new OpenLayers.Format.WMSDescribeLayer();
var text =
'<WMS_DescribeLayerResponse version="1.1.1">' +
' <LayerDescription name="topp:states" wfs="http://geo.openplans.org:80/geoserver/wfs/WfsDispatcher?">' +
' <Query typeName="topp:states"/>' +
' </LayerDescription>' +
'</WMS_DescribeLayerResponse>';
var res = parser.read(text);
t.eq(res.length, 1,
"Only one LayerDescription in data, so only one parsed");
t.eq(res[0].owsType, "WFS",
"Properly parses owsType as WFS");
t.eq(res[0].owsURL, "http://geo.openplans.org:80/geoserver/wfs/WfsDispatcher?",
"Properly parses owsURL");
t.eq(res[0].typeName, "topp:states",
"Properly parses typeName");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,271 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_read_FeatureInfoResponse(t) {
t.plan(5);
var parser = new OpenLayers.Format.WMSGetFeatureInfo();
// read empty response
var text =
'<?xml version="1.0" encoding="UTF-8" ?>' +
'<FeatureInfoResponse>' +
'</FeatureInfoResponse>';
var features = parser.read(text);
t.eq(features.length, 0,
"Parsing empty FeatureInfoResponse response succesfull");
// read 1 feature
text =
'<?xml version="1.0" encoding="UTF-8" ?>' +
'<FeatureInfoResponse>' +
' <FIELDS OBJECTID="1188" HECTARES="1819.734" ZONENR="5854" NULZONES=" " AREA="18197340.1426" PERIMETER="19177.4073627" SHAPE="NULL" SE_ANNO_CAD_DATA="NULL" SHAPE.AREA="0" SHAPE.LEN="0"/>' +
'</FeatureInfoResponse>';
features = parser.read(text);
t.eq(features.length, 1,
"Parsed 1 feature in total");
t.eq(features[0].attributes.OBJECTID, '1188',
"Attribute OBJECTID contains the right value");
// read multiple features
text =
'<?xml version="1.0" encoding="UTF-8" ?>' +
'<FeatureInfoResponse>' +
' <FIELDS OBJECTID="551" Shape="NULL" NAME="Carbon" STATE_NAME="Wyoming" AREA="7999.91062" POP2000="15639" POP00_SQMI="2" Shape_Length="6.61737274334215" Shape_Area="2.23938983524154"/>' +
' <FIELDS OBJECTID="7" Shape="NULL" AREA="97803.199" STATE_NAME="Wyoming" SUB_REGION="Mtn" STATE_ABBR="WY" POP2000="493782" POP00_SQMI="5" Shape_Length="21.9870297323522" Shape_Area="27.9666881382635"/>' +
' <FIELDS OBJECTID="99" Shape="NULL" LENGTH="378.836" TYPE="Multi-Lane Divided" ADMN_CLASS="Interstate" TOLL_RD="N" RTE_NUM1=" 80" RTE_NUM2=" " ROUTE="Interstate 80" Shape_Length="7.04294883879398"/>' +
'</FeatureInfoResponse>';
features = parser.read(text);
t.eq(features.length, 3,
"Parsed 3 features in total");
t.eq(features[1].attributes.STATE_NAME, 'Wyoming',
"Attribute STATE_NAME contains the right value");
}
function test_read_msGMLOutput(t) {
t.plan(7);
var parser = new OpenLayers.Format.WMSGetFeatureInfo();
// read empty response
var text =
'<?xml version="1.0" encoding="ISO-8859-1"?>' +
'<msGMLOutput ' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:xlink="http://www.w3.org/1999/xlink"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'</msGMLOutput>';
var features = parser.read(text);
t.eq(features.length, 0,
"Parsing empty msGMLOutput response succesfull");
// read 1 feature from 1 layer
text =
'<?xml version="1.0" encoding="ISO-8859-1"?>' +
'<msGMLOutput ' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:xlink="http://www.w3.org/1999/xlink"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
' <AAA64_layer>' +
' <AAA64_feature>' +
' <gml:boundedBy>' +
' <gml:Box srsName="EPSG:28992">' +
' <gml:coordinates>107397.266000,460681.063000 116568.188000,480609.250000</gml:coordinates>' +
' </gml:Box>' +
' </gml:boundedBy>' +
' <OBJECTID>109</OBJECTID>' +
' <ROUTE>N231</ROUTE>' +
' <ROUTE_CH>#N231</ROUTE_CH>' +
' <COUNT>2</COUNT>' +
' <BEHEERDER>P</BEHEERDER>' +
' <LENGTH>28641.7</LENGTH>' +
' <SHAPE>&lt;shape&gt;</SHAPE>' +
' <SE_ANNO_CAD_DATA>&lt;null&gt;</SE_ANNO_CAD_DATA>' +
' </AAA64_feature>' +
' </AAA64_layer>' +
'</msGMLOutput>';
features = parser.read(text);
t.eq(features.length, 1,
"Parsed 1 feature in total");
t.eq(features[0].attributes.OBJECTID, '109',
"Attribute OBJECTID contains the right value");
t.eq(features[0].type, 'AAA64',
"Parsed the layer name correctly");
// read 2 features from 2 layers
text =
'<?xml version="1.0" encoding="ISO-8859-1"?>' +
'<msGMLOutput ' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:xlink="http://www.w3.org/1999/xlink"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
' <AAA64_layer>' +
' <AAA64_feature>' +
' <gml:boundedBy>' +
' <gml:Box srsName="EPSG:28992">' +
' <gml:coordinates>129799.109000,467950.250000 133199.906000,468904.063000</gml:coordinates>' +
' </gml:Box>' +
' </gml:boundedBy>' +
' <OBJECTID>287</OBJECTID>' +
' <ROUTE>N403</ROUTE>' +
' <ROUTE_CH>#N403</ROUTE_CH>' +
' <COUNT>1</COUNT>' +
' <BEHEERDER>P</BEHEERDER>' +
' <LENGTH>4091.25</LENGTH>' +
' <SHAPE>&lt;shape&gt;</SHAPE>' +
' <SE_ANNO_CAD_DATA>&lt;null&gt;</SE_ANNO_CAD_DATA>' +
' </AAA64_feature>' +
' </AAA64_layer>' +
' <AAA62_layer>' +
' <AAA62_feature>' +
' <gml:boundedBy>' +
' <gml:Box srsName="EPSG:28992">' +
' <gml:coordinates>129936.000000,468362.000000 131686.000000,473119.000000</gml:coordinates>' +
' </gml:Box>' +
' </gml:boundedBy>' +
' <OBJECTID>1251</OBJECTID>' +
' <VWK_ID>1515</VWK_ID>' +
' <VWK_BEGDTM>00:00:00 01/01/1998</VWK_BEGDTM>' +
' <VWJ_ID_BEG>1472</VWJ_ID_BEG>' +
' <VWJ_ID_END>1309</VWJ_ID_END>' +
' <VAKTYPE>D</VAKTYPE>' +
' <VRT_CODE>227</VRT_CODE>' +
' <VRT_NAAM>Vecht</VRT_NAAM>' +
' <VWG_NR>2</VWG_NR>' +
' <VWG_NAAM>Vecht</VWG_NAAM>' +
' <BEGKM>18.25</BEGKM>' +
' <ENDKM>23.995</ENDKM>' +
' <LENGTH>5745.09</LENGTH>' +
' <SHAPE>&lt;shape&gt;</SHAPE>' +
' <SE_ANNO_CAD_DATA>&lt;null&gt;</SE_ANNO_CAD_DATA>' +
' </AAA62_feature>' +
' </AAA62_layer>' +
'</msGMLOutput>';
features = parser.read(text);
t.eq(features.length, 2,
"Parsed 2 features in total");
t.eq((features[0].type == features[1].type), false,
"The layer name differs for the two features");
text =
'<?xml version="1.0" encoding="ISO-8859-1"?>' +
'<msGMLOutput ' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:xlink="http://www.w3.org/1999/xlink"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
' <wegbeheerderinfo_layer>' +
' <wegbeheerderinfo_feature>' +
' <gml:boundedBy>' +
' <gml:Box srsName="EPSG:28992">' +
' <gml:coordinates>105002.943000,490037.863000 105271.523000,490262.208000</gml:coordinates>' +
' </gml:Box>' +
' </gml:boundedBy>' +
' <geometry>' +
' <gml:MultiLineString srsName="EPSG:28992">' +
' <gml:lineStringMember>' +
' <gml:LineString>' +
' <gml:coordinates>105270.164000,490262.208000 105098.274000,490258.040000 105028.045000,490089.576000 105002.943000,490048.851000 105049.666000,490037.863000 105271.523000,490064.957000 </gml:coordinates>' +
' </gml:LineString>' +
' </gml:lineStringMember>' +
' </gml:MultiLineString>' +
' </geometry>' +
' <OGR_FID>203327</OGR_FID>' +
' </wegbeheerderinfo_feature>' +
' </wegbeheerderinfo_layer>' +
'</msGMLOutput>';
features = parser.read(text);
t.eq((features[0].geometry instanceof OpenLayers.Geometry.MultiLineString), true,
"Parsed geometry is of type multi line string");
}
function test_read_GMLFeatureInfoResponse(t) {
t.plan(4);
var parser = new OpenLayers.Format.WMSGetFeatureInfo();
// read Ionic response, see if parser falls back to GML format
// url used:
/* http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA?service=WMS&request=GetFeatureInfo&layers=roads&version=1.1.1&bbox=-71.1,42.25,-71.05,42.3&width=500&height=500&format=image/png&SRS=EPSG:4326&styles=&x=174&y=252&query_layers=roads&info_format=application/vnd.ogc.gml */
var text =
"<?xml version='1.0' encoding='utf-8' ?>" +
' <ogcwfs:FeatureCollection xsi:schemaLocation="http://www.ionicsoft.com/wfs http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA?REQUEST=DescribeAllFeatureType&amp;SERVICE=WFS http://www.opengis.net/wfs http://webservices.ionicsoft.com/ionicweb/wfs/BOSTON_ORA/REQUEST/get/DATA/LPR/wfs/1.0.0/WFS-basic.xsd" xmlns:wfs="http://www.ionicsoft.com/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ogcwfs="http://www.opengis.net/wfs">' +
' <gml:boundedBy>' +
' <gml:Box srsName="EPSG:4326">' +
' <gml:coordinates>-71.08301710045646,42.27320863544783 -71.08020014900377,42.27480054530114</gml:coordinates>' +
' </gml:Box>' +
' </gml:boundedBy>' +
' <gml:featureMember>' +
' <wfs:roads fid="roads.9453.0">' +
' <wfs:FNODE_>8943.0</wfs:FNODE_>' +
' <wfs:TNODE_>9070.0</wfs:TNODE_>' +
' <wfs:LPOLY_>0.0</wfs:LPOLY_>' +
' <wfs:RPOLY_>0.0</wfs:RPOLY_>' +
' <wfs:LENGTH>306.875</wfs:LENGTH>' +
' <wfs:MRD_>13109.0</wfs:MRD_>' +
' <wfs:MRD_ID>9453.0</wfs:MRD_ID>' +
' <wfs:TILE_NAME>126</wfs:TILE_NAME>' +
' <wfs:COUNTYCODE>M</wfs:COUNTYCODE>' +
' <wfs:SERIAL_NUM>26000.0</wfs:SERIAL_NUM>' +
' <wfs:CLASS>5.0</wfs:CLASS>' +
' <wfs:ADMIN_TYPE>0.0</wfs:ADMIN_TYPE>' +
' <wfs:ALTRT1TYPE>0.0</wfs:ALTRT1TYPE>' +
' <wfs:STREETNAME>DOCTOR MARY MOORE BEATTY CIRCLE</wfs:STREETNAME>' +
' <wfs:CSN>M 26000</wfs:CSN>' +
' <wfs:GEOMETRY>' +
' <gml:LineString srsName="EPSG:4326">' +
' <gml:coordinates>-71.08300668868151,42.27480054530114 -71.08155305289881,42.27452010256956 -71.08021063085208,42.27320863544783</gml:coordinates>' +
' </gml:LineString>' +
' </wfs:GEOMETRY>' +
' </wfs:roads>' +
' </gml:featureMember>' +
' </ogcwfs:FeatureCollection>';
var features = parser.read(text);
t.eq(features.length, 1,
"Parsing GML GetFeatureInfo response from Ionic succesfull");
t.eq(features[0].attributes.TILE_NAME, '126',
"Attribute TILE_NAME contains the right value");
// read Geoserver response
// taken from:
/* http://demo.opengeo.org/geoserver/wms?service=WMS&request=GetFeatureInfo&layers=opengeo:roads&query_layers=opengeo:roads&format=image/png&version=1.1.1&styles=&bbox=-103.9,44.4,-103.7,44.5&srs=EPSG:4326&width=500&height=500&x=158&y=98&info_format=application/vnd.ogc.gml*/
text = '<?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns="http://www.opengis.net/wfs" xmlns:wfs="http://www.opengis.net/wfs" xmlns:opengeo="http://opengeo.org" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://opengeo.org http://demo.opengeo.org:80/geoserver/wfs?service=WFS&amp;version=1.0.0&amp;request=DescribeFeatureType&amp;typeName=opengeo:roads http://www.opengis.net/wfs http://demo.opengeo.org:80/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd"><gml:boundedBy><gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#26713"><gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">591943.9375,4925605 593045.625,4925845</gml:coordinates></gml:Box></gml:boundedBy><gml:featureMember><opengeo:roads fid="roads.90"><opengeo:cat>3</opengeo:cat><opengeo:label>secondary highway, hard surface</opengeo:label><opengeo:the_geom><gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#26713"><gml:lineStringMember><gml:LineString><gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">593045.60746465,4925605.0059156 593024.32382915,4925606.79305411 592907.54863574,4925624.85647524 592687.35111096,4925670.76834012 592430.76279218,4925678.79393165 592285.97636109,4925715.70811767 592173.39165655,4925761.83511156 592071.1753393,4925793.95523514 591985.96972625,4925831.59842486 591943.98769455,4925844.93220071</gml:coordinates></gml:LineString></gml:lineStringMember></gml:MultiLineString></opengeo:the_geom></opengeo:roads></gml:featureMember></wfs:FeatureCollection>';
features = parser.read(text);
t.eq(features.length, 1,
"Parsing GML GetFeatureInfo response from Geoserver succesfull");
t.eq(features[0].attributes.cat, '3',
"Attribute cat contains the right value");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,834 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var text =
'<?xml version="1.0"?>' +
'<ol:root xmlns="http://namespace.default.net" ' +
'xmlns:ol="http://namespace.openlayers.org" ' +
'xmlns:ta="http://namespace.testattribute.net">' +
'<ol:child ta:attribute="value1" ' +
'attribute="value2">' +
'junk1' +
'<' + '/ol:child>' +
'<ol:child>junk2<' + '/ol:child>' +
'<ol:child>junk3<' + '/ol:child>' +
'<element>junk4<' + '/element>' +
'<ol:element>junk5<' + '/ol:element>' +
'<ol:p>' +
'<ol:a>junk' +
'<' + '/ol:a>' +
'<ol:b>junk' +
'<' + '/ol:b>' +
'<ol:a>junk' +
'<' + '/ol:a>' +
'<' + '/ol:p>' +
'<' + '/ol:root>';
function test_Format_XML_constructor(t) {
t.plan(13);
var options = {'foo': 'bar'};
var format = new OpenLayers.Format.XML(options);
t.ok(format instanceof OpenLayers.Format.XML,
"new OpenLayers.Format.XML returns object" );
t.eq(format.foo, "bar", "constructor sets options correctly");
t.eq(typeof format.read, "function", "format has a read function");
t.eq(typeof format.write, "function", "format has a write function");
t.ok(!window.ActiveXObject || format.xmldom, "browsers with activeX must have xmldom");
// test namespaces
t.ok(format.namespaces instanceof Object, "format has namespace object");
var namespaces = {"foo": "bar"};
format = new OpenLayers.Format.XML({namespaces: namespaces});
t.eq(format.namespaces, namespaces, "format.namespaces correctly set in constructor");
// test default prefix
t.eq(format.defaultPrefix, null, "defaultPrefix is null by default");
format = new OpenLayers.Format.XML({defaultPrefix: "foo"});
t.eq(format.defaultPrefix, "foo", "defaultPrefix correctly set in constructor");
// test readers
t.ok(format.readers instanceof Object, "format has readers object");
var readers = {"foo": "bar"};
format = new OpenLayers.Format.XML({readers: readers});
t.eq(format.readers, readers, "format.readers correctly set in constructor");
// test readers
t.ok(format.writers instanceof Object, "format has writers object");
var writers = {"foo": "bar"};
format = new OpenLayers.Format.XML({writers: writers});
t.eq(format.writers, writers, "format.writers correctly set in constructor");
}
function test_destroy(t) {
t.plan(1);
var format = new OpenLayers.Format.XML();
format.destroy();
t.eq(format.xmldom, null, "xmldom set to null for all browsers");
}
function test_Format_XML_read(t) {
var format = new OpenLayers.Format.XML();
t.plan(format.xmldom ? 10 : 9);
var doc = format.read(text);
t.eq(doc.nodeType, 9,
"doc has the correct node type");
t.eq(doc.nodeName, "#document",
"doc has the correct node name");
t.ok(doc.documentElement,
"ok to access doc.documentElement");
t.xml_eq(doc.documentElement, text,
"doc.documentElement correctly read");
// read can also be called on the prototype directly
doc = OpenLayers.Format.XML.prototype.read(text);
t.eq(doc.nodeType, 9,
"doc has the correct node type");
t.eq(doc.nodeName, "#document",
"doc has the correct node name");
t.ok(doc.documentElement,
"ok to access doc.documentElement");
t.xml_eq(doc.documentElement, text,
"doc.documentElement correctly read");
// where appropriate, make sure doc is loaded into xmldom property
if(format.xmldom) {
t.xml_eq(format.xmldom.documentElement, text,
"xmldom.documentElement contains equivalent xml");
}
// test equivalence with different namespace alias
var pre1 =
"<pre1:parent xmlns:pre1='http://namespace'>" +
"<pre1:child1>value2</pre1:child1>" +
"<pre1:child2 pre1:attr1='foo'>value2</pre1:child2>" +
"<pre1:child3 chicken:attr='hot' xmlns:chicken='http://soup'/>" +
"</pre1:parent>";
var pre2 =
"<pre2:parent xmlns:pre2='http://namespace'>" +
"<pre2:child1>value2</pre2:child1>" +
"<pre2:child2 pre2:attr1='foo'>value2</pre2:child2>" +
"<pre2:child3 pea:attr='hot' xmlns:pea='http://soup'/>" +
"</pre2:parent>";
var doc1 = format.read(pre1);
t.xml_eq(doc1.documentElement, pre2, "read correctly sets namespaces");
}
function test_Format_XML_write(t) {
t.plan(2);
var format = new OpenLayers.Format.XML();
var doc = format.read(text);
var out = format.write(doc);
out = out.replace(/[\r\n]/g, '');
out = out.replace( /<\?.*\?>/, '')
var expected = text.replace(/<\?.*\?>/, '')
t.eq(expected, out,
"correctly writes an XML DOM doc");
var out = format.write(
format.getElementsByTagNameNS(doc,
"http://namespace.openlayers.org","root")[0]);
out = out.replace(/[\r\n]/g, '');
out = out.replace( /<\?.*\?>/, '')
t.eq(out, expected,
"correctly writes an XML DOM node");
}
function test_Format_XML_createElementNS(t) {
t.plan(5);
var format = new OpenLayers.Format.XML();
var uri = "http://foo.com";
var prefix = "foo";
var localName = "bar";
var qualifiedName = prefix + ":" + name;
var node = format.createElementNS(uri, qualifiedName);
t.eq(node.nodeType, 1,
"node has correct type");
t.eq(node.nodeName, qualifiedName,
"node has correct qualified name");
t.eq(node.prefix, prefix,
"node has correct prefix");
t.eq(node.namespaceURI, uri,
"node has correct namespace uri");
var doc = format.read(text);
if (doc.importNode) {
node = doc.importNode(node, true);
}
t.ok(doc.documentElement.appendChild(node),
"node can be appended to a doc root");
}
function test_Format_XML_createTextNode(t) {
t.plan(4);
var format = new OpenLayers.Format.XML();
var value = Math.random().toString();
var node = format.createTextNode(value);
t.eq(node.nodeType, 3,
"node has correct type");
t.eq(node.nodeName, "#text",
"node has correct name");
t.eq(node.nodeValue, value,
"node has correct value");
var doc = format.read(text);
if (doc.importNode) {
node = doc.importNode(node, true);
}
t.ok(doc.documentElement.appendChild(node),
"node can be appended to a doc root");
}
function test_Format_XML_getElementsByTagNameNS(t) {
t.plan(5);
var format = new OpenLayers.Format.XML();
var olUri = "http://namespace.openlayers.org";
var name = "child";
var doc = format.read(text);
var nodes = format.getElementsByTagNameNS(doc.documentElement,
olUri, name);
t.eq(nodes.length, 3,
"gets correct number of nodes");
var qualifiedName = nodes[0].prefix + ":" + name;
t.eq(nodes[0].nodeName, qualifiedName,
"first node has correct qualified name");
var defaultUri = "http://namespace.default.net";
name = "element";
nodes = format.getElementsByTagNameNS(doc.documentElement,
defaultUri, name);
t.eq(nodes.length, 1,
"gets correct number of nodes in default namespace");
var pList = format.getElementsByTagNameNS(doc.documentElement,
olUri, "p");
t.eq(pList.length, 1, "got one ol:p element");
var p = pList[0];
var aList = format.getElementsByTagNameNS(p, olUri, "a");
t.eq(aList.length, 2, "got two child ol:a elements");
}
function test_Format_XML_getAttributeNodeNS(t) {
t.plan(5);
var format = new OpenLayers.Format.XML();
var doc = format.read(text);
var olUri = "http://namespace.openlayers.org";
var taUri = "http://namespace.testattribute.net";
var localNodeName = "child";
var localAttrName = "attribute";
var nodes = format.getElementsByTagNameNS(doc.documentElement,
olUri, localNodeName);
var attributeNode = format.getAttributeNodeNS(nodes[0],
taUri, localAttrName);
var qualifiedName = attributeNode.prefix + ":" + localAttrName;
t.ok(attributeNode,
"returns non-null value");
t.eq(attributeNode.nodeType, 2,
"attribute node has correct type");
t.eq(attributeNode.nodeName, qualifiedName,
"attribute node has correct qualified name");
t.eq(attributeNode.nodeValue, "value1",
"attribute node has correct value");
var nullAttribute = format.getAttributeNodeNS(nodes[0],
taUri, "nothing");
t.ok(nullAttribute === null,
"returns null for nonexistent attribute");
}
function test_Format_XML_getAttributeNS(t) {
t.plan(2);
var format = new OpenLayers.Format.XML();
var doc = format.read(text);
var olUri = "http://namespace.openlayers.org";
var taUri = "http://namespace.testattribute.net";
var localNodeName = "child";
var localAttrName = "attribute";
var nodes = format.getElementsByTagNameNS(doc.documentElement,
olUri, localNodeName);
var attributeValue = format.getAttributeNS(nodes[0],
taUri, localAttrName);
t.eq(attributeValue, "value1",
"got correct attribute value");
var emptyValue = format.getAttributeNS(nodes[0],
taUri, "nothing");
t.ok(emptyValue === "",
"returns empty string for nonexistent attributes");
}
function test_Format_XML_hasAttributeNS(t) {
t.plan(2);
var format = new OpenLayers.Format.XML();
var doc = format.read(text);
var olUri = "http://namespace.openlayers.org";
var taUri = "http://namespace.testattribute.net";
var localNodeName = "child";
var localAttrName = "attribute";
var nodes = format.getElementsByTagNameNS(doc.documentElement,
olUri, localNodeName);
var found = format.hasAttributeNS(nodes[0], taUri, localAttrName);
t.ok(found === true, "returns true for good attribute");
found = format.hasAttributeNS(nodes[0], taUri, "nothing");
t.ok(found === false, "returns false for bad attribute");
}
function test_namespaces(t) {
t.plan(2);
var format = new OpenLayers.Format.XML({
namespaces: {
"def": "http://example.com/default",
"foo": "http://example.com/foo",
"bar": "http://example.com/bar"
},
defaultPrefix: "def"
});
// test that prototype has not been altered
t.eq(OpenLayers.Format.XML.prototype.namespaces, null,
"setting namespaces at construction does not modify prototype");
// test that namespaceAlias has been set
t.eq(format.namespaceAlias["http://example.com/foo"], "foo",
"namespaceAlias mapping has been set");
}
function test_setNamespace(t) {
t.plan(3);
var format = new OpenLayers.Format.XML();
// test that namespaces is an object
t.ok(format.namespaces instanceof Object, "empty namespace object set");
format.setNamespace("foo", "http://example.com/foo");
t.eq(format.namespaces["foo"], "http://example.com/foo", "alias -> uri mapping set");
t.eq(format.namespaceAlias["http://example.com/foo"], "foo", "uri -> alias mapping set");
}
function test_readChildNodes(t) {
var text = "<?xml version='1.0' encoding='UTF-8'?>" +
"<container xmlns='http://example.com/foo'>" +
"<marker name='my marker 1'>" +
"<position>" +
"<lon>-180</lon>" +
"<lat>90</lat>" +
"</position>" +
"<detail>some text for first marker</detail>" +
"<atom:link xmlns:atom='http://www.w3.org/2005/Atom' href='http://host/path/1'/>" +
"</marker>" +
"<marker name='my marker 2'>" +
"<position>" +
"<lon>180</lon>" +
"<lat>-90</lat>" +
"</position>" +
"<detail>some text for second marker</detail>" +
"<atom:link xmlns:atom='http://www.w3.org/2005/Atom' href='http://host/path/2'/>" +
"</marker>" +
"</container>";
var expect = [
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-180, 90),
{
name: 'my marker 1',
link: 'http://host/path/1',
detail: 'some text for first marker'
}
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(180, -90),
{
name: 'my marker 2',
link: 'http://host/path/2',
detail: 'some text for second marker'
}
)
];
var format = new OpenLayers.Format.XML({
defaultPrefix: "foo",
namespaces: {
"foo": "http://example.com/foo",
"atom": "http://www.w3.org/2005/Atom"
},
readers: {
"foo": {
"container": function(node, obj) {
var list = [];
this.readChildNodes(node, list);
obj.list = list;
},
"marker": function(node, list) {
var feature = new OpenLayers.Feature.Vector();
feature.attributes.name = node.getAttribute("name");
this.readChildNodes(node, feature);
list.push(feature);
},
"position": function(node, feature) {
var obj = {};
this.readChildNodes(node, obj);
feature.geometry = new OpenLayers.Geometry.Point(obj.x, obj.y);
},
"lon": function(node, obj) {
obj.x = this.getChildValue(node);
},
"lat": function(node, obj) {
obj.y = this.getChildValue(node);
},
"detail": function(node, feature) {
feature.attributes.detail = this.getChildValue(node);
}
},
"atom": {
"link": function(node, feature) {
feature.attributes.link = node.getAttribute("href");
}
}
}
});
// convert text to document node
var doc = format.read(text);
// read child nodes to get back some object
var obj = format.readChildNodes(doc);
// start comparing what we got to what we expect
var got = obj.list;
t.plan(11);
t.eq(got.length, expect.length, "correct number of items parsed");
t.eq(got[0].geometry.x, expect[0].geometry.x, "correct x coord parsed for marker 1");
t.eq(got[0].geometry.y, expect[0].geometry.y, "correct y coord parsed for marker 1");
t.eq(got[0].attributes.name, expect[0].attributes.name, "correct name parsed for marker 1");
t.eq(got[0].attributes.detail, expect[0].attributes.detail, "correct detail parsed for marker 1");
t.eq(got[0].attributes.link, expect[0].attributes.link, "correct link parsed for marker 1");
t.eq(got[1].geometry.x, expect[1].geometry.x, "correct x coord parsed for marker 2");
t.eq(got[1].geometry.y, expect[1].geometry.y, "correct y coord parsed for marker 2");
t.eq(got[1].attributes.name, expect[1].attributes.name, "correct name parsed for marker 2");
t.eq(got[1].attributes.detail, expect[1].attributes.detail, "correct detail parsed for marker 2");
t.eq(got[1].attributes.link, expect[1].attributes.link, "correct link parsed for marker 2");
}
function test_writeNode(t) {
var features = [
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-180, 90),
{
name: 'my marker 1',
link: 'http://host/path/1',
detail: 'some text for first marker'
}
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(180, -90),
{
name: 'my marker 2',
link: 'http://host/path/2',
detail: 'some text for second marker'
}
)
];
var expect = "<?xml version='1.0' encoding='UTF-8'?>" +
"<container xmlns='http://example.com/foo'>" +
"<marker name='my marker 1'>" +
"<position>" +
"<lon>-180</lon>" +
"<lat>90</lat>" +
"</position>" +
"<detail>some text for first marker</detail>" +
"<atom:link xmlns:atom='http://www.w3.org/2005/Atom' href='http://host/path/1'/>" +
"</marker>" +
"<marker name='my marker 2'>" +
"<position>" +
"<lon>180</lon>" +
"<lat>-90</lat>" +
"</position>" +
"<detail>some text for second marker</detail>" +
"<atom:link xmlns:atom='http://www.w3.org/2005/Atom' href='http://host/path/2'/>" +
"</marker>" +
"</container>";
var format = new OpenLayers.Format.XML({
defaultPrefix: "foo",
namespaces: {
"foo": "http://example.com/foo",
"atom": "http://www.w3.org/2005/Atom"
},
writers: {
"foo": {
"container": function(features) {
var node = this.createElementNSPlus("container");
var feature;
for(var i=0; i<features.length; ++i) {
feature = features[i];
this.writeNode("marker", features[i], node);
}
return node;
},
"marker": function(feature) {
var node = this.createElementNSPlus("marker", {
attributes: {name: feature.attributes.name}
});
this.writeNode("position", feature.geometry, node);
this.writeNode("detail", feature.attributes.detail, node);
this.writeNode("atom:link", feature.attributes.link, node);
return node;
},
"position": function(geometry) {
var node = this.createElementNSPlus("position");
this.writeNode("lon", geometry.x, node);
this.writeNode("lat", geometry.y, node);
return node;
},
"lon": function(x) {
return this.createElementNSPlus("lon", {
value: x
});
},
"lat": function(y) {
return this.createElementNSPlus("lat", {
value: y
});
},
"detail": function(text) {
return this.createElementNSPlus("detail", {
value: text
});
}
},
"atom": {
"link": function(href) {
return this.createElementNSPlus("atom:link", {
attributes: {href: href}
});
}
}
}
});
t.plan(1);
// test that we get what we expect from writeNode
var got = format.writeNode("container", features);
t.xml_eq(got, expect, "features correctly written");
}
function test_createElementNSPlus(t) {
var format = new OpenLayers.Format.XML({
defaultPrefix: "def",
namespaces: {
"def": "http://example.com/default",
"foo": "http://example.com/foo",
"bar": "http://example.com/bar"
}
});
var cases = [
{
description: "unprefixed name with default options",
node: format.createElementNSPlus("FooNode"),
expect: "<def:FooNode xmlns:def='http://example.com/default'/>"
}, {
description: "def prefixed name with default options",
node: format.createElementNSPlus("def:FooNode"),
expect: "<def:FooNode xmlns:def='http://example.com/default'/>"
}, {
description: "foo prefixed name with default options",
node: format.createElementNSPlus("foo:FooNode"),
expect: "<foo:FooNode xmlns:foo='http://example.com/foo'/>"
}, {
description: "unprefixed name with uri option",
node: format.createElementNSPlus("FooNode", {
uri: "http://example.com/elsewhere"
}),
expect: "<FooNode xmlns='http://example.com/elsewhere'/>"
}, {
description: "foo prefixed name with uri option (overriding format.namespaces)",
node: format.createElementNSPlus("foo:FooNode", {
uri: "http://example.com/elsewhere"
}),
expect: "<foo:FooNode xmlns:foo='http://example.com/elsewhere'/>"
}, {
description: "foo prefixed name with attributes option",
node: format.createElementNSPlus("foo:FooNode", {
attributes: {
"id": "123",
"foo:attr1": "namespaced attribute 1",
"bar:attr2": "namespaced attribute 2"
}
}),
expect: "<foo:FooNode xmlns:foo='http://example.com/foo' xmlns:bar='http://example.com/bar' id='123' foo:attr1='namespaced attribute 1' bar:attr2='namespaced attribute 2'/>"
}, {
description: "foo prefixed name with attributes and value options",
node: format.createElementNSPlus("foo:FooNode", {
attributes: {"id": "123"},
value: "text value"
}),
expect: "<foo:FooNode xmlns:foo='http://example.com/foo' id='123'>text value<" + "/foo:FooNode>"
}, {
description: "value of 0 gets appended as a text node",
node: format.createElementNSPlus("foo:bar", {value: 0}),
expect: "<foo:bar xmlns:foo='http://example.com/foo'>0</foo:bar>"
}, {
description: "value of true gets appended as a text node",
node: format.createElementNSPlus("foo:bar", {value: true}),
expect: "<foo:bar xmlns:foo='http://example.com/foo'>true</foo:bar>"
}, {
description: "value of false gets appended as a text node",
node: format.createElementNSPlus("foo:bar", {value: false}),
expect: "<foo:bar xmlns:foo='http://example.com/foo'>false</foo:bar>"
}, {
description: "null value does not get appended as a text node",
node: format.createElementNSPlus("foo:bar", {value: null}),
expect: "<foo:bar xmlns:foo='http://example.com/foo'/>"
}, {
description: "undefined value does not get appended as a text node",
node: format.createElementNSPlus("foo:bar"),
expect: "<foo:bar xmlns:foo='http://example.com/foo'/>"
}
];
t.plan(cases.length);
var test;
for(var i=0; i<cases.length; ++i) {
test = cases[i];
t.xml_eq(test.node, test.expect, test.description);
}
}
function test_setAttributes(t) {
var format = new OpenLayers.Format.XML({
defaultPrefix: "def",
namespaces: {
"def": "http://example.com/default",
"foo": "http://example.com/foo",
"bar": "http://example.com/bar"
}
});
var cases = [
{
description: "unprefixed attribute",
node: format.createElementNSPlus("foo:Node"),
attributes: {"id": "123"},
expect: "<foo:Node xmlns:foo='http://example.com/foo' id='123'/>"
}, {
description: "foo prefixed attribute",
node: format.createElementNSPlus("foo:Node"),
attributes: {"foo:id": "123"},
expect: "<foo:Node xmlns:foo='http://example.com/foo' foo:id='123'/>"
}, {
description: "foo prefixed attribute with def prefixed node",
node: format.createElementNSPlus("def:Node"),
attributes: {"foo:id": "123"},
expect: "<def:Node xmlns:def='http://example.com/default' xmlns:foo='http://example.com/foo' foo:id='123'/>"
}, {
description: "multiple attributes",
node: format.createElementNSPlus("def:Node"),
attributes: {"id": "123", "foo": "bar"},
expect: "<def:Node xmlns:def='http://example.com/default' id='123' foo='bar'/>"
}
];
t.plan(cases.length);
var test;
for(var i=0; i<cases.length; ++i) {
test = cases[i];
format.setAttributes(test.node, test.attributes);
t.xml_eq(test.node, test.expect, test.description);
}
}
function test_keepData(t) {
t.plan(2);
var options = {'keepData': true};
var format = new OpenLayers.Format.XML(options);
format.read(text);
t.ok(format.data != null, 'data property is not null after read with keepData=true');
t.eq(format.data.documentElement.tagName,'ol:root','keepData keeps the right data');
}
function test_getChildValue(t) {
t.plan(1);
var text =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<root>" +
"x<!-- comment -->y<!-- comment 2 --><![CDATA[z]]>z<foo />&#x79;" +
"</root>";
var format = new OpenLayers.Format.XML();
var doc = format.read(text).documentElement;
t.eq(format.getChildValue(doc), "xyzzy", "child value skips comments, concatenates multiple values, reads through entities");
}
function test_getChildEl(t) {
t.plan(3);
var text =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<root>" +
"<!-- comment -->" +
"<a>x</a>" +
"<b>x</b>" +
"</root>";
var format = new OpenLayers.Format.XML();
var doc = format.read(text).documentElement;
var a = format.getChildEl(doc);
t.eq(a.nodeName, "a", "first element found correctly");
a = format.getChildEl(doc, "a");
t.eq(b, null, "first child element matches the given name");
var b = format.getChildEl(doc, "b");
t.eq(b, null, "first child element does not match the given name");
}
function test_getNextEl(t) {
t.plan(5);
var text =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<root>" +
"<!-- comment -->" +
"<a>x</a>" +
"<!-- comment -->" +
"<b xmlns='urn:example'>x</b>" +
"</root>";
var format = new OpenLayers.Format.XML();
var doc = format.read(text).documentElement;
var a = format.getChildEl(doc);
var b = format.getNextEl(a);
t.eq(b && b.nodeName, "b", "next element correctly found");
b = format.getNextEl(a, "b");
t.eq(b && b.nodeName, "b", "next element correctly found when name supplied");
b = format.getNextEl(a, "c");
t.eq(b, null, "null returned when name does not match next element");
b = format.getNextEl(a, null, "urn:example");
t.eq(b && b.nodeName, "b", "next element correctly found when namespace supplied");
b = format.getNextEl(a, null, "foo");
t.eq(b, null, "null returned when namespace does not match next element");
}
function test_isSimpleContent(t) {
t.plan(2);
var text =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<root>" +
"<!-- comment -->" +
"<a>x<!-- comment -->y<!-- comment 2 --><![CDATA[z]]>z<foo />&#x79;</a>" +
"<!-- comment -->" +
"<b>x<!-- comment -->y<!-- comment 2 --><![CDATA[z]]>z&#x79;</b>" +
"</root>";
var format = new OpenLayers.Format.XML();
var doc = format.read(text).documentElement;
var a = format.getChildEl(doc);
var b = format.getNextEl(a);
t.ok(!format.isSimpleContent(a), "<a> content is not simple");
t.ok(format.isSimpleContent(b), "<b> content is simple");
}
function test_lookupNamespaceURI(t) {
t.plan(8);
var text =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<root xmlns:baz='urn:baznamespace'>" +
"<!-- comment -->" +
"<a><foo /></a>" +
"<!-- comment -->" +
"<b xmlns='urn:example'><!-- comment --><bar foo='value'/></b>" +
"</root>";
var format = new OpenLayers.Format.XML();
var doc = format.read(text).documentElement;
var a = format.getChildEl(doc);
t.eq(format.lookupNamespaceURI(a, "baz"), "urn:baznamespace", "prefix lookup on first child");
var foo = format.getChildEl(a);
t.eq(format.lookupNamespaceURI(foo, "baz"), "urn:baznamespace", "prefix lookup on child of first child");
var b = format.getNextEl(a);
t.eq(format.lookupNamespaceURI(b, null), "urn:example", "default namespace lookup on element");
var bar = format.getChildEl(b);
t.eq(format.lookupNamespaceURI(bar, null), "urn:example", "default namespace lookup on child");
t.eq(format.lookupNamespaceURI(bar, "baz"), "urn:baznamespace", "prefix lookup on child with different default");
// test that the alias behaves properly
var lookup = OpenLayers.Format.XML.lookupNamespaceURI;
t.eq(lookup(bar, "baz"), "urn:baznamespace", "(alias) prefix lookup on child with different default");
var attr = bar.attributes[0];
// Internet Explorer didn't have the ownerElement property until 8.
var supportsOwnerElement = !!attr.ownerElement;
if(supportsOwnerElement) {
t.eq(format.lookupNamespaceURI(attr, null), "urn:example", "default namespace lookup on attribute");
t.eq(format.lookupNamespaceURI(attr, "baz"), "urn:baznamespace", "prefix lookup on attribute with different default");
} else {
t.debug_print("namespace lookup on attributes not supported in this browser");
t.ok(true, "namespace lookup on attributes not supported in this browser");
t.ok(true, "namespace lookup on attributes not supported in this browser");
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,344 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script src="data/geos_wkt_intersects.js"></script>
<script type="text/javascript">
var map;
function test_Geometry_constructor (t) {
t.plan( 2 );
var g = new OpenLayers.Geometry();
t.eq(g.CLASS_NAME, "OpenLayers.Geometry", "correct CLASS_NAME")
t.ok(OpenLayers.String.startsWith(g.id, "OpenLayers.Geometry_"),
"id correctly set");
}
function test_Geometry_clone(t) {
t.plan(2);
var geometry = new OpenLayers.Geometry();
var clone = geometry.clone();
t.eq(clone.CLASS_NAME, "OpenLayers.Geometry", "correct CLASS_NAME")
t.ok(OpenLayers.String.startsWith(clone.id, "OpenLayers.Geometry_"),
"id correctly set");
}
function test_Geometry_setBounds(t) {
t.plan( 2 );
var g = new OpenLayers.Geometry();
//null object
g.setBounds(null);
t.ok(g.bounds == null, "setbounds with null value does not crash or set bounds");
//no classname object
g_clone = {};
var object = {
'clone': function() { return g_clone; }
};
g.setBounds(object);
t.ok(g.bounds == g_clone, "setbounds with valid object sets bounds, calls clone");
}
function test_Geometry_extendBounds(t) {
t.plan(9);
OpenLayers.Bounds.prototype._extend =
OpenLayers.Bounds.prototype.extend;
OpenLayers.Bounds.prototype.extend = function(b) {
g_extendBounds = b;
};
var g = new OpenLayers.Geometry();
//this.bounds null (calculateBounds(), setBounds() called)
g.setBounds = function(b) { g_setBounds = b; };
g.calculateBounds = function() { g_calculateBounds = {}; };
var object = {};
g_setBounds = null;
g_calculateBounds = null;
g_extendBounds = null;
g.extendBounds(object);
t.ok(g_calculateBounds != null, "calculateBounds() called when this.bounds is null");
t.ok(g_setBounds == object, "setBounds() called when this.bounds is null and calculateBounds() is null too");
t.ok(g_extendBounds != object, "this.bounds.extend() not called when this.bounds is null and calculateBounds() is null too");
//this.bounds null (calculateBounds() sets this.bounds:
// - setBounds() not called
// - this.bounds.extend() called
g_calcBounds = new OpenLayers.Bounds(1,2,3,4);
g.calculateBounds = function() {
g_calculateBounds = {};
this.bounds = g_calcBounds;
};
var object = {};
g_setBounds = null;
g_calculateBounds = null;
g_extendBounds = null;
g.extendBounds(object);
t.ok(g_calculateBounds != null, "calculateBounds() called when this.bounds is null");
t.ok(g_setBounds == null, "setBounds() not called when this.bounds is null and calculateBounds() sets this.bounds");
t.ok(g_extendBounds == object, "this.bounds.extend() called when this.bounds is null and calculateBounds() sets this.bounds");
//this.bounds non-null thus extend()
// - setBounds() not called
// - this.bounds.extend() called
g_setBounds = null;
g_calculateBounds = null;
g_extendBounds = null;
g.extendBounds(object);
t.ok(g_calculateBounds == null, "calculateBounds() not called when this.bounds is non null");
t.ok(g_setBounds == null, "setBounds() not called when this.bounds is nonnull");
t.ok(g_extendBounds == object, "this.bounds.extend() called when this.bounds is non-null");
OpenLayers.Bounds.prototype.extend =
OpenLayers.Bounds.prototype._extend;
}
function test_Geometry_getBounds(t) {
t.plan(1);
var g = new OpenLayers.Geometry();
var testBounds = new OpenLayers.Bounds(1,2,3,4);
g.bounds = testBounds.clone();
t.ok(g.getBounds().equals(testBounds), "getBounds works");
}
function test_Geometry_atPoint(t) {
t.plan(6);
var g = new OpenLayers.Geometry();
var lonlat = null;
var lon = 5;
var lat = 10;
//null lonlat
g.bounds = new OpenLayers.Bounds();
var atPoint = g.atPoint(lonlat, lon, lat);
t.ok(!atPoint, "null lonlat")
//null this.bounds
g.bounds = null;
lonlat = new OpenLayers.LonLat(1,2);
atPoint = g.atPoint(lonlat, lon, lat);
t.ok(!atPoint, "null this.bounds")
//toleranceLon/toleranceLat
//default toleranceLon/toleranceLat
OpenLayers.Bounds.prototype._containsLonLat = OpenLayers.Bounds.prototype.containsLonLat;
g_Return = {};
OpenLayers.Bounds.prototype.containsLonLat = function(ll) {
g_bounds = this;
return g_Return;
}
var testBounds = new OpenLayers.Bounds(10,20,30,40);
g.bounds = testBounds.clone();
lonlat = new OpenLayers.LonLat(20,30);
g_bounds = null;
atPoint = g.atPoint(lonlat);
t.ok(g_bounds.equals(testBounds), "default toleranceLon/Lat are 0");
t.ok(atPoint == g_Return, "default toleranceLon/Lat returns correctly");
//real toleranceLon/toleranceLat
var testBounds = new OpenLayers.Bounds(10,20,30,40);
g.bounds = testBounds.clone();
lonlat = new OpenLayers.LonLat(20,30);
g_bounds = null;
atPoint = g.atPoint(lonlat, lon, lat);
testBounds.left -= lon;
testBounds.bottom -= lat;
testBounds.right += lon;
testBounds.top += lat;
t.ok(g_bounds.equals(testBounds), "real toleranceLon/Lat are 0");
t.ok(atPoint == g_Return, "real toleranceLon/Lat returns correctly");
OpenLayers.Bounds.prototype.containsLonLat = OpenLayers.Bounds.prototype._containsLonLat;
}
function test_Geometry_getLength(t) {
t.plan(1);
var g = new OpenLayers.Geometry();
t.eq(g.getLength(), 0, "getLength is 0");
}
function test_Geometry_getArea(t) {
t.plan(1);
var g = new OpenLayers.Geometry();
t.eq(g.getArea(), 0, "getArea is 0");
}
function test_Geometry_clearBounds(t) {
t.plan(2);
var g = new OpenLayers.Geometry();
g.parent = new OpenLayers.Geometry();
g.bounds = "foo";
g.parent.bounds = "bar";
g.clearBounds();
t.ok(g.bounds == null, "bounds is correctly cleared");
t.ok(g.parent.bounds == null, "parent geometry bounds is correctly cleared");
}
function test_Geometry_destroy(t) {
t.plan( 2 );
var g = new OpenLayers.Geometry();
g.bounds = new OpenLayers.Bounds();
g_style_destroy = null;
g.destroy();
t.eq(g.id, null, "id nullified");
t.eq(g.bounds, null, "bounds nullified");
}
function test_Geometry_intersects_geos_wkt(t) {
var wkt = new OpenLayers.Format.WKT();
var failures = [];
var intersect12, intersect21, msg;
for (var i = 0; i < geos_test_data.length; i++) {
var testcase = geos_test_data[i];
f1 = wkt.read(testcase['wkt1']);
f2 = wkt.read(testcase['wkt2']);
intersect12 = f1.geometry.intersects(f2.geometry);
intersect21 = f2.geometry.intersects(f1.geometry);
if(intersect12 != testcase.result) {
msg = "f1 should " + (testcase.result ? "" : "not ") +
"intersect f2: f1 = '" + testcase['wkt1'] + "' " +
"f2 = '" + testcase['wkt2'] + "'";
failures.push(msg);
}
if(intersect21 != testcase.result) {
msg = "f2 should " + (testcase.result ? "" : "not ") +
"intersect f1: f1 = '" + testcase['wkt1'] + "' " +
"f2 = '" + testcase['wkt2'] + "'";
failures.push(msg);
}
}
if(failures.length == 0) {
t.plan(1);
t.ok(true, "all " + geos_test_data.length + " geos tests pass");
} else {
t.plan(failures.length);
for(var f=0; f<failures.length; ++f) {
t.fail(failures[f]);
}
}
}
function test_distanceToSegment(t) {
var dist = OpenLayers.Geometry.distanceToSegment;
var cases = [{
got: dist({x: 0, y: 0}, {x1: 0, y1: 1, x2: 1, y2: 1}),
expected: {distance: 1, x: 0, y: 1}
}, {
got: dist({x: 0, y: 0}, {x1: -1, y1: -1, x2: 0, y2: -1}),
expected: {distance: 1, x: 0, y: -1}
}, {
got: dist({x: 0, y: 0}, {x1: -1, y1: -1, x2: 1, y2: 1}),
expected: {distance: 0, x: 0, y: 0}
}, {
got: dist({x: 1, y: 1}, {x1: 2, y1: 0, x2: 2, y2: 3}),
expected: {distance: 1, x: 2, y: 1}
}, {
got: dist({x: -1, y: -1}, {x1: -2, y1: -2, x2: -1, y2: -3}),
expected: {distance: Math.sqrt(2), x: -2, y: -2}
}, {
got: dist({x: -1, y: 1}, {x1: -3, y1: 1, x2: -1, y2: 3}),
expected: {distance: Math.sqrt(2), x: -2, y: 2}
}];
t.plan(cases.length);
for(var i=0; i<cases.length; ++i) {
t.eq(cases[i].got, cases[i].expected, "case " + i);
}
}
function test_fromWKT(t) {
var cases = [{
wkt: "POINT(1 2)",
geom: new OpenLayers.Geometry.Point(1, 2)
}, {
wkt: "MULTIPOINT(3.5 5.6,4.8 10.5)",
geom: new OpenLayers.Geometry.MultiPoint([
new OpenLayers.Geometry.Point(3.5, 5.6),
new OpenLayers.Geometry.Point(4.8, 10.5)
])
}, {
wkt: "LINESTRING(1 2, 3 4)",
geom: new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(1, 2),
new OpenLayers.Geometry.Point(3, 4)
])
}, {
wkt: "POLYGON((0 0, 0 4, 4 4, 4 0, 0 0),(1 1, 1 3, 3 3, 3 1, 1 1))",
geom: new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(0, 0),
new OpenLayers.Geometry.Point(0, 4),
new OpenLayers.Geometry.Point(4, 4),
new OpenLayers.Geometry.Point(4, 0),
new OpenLayers.Geometry.Point(0, 0)
]),
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(1, 1),
new OpenLayers.Geometry.Point(1, 3),
new OpenLayers.Geometry.Point(3, 3),
new OpenLayers.Geometry.Point(3, 1),
new OpenLayers.Geometry.Point(1, 1)
])
])
}, {
wkt: "GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))",
geom: new OpenLayers.Geometry.Collection([
new OpenLayers.Geometry.Point(4, 6),
new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(4, 6),
new OpenLayers.Geometry.Point(7, 10)
])
])
}];
t.plan(cases.length);
var wkt = OpenLayers.Geometry.fromWKT;
for(var i=0; i<cases.length; ++i) {
t.geom_eq(wkt(cases[i].wkt), cases[i].geom, "case " + i);
}
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,270 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var coll;
function test_Collection_constructor (t) {
t.plan( 4 );
//null param
coll = new OpenLayers.Geometry.Collection();
t.ok( coll instanceof OpenLayers.Geometry.Collection, "new OpenLayers.Geometry.Collection returns coll object" );
t.eq( coll.CLASS_NAME, "OpenLayers.Geometry.Collection", "coll.CLASS_NAME is set correctly");
t.eq( coll.components.length, 0, "coll.components is set correctly");
OpenLayers.Geometry.Collection.prototype._addComponents =
OpenLayers.Geometry.Collection.prototype.addComponents;
OpenLayers.Geometry.Collection.prototype.addComponents =
function(comps) { g_addcomponents = comps; };
//valid param
g_addcomponents = null;
var components = {};
coll = new OpenLayers.Geometry.Collection(components);
t.ok(g_addcomponents, components, "addcomponents called on non-null param")
OpenLayers.Geometry.Collection.prototype.addComponents =
OpenLayers.Geometry.Collection.prototype._addComponents;
}
function test_Collection_addComponents (t) {
t.plan( 10 );
coll = new OpenLayers.Geometry.Collection();
//null
coll.addComponents(null);
t.ok(true, "doesn't break on add null components");
OpenLayers.Geometry.Collection.prototype._addComponent =
OpenLayers.Geometry.Collection.prototype.addComponent;
OpenLayers.Geometry.Collection.prototype.addComponent =
function(comp) { g_addComp = comp; g_added++};
//nonarray argument
var g_added = 0;
var g_addComp = 0;
var component = {};
coll.addComponents(component);
t.eq(g_added, 1, "added once");
t.eq(g_addComp, component, "added component");
//array arg
var g_added = 0;
var g_addComp = 0;
var component1 = {};
var component2 = {};
coll.addComponents([component1, component2]);
t.eq(g_added, 2, "added twice");
t.eq(g_addComp, component2, "added component");
OpenLayers.Geometry.Collection.prototype.addComponent =
OpenLayers.Geometry.Collection.prototype._addComponent;
coll.addComponents(new OpenLayers.Geometry.Point(0,0));
coll.addComponents(new OpenLayers.Geometry.Point(10,10));
t.eq( coll.components.length, 2, "added two components to collection" );
bounds = coll.getBounds();
t.eq( bounds.left, 0, "left bound is 0" );
t.eq( bounds.bottom, 0, "bottom bound is 0" );
t.eq( bounds.right, 10, "right bound is 10" );
t.eq( bounds.top, 10, "top bound is 10" );
}
function test_Collection_clone (t) {
t.plan( 3 );
coll = new OpenLayers.Geometry.Collection();
coll.addComponents(new OpenLayers.Geometry.Point(0,0));
coll.addComponents(new OpenLayers.Geometry.Point(10,10));
coll2 = coll.clone();
t.ok( coll2 instanceof OpenLayers.Geometry.Collection, "coll.clone() returns collection object" );
t.eq( coll2.components.length, 2, "coll2.components.length is set correctly");
t.ok( coll2.components[0] instanceof OpenLayers.Geometry.Point,
"coll2.components.length is set correctly");
}
function test_Collection_removeComponents (t) {
t.plan( 5 );
coll = new OpenLayers.Geometry.Collection();
point = new OpenLayers.Geometry.Point(0,0);
coll.addComponents(point);
coll.addComponents(new OpenLayers.Geometry.Point(10,10));
coll.removeComponents(coll.components[0]);
t.eq( coll.components.length, 1, "coll.components.length is smaller after removeComponent" );
t.ok( coll.bounds == null, "bounds are nullified after call to remove (to trigger recalc on getBounds()");
bounds = coll.getBounds();
t.eq( bounds.left, 10, "left bound is 10 after removeComponent" );
t.eq( bounds.bottom, 10, "bottom bound is 10 after removeComponent" );
coll = new OpenLayers.Geometry.Collection();
for(var i=0; i<5; ++i) {
coll.addComponents(
new OpenLayers.Geometry.Point(Math.random(), Math.random())
);
}
coll.removeComponents(coll.components);
t.eq(coll.components.length, 0,
"remove components even works with multiple components");
}
function test_Collection_calculateBounds(t) {
t.plan( 9 );
var coll = new OpenLayers.Geometry.Collection();
coll.calculateBounds();
t.eq(coll.bounds, null, "null components list gives null bounds on calculation()");
var p1 = new OpenLayers.Geometry.Point(10,20);
var p2 = new OpenLayers.Geometry.Point(30,40);
var components = [p1, p2];
coll = new OpenLayers.Geometry.Collection(components);
coll.calculateBounds();
t.eq(coll.bounds.left, 10, "good left bounds");
t.eq(coll.bounds.bottom, 20, "good bottom bounds");
t.eq(coll.bounds.right, 30, "good right bounds");
t.eq(coll.bounds.top, 40, "good top bounds");
var newPoint = new OpenLayers.Geometry.Point(60,70);
coll.addComponent(newPoint);
coll.calculateBounds();
t.eq(coll.bounds.left, 10, "good left bounds");
t.eq(coll.bounds.bottom, 20, "good bottom bounds");
t.eq(coll.bounds.right, 60, "good right bounds");
t.eq(coll.bounds.top, 70, "good top bounds");
}
function test_Collection_equals(t) {
t.plan(1);
var geom = new OpenLayers.Geometry.Collection();
t.ok(!geom.equals(), "collection.equals() returns false for undefined");
}
function test_Collection_addComponent(t) {
t.plan(10);
var coll = new OpenLayers.Geometry.Collection();
//null
coll.addComponent(null);
t.ok(!coll.addComponent(null),
"addComponent returns false for bad component")
//good component
var component = new OpenLayers.Geometry.Point(3,4);
t.ok(coll.addComponent(component),
"addComponent returns true for good component");
t.ok(coll.bounds == null, "bounds cache correctly cleared");
var foundComponent = false;
for(var i=0; i< coll.components.length; i++) {
if (coll.components[i].equals(component)) {
foundComponent = true;
}
}
t.ok(foundComponent, "component added to internal array");
// restricted components
coll.componentTypes = ["OpenLayers.Geometry.Point",
"OpenLayers.Geometry.LineString"];
var point1 = new OpenLayers.Geometry.Point(0,0);
var point2 = new OpenLayers.Geometry.Point(1,1);
var line = new OpenLayers.Geometry.LineString([point1, point2]);
var multipoint = new OpenLayers.Geometry.MultiPoint([point1, point2]);
t.ok(coll.addComponent(point1),
"addComponent returns true for 1st geometry type in componentTypes");
t.ok(OpenLayers.Util.indexOf(coll.components, point1) > -1,
"addComponent adds 1st restricted type to components array");
t.ok(coll.addComponent(line),
"addComponent returns true for 2nd geometry type in componentTypes");
t.ok(OpenLayers.Util.indexOf(coll.components, point1) > -1,
"addComponent adds 2nd restricted type to components array");
t.ok(!coll.addComponent(multipoint),
"addComponent returns false for geometry type not in componentTypes");
t.ok(OpenLayers.Util.indexOf(coll.components, multipoint) == -1,
"addComponent doesn't add restricted type to component array");
}
function test_collection_getLength(t) {
t.plan(2);
//null
var coll = new OpenLayers.Geometry.Collection();
t.eq( coll.getLength(), 0, "null coll has 0 getlength");
//valid
coll.components = [
{ 'getLength': function() { return 50; } },
{ 'getLength': function() { return 15; } }
];
t.eq( coll.getLength(), 65, "coll with valid components correctly sums getlength");
}
function test_collection_getArea(t) {
t.plan(2);
//null
var coll = new OpenLayers.Geometry.Collection();
t.eq( coll.getArea(), 0, "null coll has 0 getArea");
//valid
coll.components = [
{ 'getArea': function() { return 50; } },
{ 'getArea': function() { return 15; } }
];
t.eq( coll.getArea(), 65, "coll with valid components correctly sums getArea");
}
function test_transform(t) {
t.plan(5);
var p1 = new OpenLayers.Geometry.Point(0,0);
p1.bounds = "foo";
var p2 = new OpenLayers.Geometry.Point(1,1);
p2.bounds = "foo";
var line = new OpenLayers.Geometry.LineString([p1, p2]);
var multipoint = new OpenLayers.Geometry.MultiPoint([p1, p2]);
var coll = new OpenLayers.Geometry.Collection([
p1, p2, line, multipoint
]);
coll.bounds = "foo";
var wgs84 = new OpenLayers.Projection("EPSG:4326");
var sm = new OpenLayers.Projection("EPSG:900913");
coll.transform(wgs84, sm);
t.eq(coll.bounds, null, "coll bounds cleared");
t.eq(p1.bounds, null, "p1 component bounds cleared");
t.eq(p2.bounds, null, "p2 component bounds cleared");
t.eq(line.bounds, null, "line component bounds cleared");
t.eq(multipoint.bounds, null, "multipoint component bounds cleared");
}
function test_Collection_destroy(t) {
t.plan( 1 );
coll = new OpenLayers.Geometry.Collection();
coll.components = {};
coll.destroy();
t.ok(coll.components == null, "components array cleared");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,157 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var curve;
var components = [new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(0,0)];
function test_Curve_constructor (t) {
t.plan( 3 );
curve = new OpenLayers.Geometry.Curve();
t.ok( curve instanceof OpenLayers.Geometry.Curve, "new OpenLayers.Geometry.Curve returns curve object" );
t.eq( curve.CLASS_NAME, "OpenLayers.Geometry.Curve", "curve.CLASS_NAME is set correctly");
t.eq( curve.components, [], "curve.components is set correctly");
}
function test_Curve_constructor (t) {
t.plan( 2 );
curve = new OpenLayers.Geometry.Curve(components);
t.ok( curve instanceof OpenLayers.Geometry.Curve, "new OpenLayers.Geometry.Curve returns curve object" );
t.eq( curve.components.length, 2, "curve.components.length is set correctly");
}
function test_Curve_clone (t) {
t.plan( 2 );
curve = new OpenLayers.Geometry.Curve(components);
curve2 = curve.clone();
t.ok( curve2 instanceof OpenLayers.Geometry.Curve, "curve.clone() returns curve object" );
t.eq( curve2.components.length, 2, "curve2.components.length is set correctly");
}
function test_Curve_calculateBounds(t) {
t.plan( 17 );
var curve = new OpenLayers.Geometry.Curve();
curve.calculateBounds();
t.eq(curve.bounds, null, "bounds null when no components");
var p1 = new OpenLayers.Geometry.Point(10,20);
var p2 = new OpenLayers.Geometry.Point(30,40);
var components = [p1, p2];
var curve = new OpenLayers.Geometry.Curve(components);
curve.calculateBounds();
t.eq(curve.bounds.left, 10, "good left bounds");
t.eq(curve.bounds.bottom, 20, "good bottom bounds");
t.eq(curve.bounds.right, 30, "good right bounds");
t.eq(curve.bounds.top, 40, "good top bounds");
var newPoint = new OpenLayers.Geometry.Point(60,70);
curve.addComponent(newPoint);
curve.calculateBounds();
t.eq(curve.bounds.left, 10, "good left bounds");
t.eq(curve.bounds.bottom, 20, "good bottom bounds");
t.eq(curve.bounds.right, 60, "good right bounds");
t.eq(curve.bounds.top, 70, "good top bounds");
//nullifying the bounds
//before calculation
curve = new OpenLayers.Geometry.Curve(components);
curve.bounds = null;
curve.calculateBounds();
t.eq(curve.bounds.left, 10, "good left bounds");
t.eq(curve.bounds.bottom, 20, "good bottom bounds");
t.eq(curve.bounds.right, 30, "good right bounds");
t.eq(curve.bounds.top, 40, "good top bounds");
//before addComponent
curve.bounds = null;
curve.addComponent(newPoint);
curve.calculateBounds();
t.eq(curve.bounds.left, 10, "good left bounds");
t.eq(curve.bounds.bottom, 20, "good bottom bounds");
t.eq(curve.bounds.right, 60, "good right bounds");
t.eq(curve.bounds.top, 70, "good top bounds");
}
function test_Curve_addComponent (t) {
t.plan( 8 );
curve = new OpenLayers.Geometry.Curve(components);
curve.addComponent(new OpenLayers.Geometry.Point(20,30));
bounds = curve.getBounds();
t.eq( curve.components.length, 3, "new point added to array" );
t.eq( bounds.top, 30, "top bound is 30 after addComponent" );
t.eq( bounds.right, 20, "right bound is 20 after addComponent" );
curve.addComponent(new OpenLayers.Geometry.Point(-20,-30), 1);
bounds = curve.getBounds();
t.eq( curve.components.length, 4, "new point added to array" );
t.eq( bounds.bottom, -30, "bottom bound is -30 after 2nd addComponent" );
t.eq( bounds.left, -20, "left bound is 20 after 2nd addComponent" );
t.eq( curve.components[1].x, -20, "new point.lon is -20 (index worked)" );
t.eq( curve.components[1].y, -30, "new point.lat is -30 (index worked)" );
}
function test_Curve_removeComponent (t) {
t.plan( 4 );
curve = new OpenLayers.Geometry.Curve(components);
curve.removeComponent(curve.components[1]);
t.eq( curve.components.length, 1, "curve.components.length is smaller after removeComponent" );
t.eq( curve.bounds, null, "curve.bounds nullified after removeComponent (for recalculation)" );
bounds = curve.getBounds();
t.eq( bounds.left, 10, "left bound is 10 after removeComponent" );
t.eq( bounds.bottom, 10, "bottom bound is 10 after removeComponent" );
}
function test_Curve_getLength (t) {
t.plan( 4 );
//no components
curve = new OpenLayers.Geometry.Curve();
curve.components = null;
t.eq(curve.getLength(), 0, "curve with no components has length 0");
//empty components
curve.components = [];
t.eq(curve.getLength(), 0, "curve with empty components has length 0");
//single point curve
curve.components = [ new OpenLayers.Geometry.Point(0,0) ];
t.eq(curve.getLength(), 0, "curve with only one point has length 0");
//multipoint
var newcomponents = [ new OpenLayers.Geometry.Point(0,0),
new OpenLayers.Geometry.Point(0,10),
new OpenLayers.Geometry.Point(20,10),
new OpenLayers.Geometry.Point(20,-10)
];
curve = new OpenLayers.Geometry.Curve(newcomponents);
t.eq(curve.getLength(), 50, "curve.getLength returns a reasonably accurate length" );
}
function test_Curve_destroy(t) {
t.plan(1);
var curve = new OpenLayers.Geometry.Curve();
curve.components = {};
curve.destroy();
t.ok( curve.components == null, "components is cleared well in destruction");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,383 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var line;
var components = [new OpenLayers.Geometry.Point(10,15),
new OpenLayers.Geometry.Point(0,0)];
function test_LineString_constructor (t) {
t.plan( 3 );
line = new OpenLayers.Geometry.LineString();
t.ok( line instanceof OpenLayers.Geometry.LineString, "new OpenLayers.Geometry.LineString returns line object" );
t.eq( line.CLASS_NAME, "OpenLayers.Geometry.LineString", "line.CLASS_NAME is set correctly");
t.eq( line.components, [], "line.components is set correctly");
}
function test_LineString_constructor (t) {
t.plan( 3 );
line = new OpenLayers.Geometry.LineString(components);
t.ok( line instanceof OpenLayers.Geometry.LineString, "new OpenLayers.Geometry.LineString returns line object" );
t.eq( line.CLASS_NAME, "OpenLayers.Geometry.LineString", "line.CLASS_NAME is set correctly");
// TBD FIXME, recursion
// t.eq( line.components, components, "line.components is set correctly");
t.eq( line.components.length, 2, "line.components.length is set correctly");
}
function test_LineString_toString(t) {
t.plan(1);
line = new OpenLayers.Geometry.LineString(components);
t.eq(line.toString(),
"LINESTRING(10 15,0 0)",
"toString() returns WKT");
}
function test_LineString_removeComponent(t) {
t.plan(2);
OpenLayers.Geometry.Collection.prototype._removeComponent =
OpenLayers.Geometry.Collection.prototype.removeComponent;
OpenLayers.Geometry.Collection.prototype.removeComponent =
function(point) { g_removeComponent = point; };
line = new OpenLayers.Geometry.LineString(components);
g_removeComponent = null;
line.removeComponent(components[0]);
t.ok(g_removeComponent == null, "point not removed if only 2 points in components");
line.components.push(new OpenLayers.Geometry.Point(4,4));
line.removeComponent(components[0]);
t.ok(g_removeComponent, components[0], "point removed if 3 points in components");
OpenLayers.Geometry.Collection.prototype.removeComponent =
OpenLayers.Geometry.Collection.prototype._removeComponent;
}
function test_LineString_move(t) {
t.plan(4);
var components = [new OpenLayers.Geometry.Point(10,15),
new OpenLayers.Geometry.Point(0,0)];
var line = new OpenLayers.Geometry.LineString(components);
var x0 = components[0].x;
var y0 = components[0].y;
var x1 = components[1].x;
var y1 = components[1].y;
var dx = 10 * Math.random();
var dy = 10 * Math.random();
line.move(dx, dy);
t.eq(line.components[0].x, x0 + dx, "move() correctly modifies first x");
t.eq(line.components[0].y, y0 + dy, "move() correctly modifies first y");
t.eq(line.components[1].x, x1 + dx, "move() correctly modifies second x");
t.eq(line.components[1].y, y1 + dy, "move() correctly modifies second y");
}
function test_LineString_rotate(t) {
t.plan(6);
var components = [new OpenLayers.Geometry.Point(10,15),
new OpenLayers.Geometry.Point(0,0)];
var geometry = new OpenLayers.Geometry.LineString(components);
var originals = [];
var comp;
var angle = 2 * Math.PI * Math.random();
var origin = new OpenLayers.Geometry.Point(10 * Math.random(),
10 * Math.random());
for(var i=0; i<geometry.components.length; ++i) {
comp = geometry.components[i];
originals[i] = comp.rotate;
comp.rotate = function(a, o) {
t.ok(true, "rotate called for component " + i);
t.ok(a == angle, "rotate called with correct angle");
t.ok(o == origin, "rotate called with correct origin");
}
}
geometry.rotate(angle, origin);
// restore the original rotate defs
for(var i=0; i<geometry.components.length; ++i) {
comp.rotate = originals[i];
}
}
function test_LineString_resize(t) {
t.plan(8);
var tolerance = 1e-10;
var components = [new OpenLayers.Geometry.Point(10 * Math.random(),
10 * Math.random()),
new OpenLayers.Geometry.Point(10 * Math.random(),
10 * Math.random())];
var geometry = new OpenLayers.Geometry.LineString(components);
var origin = new OpenLayers.Geometry.Point(10 * Math.random(),
10 * Math.random());
var scale = 10 * Math.random();
var oldLength = geometry.getLength();
var ret = geometry.resize(scale, origin);
t.ok(ret === geometry, "resize returns geometry");
var newLength = geometry.getLength();
t.ok((((newLength / oldLength) - scale) / scale) < tolerance,
"resize correctly changes the length of a linestring")
var originals = [];
var comp;
for(var i=0; i<geometry.components.length; ++i) {
comp = geometry.components[i];
originals[i] = comp.resize;
comp.resize = function(s, o) {
t.ok(true, "resize called for component " + i);
t.ok(s == scale, "resize called with correct scale");
t.ok(o == origin, "resize called with correct origin");
}
}
geometry.resize(scale, origin);
// restore the original resize defs
for(var i=0; i<geometry.components.length; ++i) {
comp.resize = originals[i];
}
}
function test_split(t) {
var wkt = OpenLayers.Geometry.fromWKT;
var cases = [{
msg: "no intersection",
g1: "LINESTRING(0 0, 0 1)",
g2: "LINESTRING(1 0, 1 1)",
exp: null
} , {
msg: "intersection at midpoint",
g1: "LINESTRING(0 0, 1 1)",
g2: "LINESTRING(1 0, 0 1)",
exp: ["LINESTRING(1 0, 0.5 0.5)", "LINESTRING(0.5 0.5, 0 1)"]
}, {
msg: "intersection at midpoint (reverse source/target)",
g1: "LINESTRING(1 0, 0 1)",
g2: "LINESTRING(0 0, 1 1)",
exp: ["LINESTRING(0 0, 0.5 0.5)", "LINESTRING(0.5 0.5, 1 1)"]
}, {
msg: "intersection at endpoint",
g1: "LINESTRING(0 0, 1 1)",
g2: "LINESTRING(1 0, 1 1)",
exp: null
}, {
msg: "midpoint intersection, no options",
g1: "LINESTRING(0 0, 2 2)",
g2: "LINESTRING(0 2, 2 0)",
exp: ["LINESTRING(0 2, 1 1)", "LINESTRING(1 1, 2 0)"]
}, {
msg: "midpoint intersection, edge false",
opt: {edge: false},
g1: "LINESTRING(0 0, 2 2)",
g2: "LINESTRING(0 2, 2 0)",
exp: null
}, {
msg: "midpoint intersection, mutual",
opt: {mutual: true},
g1: "LINESTRING(0 0, 2 2)",
g2: "LINESTRING(0 2, 2 0)",
exp: [["LINESTRING(0 0, 1 1)", "LINESTRING(1 1, 2 2)"], ["LINESTRING(0 2, 1 1)", "LINESTRING(1 1, 2 0)"]]
}, {
msg: "close intersection, no tolerance",
g1: "LINESTRING(0 0, 0.9 0.9)",
g2: "LINESTRING(0 2, 2 0)",
exp: null
}, {
msg: "close intersection, within tolerance",
opt: {tolerance: 0.2},
g1: "LINESTRING(0 0, 0.9 0.9)",
g2: "LINESTRING(0 2, 2 0)",
exp: ["LINESTRING(0 2, 0.9 0.9)", "LINESTRING(0.9 0.9, 2 0)"]
}];
t.plan(cases.length);
var c, parts, part, midparts;
for(var i=0; i<cases.length; ++i) {
c = cases[i];
var g1 = wkt(c.g1);
var g2 = wkt(c.g2);
var got = g1.split(g2, c.opt);
var exp = c.exp;
if(got instanceof Array) {
parts = [];
for(var j=0; j<got.length; ++j) {
part = got[j];
if(part instanceof Array) {
midparts = [];
for(var k=0; k<part.length; ++k) {
midparts.push(part[k].toString());
}
parts.push("[" + midparts.join(", ") + "]");
} else {
parts.push(got[j].toString());
}
}
got = parts.join(", ");
}
if(exp instanceof Array) {
parts = [];
for(var j=0; j<exp.length; ++j) {
part = exp[j];
if(part instanceof Array) {
midparts = [];
for(var k=0; k<part.length; ++k) {
midparts.push(wkt(part[k]).toString());
}
parts.push("[" + midparts.join(", ") + "]");
} else {
parts.push(wkt(exp[j]).toString());
}
}
exp = parts.join(", ");
}
t.eq(got, exp, "case " + i + ": " + c.msg);
}
}
function test_distanceTo(t) {
var wkt = OpenLayers.Geometry.fromWKT;
var geoms = [
wkt("POINT(0 0)"),
wkt("LINESTRING(-2 0, 0 -2, 2 -1, 2 0)")
];
var cases = [{
got: geoms[1].distanceTo(geoms[0]),
expected: Math.sqrt(2)
}, {
got: geoms[1].distanceTo(geoms[0], {details: true}),
expected: {
distance: Math.sqrt(2),
x0: -1, y0: -1,
x1: 0, y1: 0
}
}];
t.plan(cases.length);
for(var i=0; i<cases.length; ++i) {
t.eq(cases[i].got, cases[i].expected, "case " + i);
}
}
function test_LineString_equals(t) {
t.plan(3);
var x0 = Math.random() * 100;
var y0 = Math.random() * 100;
var x1 = Math.random() * 100;
var y1 = Math.random() * 100;
var point0 = new OpenLayers.Geometry.Point(x0, y0);
var point1 = new OpenLayers.Geometry.Point(x1, y1);
var geometry = new OpenLayers.Geometry.LineString([point0, point1]);
var equal = new OpenLayers.Geometry.LineString([point0, point1]);
var offX = new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(x0 + 1, y0),
new OpenLayers.Geometry.Point(x1 + 1, y1)]);
var offY = new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(x0, y0 + 1),
new OpenLayers.Geometry.Point(x1, y1 + 1)]);
t.ok(geometry.equals(equal),
"equals() returns true for a geometry with equivalent coordinates");
t.ok(!geometry.equals(offX),
"equals() returns false for a geometry with offset x");
t.ok(!geometry.equals(offY),
"equals() returns false for a geometry with offset y");
}
function test_getVertices(t) {
t.plan(14);
var points = [
new OpenLayers.Geometry.Point(10, 20),
new OpenLayers.Geometry.Point(20, 30),
new OpenLayers.Geometry.Point(30, 40),
new OpenLayers.Geometry.Point(40, 50)
];
var line = new OpenLayers.Geometry.LineString(points);
var verts = line.getVertices();
t.ok(verts instanceof Array, "got back an array");
t.eq(verts.length, points.length, "of correct length length");
t.geom_eq(verts[0], points[0], "0: correct geometry");
t.geom_eq(verts[1], points[1], "1: correct geometry");
t.geom_eq(verts[2], points[2], "2: correct geometry");
t.geom_eq(verts[3], points[3], "3: correct geometry");
// get nodes only
var nodes = line.getVertices(true);
t.ok(nodes instanceof Array, "[nodes only] got back an array");
t.eq(nodes.length, 2, "[nodes only] of correct length length");
t.geom_eq(nodes[0], points[0], "[nodes only] first: correct geometry");
t.geom_eq(nodes[1], points[points.length-1], "[nodes only] last: correct geometry");
// no nodes
var nodes = line.getVertices(false);
t.ok(nodes instanceof Array, "[no nodes] got back an array");
t.eq(nodes.length, 2, "[no nodes] of correct length length");
t.geom_eq(nodes[0], points[1], "[no nodes] first: correct geometry");
t.geom_eq(nodes[1], points[2], "[no nodes] last: correct geometry");
}
function test_LineString_clone(t) {
t.plan(2);
var x0 = Math.random() * 100;
var y0 = Math.random() * 100;
var x1 = Math.random() * 100;
var y1 = Math.random() * 100;
var point0 = new OpenLayers.Geometry.Point(x0, y0);
var point1 = new OpenLayers.Geometry.Point(x1, y1);
var geometry = new OpenLayers.Geometry.LineString([point0, point1]);
var clone = geometry.clone();
t.ok(clone instanceof OpenLayers.Geometry.LineString,
"clone() creates an OpenLayers.Geometry.LineString");
t.ok(geometry.equals(clone), "clone has equivalent coordinates");
}
function test_getGeodesicLength(t) {
// expected values from http://www.movable-type.co.uk/scripts/latlong-vincenty.html
var cases = [{
wkt: "LINESTRING(0 0, -10 45)",
exp: 5081689.690
}, {
wkt: "LINESTRING(-10 45, 0 0)",
exp: 5081689.690
}, {
wkt: "LINESTRING(0 0, -10 45, -20 50)",
exp: 5081689.690 + 935018.062
}];
t.plan(cases.length);
var geom, got;
for(var i=0; i<cases.length; ++i) {
geom = new OpenLayers.Geometry.fromWKT(cases[i].wkt);
got = geom.getGeodesicLength();
t.eq(Math.round(got), Math.round(cases[i].exp), "[case " + i + "] length calculated");
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,241 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var line;
var components = [new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(0,0)];
function test_LinearRing_constructor (t) {
t.plan( 6 );
//null
ring = new OpenLayers.Geometry.LinearRing();
t.ok( ring instanceof OpenLayers.Geometry.LinearRing, "new OpenLayers.Geometry.LinearRing returns ring object" );
t.eq( ring.CLASS_NAME, "OpenLayers.Geometry.LinearRing", "ring.CLASS_NAME is set correctly");
t.eq( ring.components, [], "ring.components is set correctly");
//valid components
ring = new OpenLayers.Geometry.LinearRing(components);
t.ok( ring instanceof OpenLayers.Geometry.LinearRing, "new OpenLayers.Geometry.LinearRing returns ring object" );
t.eq( ring.CLASS_NAME, "OpenLayers.Geometry.LinearRing", "ring.CLASS_NAME is set correctly");
t.eq( ring.components.length, 3, "ring.components.length is set correctly");
}
function test_LinearRing_addComponent(t) {
t.plan(13);
var ring = new OpenLayers.Geometry.LinearRing();
var point = new OpenLayers.Geometry.Point(0,0);
t.ok(ring.addComponent(point),
"addComponent returns true for 1st point");
t.eq(ring.components.length, 2, "add first point, correct length");
t.ok(ring.components[0].equals(point), "point one correct");
t.ok(ring.components[0] === ring.components[ring.components.length - 1],
"first and last point are the same");
newPoint = new OpenLayers.Geometry.Point(10,10);
t.ok(ring.addComponent( newPoint ),
"addComponent returns true for unique point");
t.eq(ring.components.length, 3, "correctly adds 3rd point");
t.ok(ring.components[0].equals(point), "point one correct");
t.ok(ring.components[1].equals(newPoint), "point one correct");
t.ok(ring.components[0] === ring.components[ring.components.length - 1],
"first and last point are the same");
var length = ring.components.length;
var clone = ring.components[length - 1].clone();
t.ok(!ring.addComponent(clone),
"addComponent returns false for adding a duplicate last point");
t.eq(ring.components.length, length,
"components remains unchanged after trying to add duplicate point");
t.ok(ring.addComponent(clone, length - 1),
"addComponent returns true when adding a duplicate with an index");
t.eq(ring.components.length, length + 1,
"components increase in length after adding a duplicate point with index");
}
function test_LinearRing_removeComponent(t) {
t.plan(11);
var components = [new OpenLayers.Geometry.Point(0,0),
new OpenLayers.Geometry.Point(0,10),
new OpenLayers.Geometry.Point(15,15),
new OpenLayers.Geometry.Point(10,0)
];
var ring = new OpenLayers.Geometry.LinearRing(components);
ring.removeComponent( ring.components[2] );
t.eq(ring.components.length, 4, "removing from linear ring with 5 points: length ok");
t.ok(ring.components[0].equals(components[0]), "point one correct");
t.ok(ring.components[1].equals(components[1]), "point two correct");
t.ok(ring.components[2].equals(components[3]), "point one correct");
t.ok(ring.components[0] === ring.components[ring.components.length - 1],
"first and last point are the same");
var testBounds = new OpenLayers.Bounds(0,0,10,10);
var ringBounds = ring.getBounds();
t.ok(ringBounds.equals(testBounds), "bounds correctly recalculated");
ring.removeComponent( ring.components[2] );
t.eq(ring.components.length, 4, "cant remove from linear ring with only 4 points. new length ok (unchanged)");
t.ok(ring.components[0].equals(components[0]), "point one correct");
t.ok(ring.components[1].equals(components[1]), "point two correct");
t.ok(ring.components[2].equals(components[3]), "point one correct");
t.ok(ring.components[0] === ring.components[ring.components.length - 1],
"first and last point are the same");
}
function test_LinearRing_getArea(t) {
t.plan(1);
var components = [new OpenLayers.Geometry.Point(0,0),
new OpenLayers.Geometry.Point(0,10),
new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(10,0)
];
var ring = new OpenLayers.Geometry.LinearRing(components);
t.eq(ring.getArea(), 100, "getArea works lovely");
}
function test_LinearRing_getLength(t) {
t.plan(1);
var components = [
new OpenLayers.Geometry.Point(0,0),
new OpenLayers.Geometry.Point(0,10),
new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(10,0)
];
var ring = new OpenLayers.Geometry.LinearRing(components);
t.eq(ring.getLength(), 40, "getLength returns the correct perimiter");
}
function test_LinearRing_move(t) {
var nvert = 4,
x = new Array(nvert),
y = new Array(nvert),
components = new Array(nvert);
t.plan(2 * (nvert + 1));
for(var i=0; i<nvert; ++i) {
x[i] = Math.random();
y[i] = Math.random();
components[i] = new OpenLayers.Geometry.Point(x[i], y[i]);
}
x.push(x[0]);
y.push(y[0]);
var ring = new OpenLayers.Geometry.LinearRing(components);
var dx = Math.random();
var dy = Math.random();
ring.move(dx, dy);
for(var j=0; j<nvert + 1; ++j) {
t.eq(ring.components[j].x, x[j] + dx,
"move correctly adjust x coord of " + j + " component");
t.eq(ring.components[j].y, y[j] + dy,
"move correctly adjust y coord of " + j + " component");
}
}
function test_LinearRing_rotate(t) {
t.plan(10);
var components = [
new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(11,10),
new OpenLayers.Geometry.Point(11,11),
new OpenLayers.Geometry.Point(10,11)
];
var ring = new OpenLayers.Geometry.LinearRing(components);
// rotate a quarter turn around the origin
var origin = new OpenLayers.Geometry.Point(0, 0);
var angle = 90;
ring.rotate(angle, origin);
function withinTolerance(i, j) {
return Math.abs(i - j) < 1e-9;
}
t.ok(withinTolerance(ring.components[0].x , -10),
"rotate correctly adjusts x of component 0");
t.ok(withinTolerance(ring.components[0].y, 10),
"rotate correctly adjusts y of component 0");
t.ok(withinTolerance(ring.components[1].x, -10),
"rotate correctly adjusts x of component 1");
t.ok(withinTolerance(ring.components[1].y, 11),
"rotate correctly adjusts y of component 1");
t.ok(withinTolerance(ring.components[2].x, -11),
"rotate correctly adjusts x of component 2");
t.ok(withinTolerance(ring.components[2].y, 11),
"rotate correctly adjusts y of component 2");
t.ok(withinTolerance(ring.components[3].x, -11),
"rotate correctly adjusts x of component 3");
t.ok(withinTolerance(ring.components[3].y, 10),
"rotate correctly adjusts y of component 3");
t.ok(withinTolerance(ring.components[4].x, -10),
"rotate correctly adjusts x of component 4");
t.ok(withinTolerance(ring.components[4].y, 10),
"rotate correctly adjusts y of component 4");
}
function test_LinearRing_resize(t) {
t.plan(10);
var components = [
new OpenLayers.Geometry.Point(10,10),
new OpenLayers.Geometry.Point(11,10),
new OpenLayers.Geometry.Point(11,11),
new OpenLayers.Geometry.Point(10,11)
];
var ring = new OpenLayers.Geometry.LinearRing(components);
// rotate a quarter turn around the origin
var origin = new OpenLayers.Geometry.Point(0, 0);
var scale = Math.random();
ring.resize(scale, origin);
function withinTolerance(i, j) {
return Math.abs(i - j) < 1e-9;
}
t.ok(withinTolerance(ring.components[0].x , 10 * scale),
"resize correctly adjusts x of component 0");
t.ok(withinTolerance(ring.components[0].y, 10 * scale),
"resize correctly adjusts y of component 0");
t.ok(withinTolerance(ring.components[1].x, 11 * scale),
"resize correctly adjusts x of component 1");
t.ok(withinTolerance(ring.components[1].y, 10 * scale),
"resize correctly adjusts y of component 1");
t.ok(withinTolerance(ring.components[2].x, 11 * scale),
"resize correctly adjusts x of component 2");
t.ok(withinTolerance(ring.components[2].y, 11 * scale),
"resize correctly adjusts y of component 2");
t.ok(withinTolerance(ring.components[3].x, 10 * scale),
"resize correctly adjusts x of component 3");
t.ok(withinTolerance(ring.components[3].y, 11 * scale),
"resize correctly adjusts y of component 3");
t.ok(withinTolerance(ring.components[4].x, 10 * scale),
"resize correctly adjusts x of component 4");
t.ok(withinTolerance(ring.components[4].y, 10 * scale),
"resize correctly adjusts y of component 4");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,267 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var line;
function test_MultiLineString_constructor (t) {
t.plan( 3 );
mline = new OpenLayers.Geometry.MultiLineString();
t.ok( mline instanceof OpenLayers.Geometry.MultiLineString, "new OpenLayers.Geometry.MultiLineString returns mline object" );
t.eq( mline.CLASS_NAME, "OpenLayers.Geometry.MultiLineString", "mline.CLASS_NAME is set correctly");
t.eq( mline.components, [], "line.components is set correctly");
}
function test_MultiLineString_constructor (t) {
t.plan( 3 );
line = new OpenLayers.Geometry.LineString();
mline = new OpenLayers.Geometry.MultiLineString(line);
t.ok( mline instanceof OpenLayers.Geometry.MultiLineString, "new OpenLayers.Geometry.MultiLineString returns mline object" );
t.eq( mline.CLASS_NAME, "OpenLayers.Geometry.MultiLineString", "mline.CLASS_NAME is set correctly");
t.eq( mline.components.length, 1, "mline.components.length is set correctly");
}
function test_split(t) {
var wkt = OpenLayers.Geometry.fromWKT;
var cases = [{
msg: "no intersection",
g1: "MULTILINESTRING((0 0, 0 1), (2 2, 3 3))",
g2: "MULTILINESTRING((1 0, 1 1), (2 2, 3 2))",
exp: null
} , {
msg: "intersection at midpoint",
g1: "MULTILINESTRING((0 0, 1 1))",
g2: "MULTILINESTRING((1 0, 0 1))",
exp: ["MULTILINESTRING((1 0, 0.5 0.5))", "MULTILINESTRING((0.5 0.5, 0 1))"]
}, {
msg: "intersection at midpoint (reverse source/target)",
g1: "MULTILINESTRING((1 0, 0 1))",
g2: "MULTILINESTRING((0 0, 1 1))",
exp: ["MULTILINESTRING((0 0, 0.5 0.5))", "MULTILINESTRING((0.5 0.5, 1 1))"]
}, {
msg: "intersection at endpoint",
g1: "MULTILINESTRING((0 0, 1 1))",
g2: "MULTILINESTRING((1 0, 1 1))",
exp: null
}, {
msg: "midpoint intersection, no options",
g1: "MULTILINESTRING((0 0, 2 2))",
g2: "MULTILINESTRING((0 2, 2 0))",
exp: ["MULTILINESTRING((0 2, 1 1))", "MULTILINESTRING((1 1, 2 0))"]
}, {
msg: "midpoint intersection, edge false",
opt: {edge: false},
g1: "MULTILINESTRING((0 0, 2 2))",
g2: "MULTILINESTRING((0 2, 2 0))",
exp: null
}, {
msg: "midpoint intersection, mutual",
opt: {mutual: true},
g1: "MULTILINESTRING((0 0, 2 2))",
g2: "MULTILINESTRING((0 2, 2 0))",
exp: [["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2))"], ["MULTILINESTRING((0 2, 1 1))", "MULTILINESTRING((1 1, 2 0))"]]
}, {
msg: "close intersection, no tolerance",
g1: "MULTILINESTRING((0 0, 0.9 0.9))",
g2: "MULTILINESTRING((0 2, 2 0))",
exp: null
}, {
msg: "close intersection, within tolerance",
opt: {tolerance: 0.2},
g1: "MULTILINESTRING((0 0, 0.9 0.9))",
g2: "MULTILINESTRING((0 2, 2 0))",
exp: ["MULTILINESTRING((0 2, 0.9 0.9))", "MULTILINESTRING((0.9 0.9, 2 0))"]
}, {
msg: "multi source, single target",
g1: "MULTILINESTRING((0 0, 2 2))",
g2: "LINESTRING(0 2, 2 0)",
exp: ["LINESTRING(0 2, 1 1)", "LINESTRING(1 1, 2 0)"]
}, {
msg: "multi source, single target, mutual split",
opt: {mutual: true},
g1: "MULTILINESTRING((0 0, 2 2))",
g2: "LINESTRING(0 2, 2 0)",
exp: [["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2))"], ["LINESTRING(0 2, 1 1)", "LINESTRING(1 1, 2 0)"]]
}, {
msg: "single source, multi target",
g1: "LINESTRING(0 2, 2 0)",
g2: "MULTILINESTRING((0 0, 2 2))",
exp: ["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2))"]
}, {
msg: "partial target split",
g1: "MULTILINESTRING((2 0, 0 2))",
g2: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
exp: ["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4))"]
}, {
msg: "partial target split, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((2 0, 0 2))",
g2: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
exp: [["MULTILINESTRING((2 0, 1 1))", "MULTILINESTRING((1 1, 0 2))"], ["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4))"]]
}, {
msg: "partial source split, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
g2: "MULTILINESTRING((2 0, 0 2))",
exp: [["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4))"], ["MULTILINESTRING((2 0, 1 1))", "MULTILINESTRING((1 1, 0 2))"]]
}, {
msg: "partial target split with source endpoint",
g1: "MULTILINESTRING((1 0, 1 1))",
g2: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
exp: ["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4))"]
}, {
msg: "partial target split with source endpoint, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((5 5, 6 6), (1 0, 1 1))",
g2: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
exp: [[], ["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4))"]]
}, {
msg: "partial source split with target endpoint",
g1: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4))",
g2: "MULTILINESTRING((1 0, 1 1))",
exp: null
}, {
msg: "partial source split with target endpoint, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((0 0, 2 2), (3 3, 4 4), (5 5, 6 6))",
g2: "MULTILINESTRING((1 0, 1 1))",
exp: [["MULTILINESTRING((0 0, 1 1))", "MULTILINESTRING((1 1, 2 2), (3 3, 4 4), (5 5, 6 6))"], []]
}, {
msg: "partial target and source split",
g1: "MULTILINESTRING((0 5, 2 5), (4 5, 6 5), (8 5, 10 5))",
g2: "MULTILINESTRING((5 0, 5 2), (5 4, 5 6), (5 8, 5 10))",
exp: ["MULTILINESTRING((5 0, 5 2), (5 4, 5 5))", "MULTILINESTRING((5 5, 5 6), (5 8, 5 10))"]
}, {
msg: "partial target and source split, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((0 5, 2 5), (4 5, 6 5), (8 5, 10 5))",
g2: "MULTILINESTRING((5 0, 5 2), (5 4, 5 6), (5 8, 5 10))",
exp: [["MULTILINESTRING((0 5, 2 5), (4 5, 5 5))", "MULTILINESTRING((5 5, 6 5), (8 5, 10 5))"],
["MULTILINESTRING((5 0, 5 2), (5 4, 5 5))", "MULTILINESTRING((5 5, 5 6), (5 8, 5 10))"]]
}, {
msg: "partial target and source split with source endpoint, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((0 5, 2 5), (4 5, 6 5), (8 5, 10 5))",
g2: "MULTILINESTRING((4 0, 4 2), (4 4, 4 6), (4 8, 4 10))",
exp: [[], ["MULTILINESTRING((4 0, 4 2), (4 4, 4 5))", "MULTILINESTRING((4 5, 4 6), (4 8, 4 10))"]]
}, {
msg: "partial target and source split with target endpoint, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((4 0, 4 2), (4 4, 4 6), (4 8, 4 10))",
g2: "MULTILINESTRING((0 5, 2 5), (4 5, 6 5), (8 5, 10 5))",
exp: [["MULTILINESTRING((4 0, 4 2), (4 4, 4 5))", "MULTILINESTRING((4 5, 4 6), (4 8, 4 10))"], []]
}, {
msg: "partial target and source split with source vertex, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((0 5, 2 5), (4 5, 5 5, 6 5), (8 5, 10 5))",
g2: "MULTILINESTRING((5 0, 5 2), (5 4, 5 6), (5 8, 5 10))",
exp: [["MULTILINESTRING((0 5, 2 5), (4 5, 5 5))", "MULTILINESTRING((5 5, 6 5), (8 5, 10 5))"], ["MULTILINESTRING((5 0, 5 2), (5 4, 5 5))", "MULTILINESTRING((5 5, 5 6), (5 8, 5 10))"]]
}, {
msg: "partial target and source split with target vertex, mutual true",
opt: {mutual: true},
g1: "MULTILINESTRING((5 0, 5 2), (5 4, 5 6), (5 8, 5 10))",
g2: "MULTILINESTRING((0 5, 2 5), (4 5, 5 5, 6 5), (8 5, 10 5))",
exp: [["MULTILINESTRING((5 0, 5 2), (5 4, 5 5))", "MULTILINESTRING((5 5, 5 6), (5 8, 5 10))"], ["MULTILINESTRING((0 5, 2 5), (4 5, 5 5))", "MULTILINESTRING((5 5, 6 5), (8 5, 10 5))"]]
}];
t.plan(cases.length);
var c, parts, part, midparts;
for(var i=0; i<cases.length; ++i) {
c = cases[i];
var g1 = wkt(c.g1);
var g2 = wkt(c.g2);
var got = g1.split(g2, c.opt);
var exp = c.exp;
if(got instanceof Array) {
parts = [];
for(var j=0; j<got.length; ++j) {
part = got[j];
if(part instanceof Array) {
midparts = [];
for(var k=0; k<part.length; ++k) {
midparts.push(part[k].toString());
}
parts.push("[" + midparts.join(", ") + "]");
} else {
parts.push(got[j].toString());
}
}
got = parts.join(", ");
}
if(exp instanceof Array) {
parts = [];
for(var j=0; j<exp.length; ++j) {
part = exp[j];
if(part instanceof Array) {
midparts = [];
for(var k=0; k<part.length; ++k) {
midparts.push(wkt(part[k]).toString());
}
parts.push("[" + midparts.join(", ") + "]");
} else {
parts.push(wkt(exp[j]).toString());
}
}
exp = parts.join(", ");
}
t.eq(got, exp, "case " + i + ": " + c.msg);
}
}
function test_getVertices(t) {
t.plan(22);
var points = [
new OpenLayers.Geometry.Point(10, 20),
new OpenLayers.Geometry.Point(20, 30),
new OpenLayers.Geometry.Point(30, 40),
new OpenLayers.Geometry.Point(40, 50)
];
var multi = new OpenLayers.Geometry.MultiLineString([
new OpenLayers.Geometry.LineString(points),
new OpenLayers.Geometry.LineString(points)
]);
var verts = multi.getVertices();
t.ok(verts instanceof Array, "got back an array");
t.eq(verts.length, 2 * points.length, "of correct length length");
t.geom_eq(verts[0], points[0], "0: correct geometry");
t.geom_eq(verts[1], points[1], "1: correct geometry");
t.geom_eq(verts[2], points[2], "2: correct geometry");
t.geom_eq(verts[3], points[3], "3: correct geometry");
t.geom_eq(verts[4], points[0], "4: correct geometry");
t.geom_eq(verts[5], points[1], "5: correct geometry");
t.geom_eq(verts[6], points[2], "6: correct geometry");
t.geom_eq(verts[7], points[3], "7: correct geometry");
// nodes only
var nodes = multi.getVertices(true);
t.ok(nodes instanceof Array, "[nodes only] got back an array");
t.eq(nodes.length, 4, "[nodes only] of correct length length");
t.geom_eq(nodes[0], points[0], "[nodes only] 0: correct geometry");
t.geom_eq(nodes[1], points[3], "[nodes only] 1: correct geometry");
t.geom_eq(nodes[2], points[0], "[nodes only] 2: correct geometry");
t.geom_eq(nodes[3], points[3], "[nodes only] 3: correct geometry");
// no nodes
var nodes = multi.getVertices(false);
t.ok(nodes instanceof Array, "[no nodes] got back an array");
t.eq(nodes.length, 4, "[no nodes] of correct length length");
t.geom_eq(nodes[0], points[1], "[no nodes] 0: correct geometry");
t.geom_eq(nodes[1], points[2], "[no nodes] 1: correct geometry");
t.geom_eq(nodes[2], points[1], "[no nodes] 2: correct geometry");
t.geom_eq(nodes[3], points[2], "[no nodes] 3: correct geometry");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,130 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var point = new OpenLayers.Geometry.Point(10, 15);
function test_MultiPoint_constructor (t) {
t.plan( 2 );
var multipoint = new OpenLayers.Geometry.MultiPoint();
t.ok( multipoint instanceof OpenLayers.Geometry.MultiPoint, "new OpenLayers.Geometry.MultiPoint returns multipoint object" );
t.eq( multipoint.CLASS_NAME, "OpenLayers.Geometry.MultiPoint", "multipoint.CLASS_NAME is set correctly");
}
function test_MultiPoint_constructor (t) {
t.plan( 3 );
var multipoint = new OpenLayers.Geometry.MultiPoint([point]);
t.ok( multipoint instanceof OpenLayers.Geometry.MultiPoint, "new OpenLayers.Geometry.MultiPoint returns multipoint object" );
t.eq( multipoint.CLASS_NAME, "OpenLayers.Geometry.MultiPoint", "multipoint.CLASS_NAME is set correctly");
t.eq( multipoint.components.length, 1, "multipolygon.components.length is set correctly");
}
function test_MultiPoint_move(t) {
t.plan(2);
var multipoint = new OpenLayers.Geometry.MultiPoint([point]);
var x = point.x;
var y = point.y;
var dx = 10 * Math.random();
var dy = 10 * Math.random();
multipoint.move(dx, dy);
t.eq(multipoint.components[0].x, x + dx, "move() correctly modifies x");
t.eq(multipoint.components[0].y, y + dy, "move() correctly modifies y");
}
function test_distanceTo(t) {
var points = [
new OpenLayers.Geometry.Point(0, 0),
new OpenLayers.Geometry.Point(10, 0),
new OpenLayers.Geometry.Point(0, 9),
new OpenLayers.Geometry.Point(-5, 0),
new OpenLayers.Geometry.Point(-5, 4)
];
var geoms = [
new OpenLayers.Geometry.MultiPoint([points[0], points[1]]),
new OpenLayers.Geometry.MultiPoint([points[2], points[3]]),
points[4]
];
var cases = [{
got: geoms[0].distanceTo(geoms[0]),
expected: 0
}, {
got: geoms[0].distanceTo(geoms[1]),
expected: 5
}, {
got: geoms[1].distanceTo(geoms[2]),
expected: 4
}, {
got: geoms[0].distanceTo(geoms[1], {details: true}),
expected: {
distance: 5,
x0: 0, y0: 0,
x1: -5, y1: 0
}
}, {
got: geoms[1].distanceTo(geoms[0], {details: true}),
expected: {
distance: 5,
x0: -5, y0: 0,
x1: 0, y1: 0
}
}, {
got: geoms[1].distanceTo(geoms[2], {details: true}),
expected: {
distance: 4,
x0: -5, y0: 0,
x1: -5, y1: 4
}
}];
t.plan(cases.length);
for(var i=0; i<cases.length; ++i) {
t.eq(cases[i].got, cases[i].expected, "case " + i);
}
}
function test_MultiPoint_equals(t) {
t.plan(3);
var x = Math.random() * 100;
var y = Math.random() * 100;
var geometry = new OpenLayers.Geometry.MultiPoint(
[new OpenLayers.Geometry.Point(x, y)]);
var equal = new OpenLayers.Geometry.MultiPoint(
[new OpenLayers.Geometry.Point(x, y)]);
var offX = new OpenLayers.Geometry.MultiPoint(
[new OpenLayers.Geometry.Point(x + 1, y)]);
var offY = new OpenLayers.Geometry.MultiPoint(
[new OpenLayers.Geometry.Point(x, y + 1)]);
t.ok(geometry.equals(equal),
"equals() returns true for a geometry with equivalent coordinates");
t.ok(!geometry.equals(offX),
"equals() returns false for a geometry with offset x");
t.ok(!geometry.equals(offY),
"equals() returns false for a geometry with offset y");
}
function test_MultiPoint_clone(t) {
t.plan(2);
var x = Math.random() * 100;
var y = Math.random() * 100;
var geometry = new OpenLayers.Geometry.MultiPoint(
[new OpenLayers.Geometry.Point(x, y)]);
var clone = geometry.clone();
t.ok(clone instanceof OpenLayers.Geometry.MultiPoint,
"clone() creates an OpenLayers.Geometry.MultiPoint");
t.ok(geometry.equals(clone), "clone has equivalent coordinates");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,34 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var polygon;
var components = [new OpenLayers.Geometry.Point(10,10), new OpenLayers.Geometry.Point(0,0)];
var components2 = [new OpenLayers.Geometry.Point(10,10), new OpenLayers.Geometry.Point(0,0), new OpenLayers.Geometry.Point(10,0), new OpenLayers.Geometry.Point(10,10)];
var linearRing = new OpenLayers.Geometry.LinearRing(components);
var linearRing2 = new OpenLayers.Geometry.LinearRing(components2);
var polygon = new OpenLayers.Geometry.Polygon([linearRing]);
var polygon2 = new OpenLayers.Geometry.Polygon([linearRing2]);
function test_MultiPolygon_constructor (t) {
t.plan( 2 );
multipolygon = new OpenLayers.Geometry.MultiPolygon();
t.ok( multipolygon instanceof OpenLayers.Geometry.MultiPolygon, "new OpenLayers.Geometry.MultiPolygon returns multipolygon object" );
t.eq( multipolygon.CLASS_NAME, "OpenLayers.Geometry.MultiPolygon", "multipolygon.CLASS_NAME is set correctly");
}
function test_MultiPolygon_constructor (t) {
t.plan( 3 );
multipolygon = new OpenLayers.Geometry.MultiPolygon([polygon, polygon2]);
t.ok( multipolygon instanceof OpenLayers.Geometry.MultiPolygon, "new OpenLayers.Geometry.MultiPolygon returns multipolygon object" );
t.eq( multipolygon.CLASS_NAME, "OpenLayers.Geometry.MultiPolygon", "multipolygon.CLASS_NAME is set correctly");
t.eq( multipolygon.components.length, 2, "multipolygon.components.length is set correctly");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,214 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var point;
function test_Point_constructor (t) {
t.plan( 8 );
//empty
point = new OpenLayers.Geometry.Point();
t.ok( point instanceof OpenLayers.Geometry.Point, "new OpenLayers.Geometry.Point returns point object" );
t.eq( point.CLASS_NAME, "OpenLayers.Geometry.Point", "point.CLASS_NAME is set correctly");
//valid
var x = 10;
var y = 20;
point = new OpenLayers.Geometry.Point(x, y);
t.ok( point instanceof OpenLayers.Geometry.Point, "new OpenLayers.Geometry.Point returns point object" );
t.eq( point.CLASS_NAME, "OpenLayers.Geometry.Point", "point.CLASS_NAME is set correctly");
t.eq( point.x, x, "point.x is set correctly");
t.eq( point.y, y, "point.y is set correctly");
t.eq( point.lon, null, "point.lon is not set");
t.eq( point.lat, null, "point.lat is not set");
}
function test_Point_calculateBounds (t) {
t.plan(4);
var x = 10;
var y = 20;
point = new OpenLayers.Geometry.Point(x, y);
point.calculateBounds();
t.eq( point.bounds.left, x, "bounds.left is 10" );
t.eq( point.bounds.right, x, "bounds.right is 10" );
t.eq( point.bounds.top, y, "bounds.top is 20" );
t.eq( point.bounds.bottom, y, "bounds.bottom is 20" );
}
function test_Point_transform_getBounds (t) {
t.plan(2);
var x = 10;
var y = 20;
point = new OpenLayers.Geometry.Point(x, y);
point.calculateBounds();
t.ok( point.bounds != null, "bounds calculated by calcBounds" );
point.transform(new OpenLayers.Projection("EPSG:4326"),
new OpenLayers.Projection("EPSG:900913"));
t.eq(point.bounds, null, "Point bounds cleared after transform");
}
function test_Point_distanceTo(t) {
t.plan(7);
var x1 = 10;
var y1 = 20;
point1 = new OpenLayers.Geometry.Point(x1, y1);
var x2 = 100;
var y2 = 200;
point2 = new OpenLayers.Geometry.Point(x2, y2);
var dist = point1.distanceTo(point2)
t.eq( dist, 201.24611797498107267682563018581, "distances calculating correctly");
t.eq( dist, Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)), "distance calculation correct");
// test that details are returned (though trivial in this case)
var result = point1.distanceTo(point2, {details: true});
t.eq(result.distance, point1.distanceTo(point2), "[details] distance property is same as return without details");
t.eq(result.x0, x1, "[details] x0 property is correct");
t.eq(result.y0, y1, "[details] y0 property is correct");
t.eq(result.x1, x2, "[details] x1 property is correct");
t.eq(result.y1, y2, "[details] y1 property is correct");
}
function test_Point_toString(t) {
t.plan(1);
var x = 10;
var y = 20;
point = new OpenLayers.Geometry.Point(x, y);
t.eq(point.toString(), "POINT(" + x + " " + y + ")",
"toString() returns WKT" );
}
function test_Point_move(t) {
t.plan(3);
var x = 10;
var y = 20;
point = new OpenLayers.Geometry.Point(x, y);
var dx = 10 * Math.random();
var dy = 10 * Math.random();
point.bounds = "foo";
point.move(dx, dy);
t.eq(point.x, x + dx, "move() correctly modifies x");
t.eq(point.y, y + dy, "move() correctly modifies y");
t.ok(point.bounds == null, "bounds is cleared after a move()");
}
function test_Point_rotate(t) {
t.plan(5);
var tolerance = 1e-10;
var x = 10;
var y = 20;
var point = new OpenLayers.Geometry.Point(x, y);
var origin = new OpenLayers.Geometry.Point(5, 10);
// rotate a full revolution
point.bounds = "foo";
point.rotate(360, origin);
t.ok(((point.x - x) / x) < tolerance,
"rotate by 360 returns to the same y");
t.ok(((point.y - y) / y) < tolerance,
"rotate by 360 returns to the same y");
t.ok(point.bounds == null, "bounds is cleared after a rotate()");
// rotate an 1/8 turn
point.rotate(45, origin);
t.ok(((point.x - 1.4644660940672636) / 1.4644660940672636) < tolerance,
"rotate 1/8 turn correctly");
t.ok(((point.y - 20.606601717798213) / 20.606601717798213) < tolerance,
"rotate 1/8 turn correctly");
}
function test_Point_resize(t) {
t.plan(6);
var tolerance = 1e-10;
var x = 100 * Math.random();
var y = 100 * Math.random();
var point = new OpenLayers.Geometry.Point(x, y);
point.bounds = "foo";
var i = 100 * Math.random();
var j = 100 * Math.random();
var origin = new OpenLayers.Geometry.Point(i, j);
var scale = 10 * Math.random();
var oldDistance = origin.distanceTo(point);
var ret = point.resize(scale, origin);
var newDistance = origin.distanceTo(point);
t.ok(ret === point, "resize returns geometry");
t.ok((origin.x == i) && (origin.y == j),
"resize leaves the origin untouched");
t.ok((((newDistance / oldDistance) - scale) / scale) < tolerance,
"resize moves points the correct distance from the origin");
t.ok(point.bounds == null, "bounds is correctly cleared after a resize()");
// resize with non uniform scaling (ratio != 1)
point = new OpenLayers.Geometry.Point(10, 10);
origin = new OpenLayers.Geometry.Point(0, 0);
point.resize(2, origin, 4);
t.eq(point.x, 80, "non-uniform scaling correctly applied in x dim");
t.eq(point.y, 20, "non-uniform scaling correctly applied in y dim");
}
function test_Point_equals(t) {
t.plan(3);
var x = Math.random() * 100;
var y = Math.random() * 100;
var geometry = new OpenLayers.Geometry.Point(x, y);
var equal = new OpenLayers.Geometry.Point(x, y);
var offX = new OpenLayers.Geometry.Point(x + 1, y);
var offY = new OpenLayers.Geometry.Point(x, y + 1);
t.ok(geometry.equals(equal),
"equals() returns true for a geometry with equivalent coordinates");
t.ok(!geometry.equals(offX),
"equals() returns false for a geometry with offset x");
t.ok(!geometry.equals(offY),
"equals() returns false for a geometry with offset y");
}
function test_getVertices(t) {
t.plan(3);
var point = new OpenLayers.Geometry.Point(10, 20);
var verts = point.getVertices();
t.ok(verts instanceof Array, "got back an array");
t.eq(verts.length, 1, "of length 1");
t.geom_eq(verts[0], point, "with correct geometry");
}
function test_Point_clone(t) {
t.plan(2);
var x = Math.random() * 100;
var y = Math.random() * 100;
var geometry = new OpenLayers.Geometry.Point(x, y);
var clone = geometry.clone();
t.ok(clone instanceof OpenLayers.Geometry.Point,
"clone() creates an OpenLayers.Geometry.Point");
t.ok(geometry.equals(clone), "clone has equivalent coordinates");
}
</script>
</head>
<body>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -1,76 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Rectangle_constructor (t) {
t.plan( 8 );
//empty
var rect = new OpenLayers.Geometry.Rectangle();
t.ok( rect instanceof OpenLayers.Geometry.Rectangle, "new OpenLayers.Geometry.Rectangle returns Rectangle object" );
t.eq( rect.CLASS_NAME, "OpenLayers.Geometry.Rectangle", "Rectangle.CLASS_NAME is set correctly");
t.ok( rect.id != null, "rect.id is set");
t.ok( ! (rect.x || rect.y || rect.width || rect.height), "empty construct leaves properties empty");
//good
var x = {};
var y = {};
var w = {};
var h = {};
var rect = new OpenLayers.Geometry.Rectangle(x, y, w, h);
t.eq( rect.x, x, "good init correctly sets x property");
t.eq( rect.y, y, "good init correctly sets y property");
t.eq( rect.width, w, "good init correctly sets width property");
t.eq( rect.height, h, "good init correctly sets height property");
}
function test_Rectangle_calculateBounds(t) {
t.plan(1);
var x = 1;
var y = 2;
var w = 10;
var h = 20;
var rect = new OpenLayers.Geometry.Rectangle(x, y, w, h);
rect.calculateBounds();
var testBounds = new OpenLayers.Bounds(x, y, x + w, y + h)
t.ok( rect.bounds.equals(testBounds), "calculateBounds works correctly");
}
function test_Rectangle_getLength(t) {
t.plan(1);
var x = 1;
var y = 2;
var w = 10;
var h = 20;
var rect = new OpenLayers.Geometry.Rectangle(x, y, w, h);
var testLength = (2 * w) + (2 * h);
t.eq(rect.getLength(), testLength, "getLength() works");
}
function test_Rectangle_getArea(t) {
t.plan(1);
var x = 1;
var y = 2;
var w = 10;
var h = 20;
var rect = new OpenLayers.Geometry.Rectangle(x, y, w, h);
var testArea = w * h;
t.eq(rect.getArea(), testArea, "testArea() works");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,22 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Surface_constructor (t) {
t.plan( 2 );
var g = new OpenLayers.Geometry.Surface();
t.eq(g.CLASS_NAME, "OpenLayers.Geometry.Surface", "correct CLASS_NAME")
t.ok(OpenLayers.String.startsWith(g.id, "OpenLayers.Geometry.Surface_"),
"id correctly set");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,261 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_constructor(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var handler = new OpenLayers.Handler(control, callbacks, options);
t.ok(handler instanceof OpenLayers.Handler,
"new OpenLayers.Handler returns object");
t.eq(handler.map.id, map.id,
"constructing a handler with a map sets the map on the handler");
t.eq(handler.callbacks.foo, callbacks.foo,
"constructor correctly sets callbacks");
t.eq(handler.bar, options.bar,
"constructor correctly extends handler with options");
}
function test_Handler_activate(t) {
t.plan(52);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var events = ["mouseover", "mouseout", "mousedown",
"mouseup", "mousemove", "click",
"dblclick", "resize", "focus", "blur"];
var handler = new OpenLayers.Handler(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler is already active");
handler.active = false;
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(r, type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler",
"activate calls registerPriority with the handler");
} else {
// this is the call with handler.setEvent as the func
t.ok(r, "activate calls registerPriority with handler.setEvent");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
function setMethod(key) {
handler[key] = function() {return key};
}
activated = handler.activate();
t.ok(activated,
"activated returns true if the handler is not already active");
}
function test_Handler_deactivate(t) {
t.plan(52);
var map = new OpenLayers.Map('map', { controls: []});
// No controls so that we don't get more thingies than we expect
// when we actually clean up after ourselves: r5891 caused this
// because we actually destroy things now on the navigation control.
var control = new OpenLayers.Control();
map.addControl(control);
var events = ["mouseover", "mouseout", "mousedown",
"mouseup", "mousemove", "click",
"dblclick", "resize", "focus", "blur"];
var handler = new OpenLayers.Handler(control);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler is already deactive");
handler.activate();
map.events.unregister = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"deactivate calls unregister with browser event: " + type);
t.eq(typeof func, "function",
"activate calls unregister with a function");
t.eq(func(), type,
"activate calls unregister with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler",
"activate calls unregister with the handler");
} else {
// this is the call with handler.setEvent as the func
t.ok(r, "activate calls registerPriority with handler.setEvent");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
// add in a closure for key
(function(key) {
handler[key] = function() {return key};
})(events[i]);
}
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivated returns true if the handler is already active");
map.events.unregister = OpenLayers.Events.prototype.unregister;
map.destroy();
}
function test_Handler_setEvent(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler(control);
handler.click = function(evt) {
}
handler.activate();
var testEvent = {
xy: new OpenLayers.Pixel(Math.random(), Math.random()),
altKey: (Math.random() > 0.5),
shiftKey: (Math.random() > 0.5),
ctrlKey: (Math.random() > 0.5)
}
map.events.triggerEvent("click", testEvent);
t.ok(handler.evt.xy.x == testEvent.xy.x &&
handler.evt.xy.y == testEvent.xy.y,
"handler.evt has proper xy object");
t.eq(handler.evt.altKey, testEvent.altKey,
"handler.evt.altKey correct");
t.eq(handler.evt.shiftKey, testEvent.shiftKey,
"handler.evt.shiftKey correct");
t.eq(handler.evt.ctrlKey, testEvent.ctrlKey,
"handler.evt.ctrlKey correct");
}
function test_Handler_destroy(t) {
t.plan(5);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler(control);
var deactivated = false;
handler.deactivate = function() {
deactivated = true;
};
t.ok(handler.control,
"handler has a control prior to destroy");
t.ok(handler.map,
"handler has a map prior to destroy");
handler.destroy();
t.eq(handler.control, null,
"hanlder.control is null after destroy");
t.eq(handler.map, null,
"handler.map is null after destroy");
t.ok(deactivated,
"handler.deactivate is called by destroy");
}
function test_Handler_checkModifiers(t) {
t.plan(26);
var handler = new OpenLayers.Handler({});
handler.keyMask = null;
var proceed = handler.checkModifiers({});
t.ok(proceed,
"checkModifiers returns true if no keyMask on the handler");
/**
* Test checkModifiers for single keyMask values. The method should
* return true if the corresponding key is associated with the
* event. For example, if evt.shiftKey is true and handler.keyMask
* is OpenLayers.Handler.MOD_SHIFT, checkModifiers should return
* true.
*/
var constants = {
MOD_NONE: null,
MOD_SHIFT: "shiftKey",
MOD_CTRL: "ctrlKey",
MOD_ALT: "altKey"
}
var proceed, evt, value, c, k;
for(c in constants) {
handler.keyMask = OpenLayers.Handler[c];
// for this key mask, test all single key possibilities
for(k in constants) {
value = constants[k];
evt = {};
if(value) {
// mimic a key down on an event
evt[value] = true;
}
proceed = handler.checkModifiers(evt);
// if k == c, proceed should be true - false otherwise
t.eq(k == c, proceed,
"returns " + proceed + " if keyMask is " + c +
" and " + ((value) ? value : "no key") + " is down");
}
}
/**
* Test checkModifiers for double keyMask values. The method should
* return true if the corresponding key combo is associated with the
* event. For example, if evt.shiftKey is true and handler.keyMask
* is OpenLayers.Handler.MOD_SHIFT, checkModifiers should return
* true.
*/
var constants = ["MOD_SHIFT", "MOD_CTRL", "MOD_ALT"];
var keys = ["shiftKey", "ctrlKey", "altKey"];
var proceed, evt, c1, c2, k1, k2;
for(var i=0; i<constants.length-1; ++i) {
c1 = constants[i];
for(var j=i+1; j<constants.length; ++j) {
c2 = constants[j];
handler.keyMask = OpenLayers.Handler[c1] |
OpenLayers.Handler[c2];
// for this key mask, test all double key possibilities
for(var x=0; x<keys.length-1; ++x) {
k1 = keys[x];
for(var y=x+1; y<keys.length; ++y) {
k2 = keys[y];
evt = {};
evt[k1] = true;
evt[k2] = true;
proceed = handler.checkModifiers(evt);
// if the combo matches, proceed should be true
// at this point we know that i != j and x != y
t.eq(((i == x) || (i == y)) &&
((j == x) || (j == y)),
proceed,
"returns " + proceed + " if " + c1 + " | " + c2 +
" and " + k1 + " + " + k2 + " is down");
}
}
}
}
}
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 512px;"/>
</body>
</html>

View File

@ -1,299 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Click_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Click(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Click_activate(t) {
t.plan(2);
var control = {
map: new OpenLayers.Map('map')
};
var handler = new OpenLayers.Handler.Click(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
handler.dragging = true;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
}
function test_Handler_Click_events(t) {
t.plan(50);
var map = new OpenLayers.Map('map');
var control = {
map: map
};
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.Click",
"activate calls registerPriority with the handler");
}
}
function setMethod(key) {
handler[key] = function() {return key};
}
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["click", "dblclick", "mousedown", "mouseup", "rightclick"];
var nonevents = ["mousemove", "resize", "focus", "blur"];
var handler = new OpenLayers.Handler.Click(control);
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
handler.activate();
// different listeners registered for pixelTolerance option
var events = ["click", "dblclick", "mousedown", "mouseup", "rightclick"];
var nonevents = ["mousemove", "resize", "focus", "blur"];
var handler = new OpenLayers.Handler.Click(control, {}, {
pixelTolerance: 2
});
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
handler.activate();
}
function test_Handler_Click_callbacks(t) {
t.plan(13);
var map = new OpenLayers.Map('map', {controls: []});
var control = {
map: map
};
var handler = new OpenLayers.Handler.Click(control, {});
handler.activate();
// set up for single click - three tests here
var timers = {};
var sto = window.setTimeout;
window.setTimeout = function(func, delay) {
var key = Math.random();
timers[key] = true;
t.ok(typeof func == "function",
"setTimeout called with a function");
t.eq(delay, handler.delay,
"setTimeout called with proper delay");
// execute function that is supposed to be delayed
func();
return key;
}
var cto = window.clearTimeout;
window.clearTimeout = function(key) {
if(timers[key] === true) {
delete timers[key];
} else {
t.fail("clearTimeout called with non-existent timerId");
}
}
var testEvt = {id: Math.random()};
handler.callbacks = {
"click": function(evt) {
t.eq(evt.id, testEvt.id,
"(click w/ single true) click callback called with correct evt");
},
"dblclick": function(evt) {
t.fail("(click w/ single true) dblclick should not be called here");
}
};
map.events.triggerEvent("click", testEvt);
// set up for double click with double false - no tests here (only failures)
handler.callbacks = {
"click": function(evt) {
t.fail("(dblclick w/ double false) click should not be called here");
},
"dblclick": function(evt) {
t.fail("(dblclick w/ double false) dblclick should not be called here");
}
};
testEvt = Math.random();
map.events.triggerEvent("dblclick", testEvt);
// set up for double click with double true - one test here
handler.double = true;
handler.callbacks = {
"click": function(evt) {
t.fail("(dblclick w/ double true) click should not be called here");
},
"dblclick": function(evt) {
t.eq(evt, testEvt,
"(dblclick w/ double true) dblclick called with correct evt");
}
};
testEvt = Math.random();
map.events.triggerEvent("dblclick", testEvt);
// set up for two clicks with double true - 6 tests here (with timeout ones from above)
handler.double = true;
handler.callbacks = {
"click": function(evt) {
t.ok(evt != null, "(two clicks w/ double true) click will not be called here if next three tests pass");
},
"dblclick": function(evt) {
t.eq(evt, testEvt,
"(two clicks w/ double true) dblclick called with correct evt");
}
};
testEvt = Math.random();
map.events.triggerEvent("click", testEvt);
t.ok(handler.timerId != null,
"(two clicks w/ double true) timer is set to call click");
map.events.triggerEvent("click", testEvt);
t.ok(handler.timerId == null,
"(two clicks w/ double true) timer is cleared to call click");
map.events.triggerEvent("dblclick", testEvt);
handler.destroy();
// set up to tests pixelTolerance - three tests here (2 from setTimeout above)
handler = new OpenLayers.Handler.Click(control, {}, {
pixelTolerance: 2
});
handler.activate();
var downEvt = {
xy: new OpenLayers.Pixel(0, 0)
};
map.events.triggerEvent("mousedown", downEvt);
var clickEvt = {
xy: new OpenLayers.Pixel(0, 1)
};
// mouse moves one pixel, click should be called
handler.callbacks = {
"click": function(evt) {
t.ok(evt.xy == clickEvt.xy, "(pixelTolerance met) click called");
}
};
map.events.triggerEvent("click", clickEvt);
handler.clearTimer();
// mouse moves 3x3 pixels, click should not be called
map.events.triggerEvent("mousedown", downEvt);
var clickEvt = {
xy: new OpenLayers.Pixel(3, 3)
};
// mouse moves one pixel, click should be called
handler.callbacks = {
"click": function(evt) {
t.fail("(pixelTolerance not met) click should not be called");
}
};
map.events.triggerEvent("click", clickEvt); // no test run
handler.clearTimer();
window.setTimeout = sto;
window.clearTimeout = cto;
}
function test_Handler_Click_deactivate(t) {
t.plan(4);
var control = {
map: new OpenLayers.Map('map')
};
var handler = new OpenLayers.Handler.Click(control);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler was not already active");
handler.active = true;
handler.down = true;
handler.timerId = true;
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivate returns true if the handler was active already");
t.eq(handler.down, null,
"deactivate sets down to null");
t.eq(handler.timerId, null,
"deactivate sets timerId to null");
}
function test_Handler_Click_mouseup(t) {
t.plan(4);
g_Propagate = {};
g_evt = {};
//no modifiers, no handlerightclicks, no isrightclick
var temp = OpenLayers.Event.isRightClick;
OpenLayers.Event.isRightClick = function(e) {
t.ok(e == g_evt, 'correct event passed in to checkModifiers');
return false;
};
var h = {
'checkModifiers': function(e) {
t.ok(e == g_evt, 'correct event passed in to checkModifiers');
return false;
},
'control': {
'handleRightClicks': false
},
'rightclick': function(e) {
t.ok(e == g_evt, 'correct event passed in to checkModifiers');
return g_Propagate;
}
};
var propagate = OpenLayers.Handler.Click.prototype.mouseup.apply(h, [g_evt]);
t.ok(propagate, "default propagate is true when no modifiers, no handlerightclicks, no isrightclick")
//modifiers, handlerightclicks, and isrightclick
h.checkModifiers = function() { return true; };
h.control.handleRightClicks = true;
OpenLayers.Event.isRightClick = function(e) { return true; };
propagate = OpenLayers.Handler.Click.prototype.mouseup.apply(h, [g_evt]);
t.ok(propagate == g_Propagate, "return from handler's rightClick() returned from mouseup");
OpenLayers.Event.isRightClick = temp;
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,379 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Drag_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Drag(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Drag_activate(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Drag(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
handler.dragging = true;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
t.ok(!handler.dragging,
"activate sets dragging to false");
}
function test_Handler_Drag_events(t) {
t.plan(25);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Drag(control);
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["mousedown", "mouseup", "mousemove", "mouseout", "click"];
var nonevents = ["dblclick", "resize", "focus", "blur"];
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.Drag",
"activate calls registerPriority with the handler");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
function setMethod(key) {
handler[key] = function() {return key};
}
var activated = handler.activate();
}
function test_Handler_Drag_callbacks(t) {
t.plan(33);
var map = new OpenLayers.Map('map', {controls: []});
var control = new OpenLayers.Control();
map.addControl(control);
// set callback methods (out doesn't get an xy)
var events = ["down", "move", "up", "done"];
var testEvents = {};
var xys = {};
var callbacks = {};
for(var i=0; i<events.length; ++i) {
var px = new OpenLayers.Pixel(Math.random(), Math.random());
testEvents[events[i]] = {xy: px};
setCallback(events[i]);
}
function setCallback(key) {
callbacks[key] = function(evtxy) {
t.ok(evtxy.x == testEvents[key].xy.x &&
evtxy.y == testEvents[key].xy.y,
key + " callback called with the proper evt.xy");
}
}
var handler = new OpenLayers.Handler.Drag(control, callbacks);
handler.activate();
var oldIsLeftClick = OpenLayers.Event.isLeftClick;
var oldStop = OpenLayers.Event.stop;
var oldCheckModifiers = handler.checkModifiers;
// test mousedown with right click
OpenLayers.Event.isLeftClick = function() {
return false;
}
handler.checkModifiers = function() {
return true;
}
handler.started = true;
handler.start = {x: "foo", y: "bar"};
handler.last = {x: "foo", y: "bar"};
map.events.triggerEvent("mousedown", testEvents.down);
t.ok(!handler.started, "right-click sets started to false");
t.eq(handler.start, null, "right-click sets start to null");
t.eq(handler.last, null, "right-click sets last to null");
// test mousedown with improper modifier
OpenLayers.Event.isLeftClick = function() {
return true;
}
handler.checkModifiers = function() {
return false;
}
handler.started = true;
handler.start = {x: "foo", y: "bar"};
handler.last = {x: "foo", y: "bar"};
map.events.triggerEvent("mousedown", testEvents.down);
t.ok(!handler.started, "bad modifier sets started to false");
t.eq(handler.start, null, "bad modifier sets start to null");
t.eq(handler.last, null, "bad modifier sets last to null");
// test mousedown
handler.checkModifiers = function(evt) {
t.ok(evt.xy.x == testEvents.down.xy.x &&
evt.xy.y == testEvents.down.xy.y,
"mousedown calls checkModifiers with the proper event");
return true;
}
OpenLayers.Event.isLeftClick = function(evt) {
t.ok(evt.xy.x == testEvents.down.xy.x &&
evt.xy.y == testEvents.down.xy.y,
"mousedown calls isLeftClick with the proper event");
return true;
}
OpenLayers.Event.stop = function(evt, allowDefault) {
if(!allowDefault) {
t.ok(evt.xy.x == testEvents.down.xy.x &&
evt.xy.y == testEvents.down.xy.y,
"mousedown default action is disabled");
} else {
t.fail(
"mousedown is prevented from falling to other elements");
}
}
map.events.triggerEvent("mousedown", testEvents.down);
t.ok(handler.started, "mousedown sets the started flag to true");
t.ok(!handler.dragging, "mouse down sets the dragging flag to false");
t.ok(handler.start.x == testEvents.down.xy.x &&
handler.start.y == testEvents.down.xy.y,
"mouse down sets handler.start correctly");
t.ok(handler.last.x == testEvents.down.xy.x &&
handler.last.y == testEvents.down.xy.y,
"mouse down sets handler.last correctly");
OpenLayers.Event.stop = oldStop;
OpenLayers.Event.isLeftClick = oldIsLeftClick;
handler.checkModifiers = oldCheckModifiers;
// test mouseup before mousemove
var realUp = testEvents.up;
testEvents.up = testEvents.down;
// this will fail with notice about the done callback being called
// if done is called when it shouldn't be
map.events.triggerEvent("mouseup", testEvents.up);
testEvents.up = realUp;
// test mousemove
handler.started = false;
map.events.triggerEvent("mousemove", {xy: {x: null, y: null}});
// if the handler triggers the move callback, it will be with the
// incorrect evt.xy
t.ok(true,
"mousemove before the handler has started doesn't call move");
handler.started = true;
map.events.triggerEvent("mousemove", testEvents.move);
t.ok(handler.dragging, "mousemove sets the dragging flag to true");
t.ok(handler.start.x == testEvents.down.xy.x &&
handler.start.y == testEvents.down.xy.y,
"mouse move leaves handler.start alone");
t.ok(handler.last.x == testEvents.move.xy.x &&
handler.last.y == testEvents.move.xy.y,
"mouse move sets handler.last correctly");
// a second move with the same evt.xy should not trigger move callback
// if it does, the test page will complain about a bad plan number
var oldMove = handler.callbacks.move;
handler.callbacks.move = function() {
t.ok(false,
"a second move with the same evt.xy should not trigger a move callback");
}
map.events.triggerEvent("mousemove", testEvents.move);
handler.callbacks.move = oldMove;
// test mouseup
handler.started = false;
map.events.triggerEvent("mouseup", {xy: {x: null, y: null}});
// if the handler triggers the up callback, it will be with the
// incorrect evt.xy
t.ok(true,
"mouseup before the handler has started doesn't call up");
handler.started = true;
// mouseup triggers the up and done callbacks
testEvents.done = testEvents.up;
map.events.triggerEvent("mouseup", testEvents.up);
t.ok(!this.started, "mouseup sets the started flag to false");
t.ok(!this.dragging, "mouseup sets the dragging flag to false");
// test mouseout
handler.started = false;
map.events.triggerEvent("mouseout", {xy: {x: null, y: null}});
// if the handler triggers the out or done callback, it will be with the
// incorrect evt.xy
t.ok(true,
"mouseout before the handler has started doesn't call out or done");
handler.started = true;
var oldMouseLeft = OpenLayers.Util.mouseLeft;
OpenLayers.Util.mouseLeft = function(evt, element) {
t.ok(evt.xy.x == testEvents.done.xy.x &&
evt.xy.y == testEvents.done.xy.y,
"mouseout calls Util.mouseLeft with the correct event");
t.eq(element.id, map.div.id,
"mouseout calls Util.mouseLeft with the correct element");
return true;
}
// mouseup triggers the out and done callbacks
// out callback gets no arguments
handler.callbacks.out = function() {
t.eq(arguments.length, 0,
"mouseout calls out callback with no arguments");
}
map.events.triggerEvent("mouseout", testEvents.done);
t.ok(!handler.started, "mouseout sets started flag to false");
t.ok(!handler.dragging, "mouseout sets dragging flag to false");
OpenLayers.Util.mouseLeft = oldMouseLeft;
// test click with the click.html example - the click method on the
// drag handler returns (handler.start == handler.last), stopping
// propagation of the click event if the mouse moved during a drag.
// regression tests will assure that the drag handler doesn't mess
// with anything else on a click
function getProperties(obj) {
var props = {};
for(key in obj) {
if(typeof obj[key] != "function" && typeof obj[key] != "object") {
props[key] = obj[key];
}
}
return props;
}
var before = getProperties(handler);
map.events.triggerEvent("click", null);
var after = getProperties(handler);
t.eq(before, after, "click doesn't mess with handler");
}
function test_Handler_Drag_submethods(t) {
t.plan(4);
var map = new OpenLayers.Map('map', {controls: []});
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Drag(control, {});
// set test events
var events = ["down", "move", "up", "out"];
var testEvents = {};
var type, px;
for(var i=0; i<events.length; ++i) {
type = events[i];
px = new OpenLayers.Pixel(Math.random(), Math.random());
testEvents[type] = {xy: px};
setMethod(type);
}
function setMethod(type) {
handler[type] = function(evt) {
t.ok(evt.xy.x == testEvents[type].xy.x &&
evt.xy.y == testEvents[type].xy.y,
"handler." + type + " called with the right event");
}
}
handler.activate();
// test mousedown
handler.checkModifiers = function(evt) {
return true;
}
var oldIsLeftClick = OpenLayers.Event.isLeftClick;
OpenLayers.Event.isLeftClick = function(evt) {
return true;
}
map.events.triggerEvent("mousedown", testEvents.down);
OpenLayers.Event.isLeftClick = oldIsLeftClick;
// test mousemove
map.events.triggerEvent("mousemove", testEvents.move);
// test mouseup
map.events.triggerEvent("mouseup", testEvents.up);
// test mouseout
var oldMouseLeft = OpenLayers.Util.mouseLeft;
OpenLayers.Util.mouseLeft = function() {
return true;
};
handler.started = true;
map.events.triggerEvent("mouseout", testEvents.out);
OpenLayers.Util.mouseLeft = oldMouseLeft;
}
function test_Handler_Drag_deactivate(t) {
t.plan(6);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Drag(control);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler was not already active");
handler.active = true;
handler.dragging = true;
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivate returns true if the handler was active already");
t.ok(!handler.started,
"deactivate sets started to false");
t.ok(!handler.dragging,
"deactivate sets dragging to false");
t.ok(handler.start == null,
"deactivate sets start to null");
t.ok(handler.last == null,
"deactivate sets start to null");
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,484 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_initialize(t) {
t.plan(4);
var control = new OpenLayers.Control();
control.id = Math.random();
var layer = "boo";
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Feature(control, layer,
callbacks, options);
t.eq(handler.layer, "boo",
"layer property properly set");
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_activate(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
map.addLayer(layer);
var handler = new OpenLayers.Handler.Feature(control, layer);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
var zIndex = layer.div.style.zIndex;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
t.eq(parseInt(layer.div.style.zIndex),
map.Z_INDEX_BASE['Feature'],
"layer z-index properly adjusted");
}
function test_events(t) {
t.plan(25);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
map.addLayer(layer);
var handler = new OpenLayers.Handler.Feature(control, layer);
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["mousedown", "mouseup", "mousemove", "click", "dblclick"];
var nonevents = ["mouseout", "resize", "focus", "blur"];
map.events.registerPriority = function(type, obj, func) {
var output = func();
// Don't listen for setEvent handlers (#902)
if (typeof output == "string") {
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method:"+type);
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.Feature",
"activate calls registerPriority with the handler");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
function setMethod(key) {
handler[key] = function() {return key};
}
var activated = handler.activate();
}
function test_geometrytype_limit(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.layer = layer;
layer.getFeatureFromEvent = function(evt) { return feature };
map.addLayer(layer);
var handler = new OpenLayers.Handler.Feature(control, layer, {}, {'geometryTypes':['OpenLayers.Geometry.Point']});
handler.activate();
handler.callback = function(type,featurelist) {
t.eq(featurelist[0].id, feature.id, "Correct feature called back on");
}
handler.handle({type: "click"});
handler.feature = null;
handler.lastFeature = null;
handler.callback = function(type,featurelist) {
t.fail("Shouldn't have called back on " + featurelist[0].geometry);
}
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(0,0));
feature.layer = layer;
handler.handle("click", {});
}
function test_callbacks(t) {
t.plan(9);
var map = new OpenLayers.Map('map', {controls: []});
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
map.addLayer(layer);
var callbacks = {};
var newFeature, lastFeature;
var evtPx = {xy: new OpenLayers.Pixel(Math.random(), Math.random())};
// define a callback factory function
function getCallback(evt, feature) {
return function(f) {
t.ok(f == feature, evt + " callback called with proper feature");
};
}
// override the layer's getFeatureFromEvent func so that it always
// returns newFeature
layer.getFeatureFromEvent = function(evt) { return newFeature; };
var handler = new OpenLayers.Handler.Feature(control, layer, callbacks);
handler.activate();
// test click in new feature
// only 'click' callback should be called
handler.feature = null;
lastFeature = null;
newFeature = new OpenLayers.Feature.Vector();
newFeature.layer = layer;
callbacks['click'] = getCallback('click', newFeature);
callbacks['clickout'] = getCallback('clickout', lastFeature);
evtPx.type = "click";
map.events.triggerEvent('click', evtPx);
// test click in new feature and out of last feature
// both 'click' and 'clickout' callbacks should be called
lastFeature = newFeature;
newFeature = new OpenLayers.Feature.Vector();
newFeature.layer = layer;
callbacks['click'] = getCallback('click', newFeature);
callbacks['clickout'] = getCallback('clickout', lastFeature);
evtPx.type = "click";
map.events.triggerEvent('click', evtPx);
// test click out of last feature
// only 'clickout' callback should be called
lastFeature = newFeature;
newFeature = null;
callbacks['click'] = getCallback('click', newFeature);
callbacks['clickout'] = getCallback('clickout', lastFeature);
evtPx.type = "click";
map.events.triggerEvent('click', evtPx);
layer.getFeatureFromEvent = function(evt) { t.fail("mousemove called getFeatureFromEvent without any mousemove callbacks"); };
evtPx.type = "mousemove";
map.events.triggerEvent('mousemove', evtPx);
layer.getFeatureFromEvent = function(evt) { return newFeature; };
// test over a new feature
// only 'over' callback should be called
handler.feature = null;
lastFeature = null;
newFeature = new OpenLayers.Feature.Vector();
newFeature.layer = layer;
callbacks['over'] = getCallback('over', newFeature);
callbacks['out'] = getCallback('out', lastFeature);
evtPx.type = "mousemove";
map.events.triggerEvent('mousemove', evtPx);
// test over a new feature and out of last feature
// both 'over' and 'out' callbacks should be called
lastFeature = newFeature;
newFeature = new OpenLayers.Feature.Vector();
newFeature.layer = layer;
callbacks['over'] = getCallback('over', newFeature);
callbacks['out'] = getCallback('out', lastFeature);
evtPx.type = "mousemove";
map.events.triggerEvent('mousemove', evtPx);
// test out of last feature
// only 'out' callback should be called
lastFeature = newFeature;
newFeature = null;
callbacks['over'] = getCallback('over', newFeature);
callbacks['out'] = getCallback('out', lastFeature);
evtPx.type = "mousemove";
map.events.triggerEvent('mousemove', evtPx);
// test dblclick on a feature
// 'dblclick' callback should be called
handler.feature = null;
lastFeature = null;
newFeature = new OpenLayers.Feature.Vector();
newFeature.layer = layer;
callbacks['dblclick'] = getCallback('dblclick', newFeature);
evtPx.type = "dblclick";
map.events.triggerEvent('dblclick', evtPx);
}
function test_deactivate(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
map.addLayer(layer);
var layerIndex = parseInt(layer.div.style.zIndex);
var handler = new OpenLayers.Handler.Feature(control, layer);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler was not already active");
handler.active = true;
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivate returns true if the handler was active already");
t.eq(parseInt(layer.div.style.zIndex),
layerIndex,
"deactivate sets the layer z-index back");
}
function test_stopHandled(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
map.addLayer(layer);
var handler = new OpenLayers.Handler.Feature(control, layer);
handler.activate();
handler.handle = function(evt) { return /* handled */ true; };
var evtPx = {xy: new OpenLayers.Pixel(Math.random(), Math.random())};
map.events.register("click", map, function(e) {
t.ok(!handler.stopClick, "clicks propagate with stopClick set to false" );
});
map.events.register("mousedown", map, function(e) {
t.ok(!handler.stopDown, "mousedown propagate with stopDown set to false" );
});
map.events.register("mouseup", map, function(e) {
t.ok(!handler.stopUp, "mouseup propagate with stopUp set to false" );
});
// 0 test
map.events.triggerEvent('click', evtPx);
// 0 test
map.events.triggerEvent('mousedown', evtPx);
// 0 test
map.events.triggerEvent('mousedown', evtPx);
// 1 test
handler.stopClick = false;
map.events.triggerEvent('click', evtPx);
// 1 test
handler.stopDown = false;
map.events.triggerEvent('mousedown', evtPx);
// 1 test
handler.stopUp = false;
map.events.triggerEvent('mouseup', evtPx);
// 3 tests total
}
function test_destroyed_feature(t) {
t.plan(18);
// setup
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var layer = new OpenLayers.Layer();
layer.removeFeatures = function() {};
map.addLayer(layer);
var handler = new OpenLayers.Handler.Feature(control, layer);
var feature, count, lastType, lastHandled;
handler.callback = function(type, features) {
++count;
lastType = type;
lastHandled = features;
}
/**
* Test that a destroyed feature doesn't get sent to the "click" callback
*/
count = 0;
handler.activate();
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.layer = layer;
// mock click on a feature
layer.getFeatureFromEvent = function(evt) {return feature};
handler.handle({type: "click"});
// confirm that feature was handled
t.eq(count, 1, "[click] callback called once");
t.eq(lastType, "click", "[click] correct callback type");
t.eq(lastHandled[0].id, feature.id, "[click] correct feature sent to callback");
// now destroy the feature and confirm that the callback is not called again
feature.destroy();
handler.handle({type: "click"});
if(count === 1) {
t.ok(true, "[click] callback not called after destroy");
} else {
t.fail("[click] callback called after destroy: " + lastType);
}
/**
* Test that a destroyed feature doesn't get sent to the "clickout" callback
*/
count = 0;
handler.deactivate();
handler.activate();
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.layer = layer;
// mock a click on a feature
layer.getFeatureFromEvent = function(evt) {return feature};
handler.handle({type: "click"});
// confirm that callback got feature
t.eq(count, 1, "[clickout] callback called once on in");
t.eq(lastType, "click", "[clickout] click callback called on in");
t.eq(lastHandled.length, 1, "[clickout] callback called with one feature");
t.eq(lastHandled[0].id, feature.id, "[clickout] callback called with correct feature");
// now mock a click off a destroyed feature
feature.destroy();
layer.getFeatureFromEvent = function(evt) {return null};
handler.handle({type: "click"});
// confirm that callback does not get called
if(count === 1) {
t.ok(true, "[clickout] callback not called when clicking out of a destroyed feature");
} else {
t.fail("[clickout] callback called when clicking out of a destroyed feature: " + lastType);
}
/**
* Test that a destroyed feature doesn't get sent to the "over" callback
*/
count = 0;
handler.deactivate();
handler.activate();
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.layer = layer;
// mock mousemove over a feature
layer.getFeatureFromEvent = function(evt) {return feature};
handler.handle({type: "mousemove"});
// confirm that feature was handled
t.eq(count, 1, "[over] callback called once");
t.eq(lastType, "over", "[over] correct callback type");
t.eq(lastHandled[0].id, feature.id, "[over] correct feature sent to callback");
// now destroy the feature and confirm that the callback is not called again
feature.destroy();
handler.handle({type: "mousemove"});
if(count === 1) {
t.ok(true, "[over] callback not called after destroy");
} else {
t.fail("[over] callback called after destroy: " + lastType);
}
/**
* Test that a destroyed feature doesn't get sent to the "out" callback
*/
count = 0;
handler.deactivate();
handler.activate();
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(0,0));
feature.layer = layer;
// mock a mousemove over a feature
layer.getFeatureFromEvent = function(evt) {return feature};
handler.handle({type: "mousemove"});
// confirm that callback got feature
t.eq(count, 1, "[out] callback called once on over");
t.eq(lastType, "over", "[out] click callback called on over");
t.eq(lastHandled.length, 1, "[out] callback called with one feature");
t.eq(lastHandled[0].id, feature.id, "[out] callback called with correct feature");
// now mock a click off a destroyed feature
feature.destroy();
layer.getFeatureFromEvent = function(evt) {return null};
handler.handle({type: "mousemove"});
// confirm that callback does not get called
if(count === 1) {
t.ok(true, "[out] callback not called when moving out of a destroyed feature");
} else {
t.fail("[out] callback called when moving out of a destroyed feature: " + lastType);
}
handler.destroy();
}
function test_click_tolerance(t) {
t.plan(3);
var map, control, layer, feature, evtPx;
var clicks, callbacks, handler;
map = new OpenLayers.Map('map', {controls: []});
control = new OpenLayers.Control();
map.addControl(control);
layer = new OpenLayers.Layer();
map.addLayer(layer);
feature = new OpenLayers.Feature.Vector();
feature.layer = layer;
evtPx = {
xy: new OpenLayers.Pixel(Math.random(), Math.random()),
type: "click"
};
// override the layer's getFeatureFromEvent func so that it always
// returns newFeature
layer.getFeatureFromEvent = function(evt) { return feature; };
callbacks = {
click: function() {
clicks++;
}
};
handler = new OpenLayers.Handler.Feature(
control, layer, callbacks, {clickTolerance: 4});
handler.activate();
handler.down = {x: 0, y: 0};
// distance between down and up is 1, which is
// lower than clickTolerance so "click" should trigger
handler.up = {x: 1, y: 0};
clicks = 0;
map.events.triggerEvent("click", evtPx);
t.eq(clicks, 1, "click callback triggers when tolerance is not reached (lower than)");
// distance between down and up is 4, which is
// equal to clickTolerance so "click" should trigger
handler.up = {x: 0, y: 4};
clicks = 0;
map.events.triggerEvent("click", evtPx);
t.eq(clicks, 1, "click callback triggers when tolerance is not reached (equal to)");
// distance between down and up is 5, which is
// greater than clickTolerance so "click" should not trigger
handler.up = {x: 5, y: 0};
clicks = 0;
map.events.triggerEvent("click", evtPx);
t.eq(clicks, 0, "click callback does not trigger when tolerance is reached");
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,136 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Hover_events(t) {
t.plan(10);
var map = new OpenLayers.Map('map');
var control = {
map: map
};
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.Hover",
"activate calls registerPriority with the handler");
}
}
function setMethod(key) {
handler[key] = function() {return key};
}
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["mousemove", "mouseout"];
var nonevents = ["mousedown", "mouseup", "click", "dblclick", "resize", "focus", "blur"];
var handler = new OpenLayers.Handler.Hover(control);
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
handler.activate();
}
function test_Handler_Hover_callbacks(t) {
t.plan(8);
var map = new OpenLayers.Map('map', {controls: []});
var control = {
map: map
};
var timers = {};
var sto = window.setTimeout;
window.setTimeout = function(func, delay) {
var key = Math.random();
timers[key] = true;
t.ok(typeof func == "function",
"setTimeout called with a function");
t.eq(delay, handler.delay,
"setTimeout called with proper delay");
// execute function that is supposed to be delayed
func();
return key;
}
var cto = window.clearTimeout;
window.clearTimeout = function(key) {
if(timers[key] === true) {
delete timers[key];
} else {
t.fail("clearTimeout called with non-existent timerId");
}
}
var handler = new OpenLayers.Handler.Hover(control, {});
handler.activate();
var testEvt;
// test pause and move callbacks - four tests here (2 from setTimeout above)
testEvt = {id: Math.random()};
handler.callbacks = {
"pause": function(evt) {
t.eq(evt.id, testEvt.id,
"pause callback called with correct evt");
},
"move": function(evt) {
t.eq(evt.id, testEvt.id,
"move callback called with correct evt");
}
};
map.events.triggerEvent("mousemove", testEvt);
handler.clearTimer();
// test pixelTolerance - four tests here (2 from setTimeout above)
handler.pixelTolerance = 2;
handler.px = new OpenLayers.Pixel(0, 0);
testEvt = {
xy: new OpenLayers.Pixel(0, 1)
};
// mouse moves one pixel, callbacks shouldn't be called
handler.callbacks = {
"pause": function(evt) {
t.fail("(pixelTolerance met) pause callback shouldn't be called");
},
"move": function(evt) {
t.fail("(pixelTolerance met) move callback shoudln't be called");
}
};
map.events.triggerEvent("mousemove", testEvt);
handler.clearTimer();
handler.px = new OpenLayers.Pixel(0, 0);
testEvt = {
xy: new OpenLayers.Pixel(3, 3)
};
// mouse moves 3x3 pixels, callbacks should be called
handler.callbacks = {
"pause": function(evt) {
t.ok(evt.xy == testEvt.xy, "(pixelTolerance unmet) pause callback called");
},
"move": function(evt) {
t.ok(evt == testEvt, "(pixelTolerance unmet) move callback called");
}
};
map.events.triggerEvent("mousemove", testEvt);
handler.clearTimer();
window.setTimeout = sto;
window.clearTimeout = cto;
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,106 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Keyboard_initialize(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Keyboard(control, callbacks,
options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Keyboard_destroy(t) {
t.plan(3);
var control = new OpenLayers.Control();
var handler = new OpenLayers.Handler.Keyboard(control);
var old = OpenLayers.Handler.prototype.destroy;
t.ok(handler.eventListener != null,
"eventListener is not null before destroy");
OpenLayers.Handler.prototype.destroy = function() {
t.ok(true, "destroy calls destroy on correct parent");
};
handler.destroy();
t.ok(handler.eventListener == null,
"eventListeners is null after destroy");
OpenLayers.Handler.prototype.destroy = old;
}
function test_Handler_Keyboard_activate(t) {
t.plan(8);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Keyboard(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
handler.dragging = true;
var old = OpenLayers.Event.stopObserving;
var types = ["keydown", "keyup"];
OpenLayers.Event.observe = function(obj, type, method) {
t.ok(obj == document,
"activate calls observing with correct object");
var validType = (OpenLayers.Util.indexOf(types, type) != -1);
t.ok(validType, "activate calls observe for " + type);
t.ok(method == handler.eventListener,
"activate calls observing with correct method");
};
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
OpenLayers.Event.observe = old;
}
function test_Handler_Drag_deactivate(t) {
t.plan(8);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Keyboard(control);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler was not already active");
handler.active = true;
var old = OpenLayers.Event.stopObserving;
var types = ["keydown", "keyup"];
OpenLayers.Event.stopObserving = function(obj, type, method) {
t.ok(obj == document,
"deactivate calls stopObserving with correct object");
var validType = (OpenLayers.Util.indexOf(types, type) != -1);
t.ok(validType, "deactivate calls stopObserving for " + type);
t.ok(method == handler.eventListener,
"deactivate calls stopObserving with correct method");
};
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivate returns true if the handler was active already");
OpenLayers.Event.stopObserving = old;
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,136 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_MouseWheel_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.MouseWheel(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_MouseWheel_activate(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.MouseWheel(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
}
function test_Handler_MouseWheel_mousePosition(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("","",{}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var pass = false;
var handler = new OpenLayers.Handler.MouseWheel(control, {'up':
function (evt) {
if (evt.xy) { pass = true; }
}
});
handler.setMap(map);
handler.activate();
var delta = 120;
if (window.opera && window.opera.version() < 9.2) delta = -delta;
handler.onWheelEvent({'target':map.layers[0].div, wheelDelta: delta});
t.ok(pass, "evt.xy was set even without a mouse move");
}
function test_Handler_MouseWheel_events(t) {
t.plan(5);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.MouseWheel(control);
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["mousemove"];
var nonevents = ["dblclick", "resize", "focus", "blur"];
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.MouseWheel",
"activate calls registerPriority with the handler");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
function setMethod(key) {
handler[key] = function() {return key};
}
var activated = handler.activate();
}
function test_Handler_MouseWheel_deactivate(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.MouseWheel(control);
handler.active = false;
var deactivated = handler.deactivate();
t.ok(!deactivated,
"deactivate returns false if the handler was not already active");
handler.active = true;
deactivated = handler.deactivate();
t.ok(deactivated,
"deactivate returns true if the handler was active already");
}
function test_handler_MouseWheel_destroy(t) {
t.plan(1);
var control = new OpenLayers.Control();
var handler = new OpenLayers.Handler.MouseWheel(control);
handler.deactivate = function() {
t.ok(true, "Deactivate called one time.");
}
handler.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,186 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Path_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Path(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Path_activation(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Path(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
activated = handler.deactivate();
t.ok(activated,
"deactivate returns true if the handler was active already");
map.destroy();
}
function test_Handler_Path_bounds(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Path(control, {});
var activated = handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.mousedown(evt);
handler.mouseup(evt);
var evt = {xy: new OpenLayers.Pixel(175, 100), which: 1};
handler.mousemove(evt);
handler.mousedown(evt);
handler.mouseup(evt);
t.ok(handler.line.geometry.getBounds().equals(new OpenLayers.Bounds(0,-35.15625,35.15625,0)), "Correct bounds");
var evt = {xy: new OpenLayers.Pixel(175, 100), which: 1};
handler.mousedown(evt);
var evt = {xy: new OpenLayers.Pixel(125, 100), which: 1};
handler.mousemove(evt);
t.ok(!handler.line.geometry.getBounds().equals(new OpenLayers.Bounds(0,-35.15625,35.15625,0)), "Correct bounds after dragging without letting go. (Came out as "+handler.line.geometry.getBounds().toBBOX() + ".)");
map.destroy();
}
function test_callbacks(t) {
t.plan(15);
var map = new OpenLayers.Map("map", {
resolutions: [1]
});
var layer = new OpenLayers.Layer.Vector("foo", {
maxExtent: new OpenLayers.Bounds(-10, -10, 10, 10),
isBaseLayer: true
});
map.addLayer(layer);
var control = new OpenLayers.Control({
});
var log = {};
var handler = new OpenLayers.Handler.Path(control, {
create: function() {
log.type = "create",
log.args = arguments
},
modify: function() {
log.type = "modify",
log.args = arguments
},
done: function() {
log.type = "done",
log.args = arguments
},
cancel: function() {
log.type = "cancel",
log.args = arguments
}
});
control.handler = handler;
map.addControl(control);
map.setCenter(new OpenLayers.LonLat(0, 0), 0);
// mock up feature drawing
handler.activate();
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.type, "create", "[mousedown] create called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[mousedown] correct vertex");
t.ok(log.args[1] === handler.line, "[mousedown] correct sketch feature");
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.type, "modify", "[mouseup] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[mouseup] correct vertex");
t.ok(log.args[1] === handler.line, "[mouseup] correct sketch feature");
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(1, 1)});
t.eq(log.type, "modify", "[mousemove] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-149, 74), "[mousemove] correct vertex");
t.ok(log.args[1] === handler.line, "[mousemove] correct sketch feature");
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(10, 10)});
t.eq(log.type, "modify", "[mousemove] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-140, 65), "[mousemove] correct vertex");
t.ok(log.args[1] === handler.line, "[mousemove] correct sketch feature");
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(10, 10)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(10, 10)});
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(10, 10)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(10, 10)});
handler.dblclick({type: "dblclick", xy: new OpenLayers.Pixel(10, 10)});
t.eq(log.type, "done", "[dblclick] done called");
t.geom_eq(
log.args[0],
new OpenLayers.Geometry.LineString([
new OpenLayers.Geometry.Point(-150, 75),
new OpenLayers.Geometry.Point(-140, 65)
]),
"[dblclick] correct linestring"
);
// mock up sketch cancel
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 0)});
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(1, 1)});
handler.deactivate();
t.eq(log.type, "cancel", "[deactivate while drawing] cancel called");
map.destroy();
}
function test_Handler_Path_destroy(t) {
t.plan(6);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Path(control, {foo: 'bar'});
handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.mousedown(evt);
t.ok(handler.layer,
"handler has a layer prior to destroy");
t.ok(handler.point,
"handler has a point prior to destroy");
t.ok(handler.line,
"handler has a line prior to destroy");
handler.destroy();
t.eq(handler.layer, null,
"handler.layer is null after destroy");
t.eq(handler.point, null,
"handler.point is null after destroy");
t.eq(handler.line, null,
"handler.line is null after destroy");
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,227 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Point_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Point(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Point_activation(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Point(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
activated = handler.deactivate();
t.ok(activated,
"deactivate returns true if the handler was active already");
}
function test_Handler_Point_events(t) {
t.plan(29);
var map = new OpenLayers.Map('map');
var control = {
map: map
};
var handler = new OpenLayers.Handler.Point(control);
// list below events that should be handled (events) and those
// that should not be handled (nonevents) by the handler
var events = ["click", "dblclick", "mousedown", "mouseup", "mousemove"];
var nonevents = ["mouseout", "resize", "focus", "blur"];
map.events.registerPriority = function(type, obj, func) {
var r = func();
if(typeof r == "string") {
// this is one of the mock handler methods
t.eq(OpenLayers.Util.indexOf(nonevents, type), -1,
"registered method is not one of the events " +
"that should not be handled");
t.ok(OpenLayers.Util.indexOf(events, type) > -1,
"activate calls registerPriority with browser event: " + type);
t.eq(typeof func, "function",
"activate calls registerPriority with a function");
t.eq(func(), type,
"activate calls registerPriority with the correct method");
t.eq(obj["CLASS_NAME"], "OpenLayers.Handler.Point",
"activate calls registerPriority with the handler");
}
}
// set browser event like properties on the handler
for(var i=0; i<events.length; ++i) {
setMethod(events[i]);
}
function setMethod(key) {
handler[key] = function() {return key};
}
var activated = handler.activate();
handler.destroy();
// test that click and dblclick are stopped
var handler = new OpenLayers.Handler.Point(control);
var oldStop = OpenLayers.Event.stop;
OpenLayers.Event.stop = function(evt) {
t.ok(evt.type == "click" || evt.type == "dblclick",
evt.type + " stopped");
}
t.eq(handler.click({type: "click"}), false, "click returns false");
t.eq(handler.dblclick({type: "dblclick"}), false, "dblclick returns false");
OpenLayers.Event.stop = oldStop;
}
function test_callbacks(t) {
t.plan(10);
var map = new OpenLayers.Map("map", {
resolutions: [1]
});
var layer = new OpenLayers.Layer.Vector("foo", {
maxExtent: new OpenLayers.Bounds(-10, -10, 10, 10),
isBaseLayer: true
});
map.addLayer(layer);
var control = new OpenLayers.Control({
});
var log = {};
var handler = new OpenLayers.Handler.Point(control, {
create: function() {
log.type = "create",
log.args = arguments
},
modify: function() {
log.type = "modify",
log.args = arguments
},
done: function() {
log.type = "done",
log.args = arguments
},
cancel: function() {
log.type = "cancel",
log.args = arguments
}
});
control.handler = handler;
map.addControl(control);
map.setCenter(new OpenLayers.LonLat(0, 0), 0);
// mock up feature drawing
handler.activate();
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.type, "create", "[mousedown] create called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[mousedown] correct point");
t.geom_eq(log.args[1].geometry, new OpenLayers.Geometry.Point(-150, 75), "[mousedown] correct sketch feature");
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(1, 0)});
t.eq(log.type, "modify", "[mousemove] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-149, 75), "[mousemove] correct point");
t.geom_eq(log.args[1].geometry, new OpenLayers.Geometry.Point(-149, 75), "[mousemove] correct sketch feature");
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(1, 0)});
t.eq(log.type, "done", "[mouseup] done called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-149, 75), "[mouseup] correct point");
// mock up feature drawing with a cancel
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
handler.deactivate();
t.eq(log.type, "cancel", "[deactivate while drawing] cancel called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[deactivate while drawing] correct point");
map.destroy();
}
function test_Handler_Point_deactivation(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Point(control, {foo: 'bar'});
handler.activate();
handler.layer.destroy();
handler.deactivate();
t.eq(handler.layer, null,
"deactivate doesn't throw an error if layer was" +
" previously destroyed");
}
function test_Handler_Point_bounds(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Point(control, {});
var activated = handler.activate();
var px = new OpenLayers.Pixel(150, 75);
var evt = {xy: px, which: 1};
handler.mousedown(evt);
var lonlat = map.getLonLatFromPixel(px);
t.eq(handler.point.geometry.x, lonlat.lon, "X is correct");
t.eq(handler.point.geometry.y, lonlat.lat, "Y is correct");
t.ok(handler.point.geometry.getBounds().equals(new OpenLayers.Bounds(lonlat.lon,lonlat.lat,lonlat.lon,lonlat.lat)), "Correct bounds");
var evt = {xy: new OpenLayers.Pixel(175, 100), which: 1};
handler.mousemove(evt);
t.ok(!handler.point.geometry.getBounds().equals(new OpenLayers.Bounds(0,0,0,0)), "Bounds changed after moving mouse");
}
function test_Handler_Point_destroy(t) {
t.plan(4);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Point(control, {foo: 'bar'});
handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.mousedown(evt);
t.ok(handler.layer,
"handler has a layer prior to destroy");
t.ok(handler.point,
"handler has a point prior to destroy");
handler.destroy();
t.eq(handler.layer, null,
"handler.layer is null after destroy");
t.eq(handler.point, null,
"handler.point is null after destroy");
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,201 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_Polygon_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.Polygon(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_Polygon_activation(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Polygon(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
activated = handler.deactivate();
t.ok(activated,
"deactivate returns true if the handler was active already");
map.destroy();
}
function test_Handler_Polygon_bounds(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Polygon(control, {});
var activated = handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.mousedown(evt);
handler.mouseup(evt);
var evt = {xy: new OpenLayers.Pixel(175, 100), which: 1};
handler.mousemove(evt);
handler.mousedown(evt);
handler.mouseup(evt);
t.ok(handler.line.geometry.getBounds().equals(new OpenLayers.Bounds(0,-35.15625,35.15625,0)), "Correct bounds");
var evt = {xy: new OpenLayers.Pixel(175, 100), which: 1};
handler.mousedown(evt);
var evt = {xy: new OpenLayers.Pixel(125, 100), which: 1};
handler.mousemove(evt);
t.ok(!handler.polygon.geometry.getBounds().equals(new OpenLayers.Bounds(0,-35.15625,35.15625,0)),
"Correct bounds after dragging without letting go. (Came out as "+handler.line.geometry.getBounds().toBBOX() + ".)");
map.destroy();
}
function test_callbacks(t) {
t.plan(15);
var map = new OpenLayers.Map("map", {
resolutions: [1]
});
var layer = new OpenLayers.Layer.Vector("foo", {
maxExtent: new OpenLayers.Bounds(-10, -10, 10, 10),
isBaseLayer: true
});
map.addLayer(layer);
var control = new OpenLayers.Control({
});
var log = {};
var handler = new OpenLayers.Handler.Polygon(control, {
create: function() {
log.type = "create",
log.args = arguments
},
modify: function() {
log.type = "modify",
log.args = arguments
},
done: function() {
log.type = "done",
log.args = arguments
},
cancel: function() {
log.type = "cancel",
log.args = arguments
}
});
control.handler = handler;
map.addControl(control);
map.setCenter(new OpenLayers.LonLat(0, 0), 0);
// mock up feature drawing
handler.activate();
// click at 0, 0
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.type, "create", "[mousedown] create called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[mousedown] correct vertex");
t.ok(log.args[1] === handler.polygon, "[mousedown] correct sketch feature");
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 0)});
t.eq(log.type, "modify", "[mouseup] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 75), "[mouseup] correct vertex");
t.ok(log.args[1] === handler.polygon, "[mouseup] correct sketch feature");
// move to 10, 10 and click
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(10, 10)});
t.eq(log.type, "modify", "[mousemove] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-140, 65), "[mousemove] correct vertex");
t.ok(log.args[1] === handler.polygon, "[mouseup] correct sketch feature");
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(10, 10)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(10, 10)});
// move to 0, 10 and double click
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(0, 10)});
t.eq(log.type, "modify", "[mousemove] modify called");
t.geom_eq(log.args[0], new OpenLayers.Geometry.Point(-150, 65), "[mousemove] correct vertex");
t.ok(log.args[1] === handler.polygon, "[mouseup] correct sketch feature");
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 10)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 10)});
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 10)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 10)});
handler.dblclick({type: "dblclick", xy: new OpenLayers.Pixel(0, 10)});
t.eq(log.type, "done", "[dblclick] done called");
t.geom_eq(
log.args[0],
new OpenLayers.Geometry.Polygon([
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(-150, 75),
new OpenLayers.Geometry.Point(-140, 65),
new OpenLayers.Geometry.Point(-150, 65),
new OpenLayers.Geometry.Point(-150, 75)
])
]),
"[dblclick] correct polygon"
);
// mock up sketch cancel
handler.mousedown({type: "mousedown", xy: new OpenLayers.Pixel(0, 0)});
handler.mouseup({type: "mouseup", xy: new OpenLayers.Pixel(0, 0)});
handler.mousemove({type: "mousemove", xy: new OpenLayers.Pixel(1, 1)});
handler.deactivate();
t.eq(log.type, "cancel", "[deactivate while drawing] cancel called");
map.destroy();
}
function test_Handler_Polygon_destroy(t) {
t.plan(8);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.Polygon(control, {foo: 'bar'});
handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.mousedown(evt);
t.ok(handler.layer,
"handler has a layer prior to destroy");
t.ok(handler.point,
"handler has a point prior to destroy");
t.ok(handler.line,
"handler has a line prior to destroy");
t.ok(handler.polygon,
"handler has a polygon prior to destroy");
handler.destroy();
t.eq(handler.layer, null,
"handler.layer is null after destroy");
t.eq(handler.point, null,
"handler.point is null after destroy");
t.eq(handler.line, null,
"handler.line is null after destroy");
t.eq(handler.polygon, null,
"handler.polygon is null after destroy");
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,228 +0,0 @@
<html>
<head>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
function test_Handler_RegularPolygon_constructor(t) {
t.plan(3);
var control = new OpenLayers.Control();
control.id = Math.random();
var callbacks = {foo: "bar"};
var options = {bar: "foo"};
var oldInit = OpenLayers.Handler.prototype.initialize;
OpenLayers.Handler.prototype.initialize = function(con, call, opt) {
t.eq(con.id, control.id,
"constructor calls parent with the correct control");
t.eq(call, callbacks,
"constructor calls parent with the correct callbacks");
t.eq(opt, options,
"regular polygon constructor calls parent with the correct options");
}
var handler = new OpenLayers.Handler.RegularPolygon(control, callbacks, options);
OpenLayers.Handler.prototype.initialize = oldInit;
}
function test_Handler_RegularPolygon_activation(t) {
t.plan(3);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.RegularPolygon(control);
handler.active = true;
var activated = handler.activate();
t.ok(!activated,
"activate returns false if the handler was already active");
handler.active = false;
activated = handler.activate();
t.ok(activated,
"activate returns true if the handler was not already active");
activated = handler.deactivate();
t.ok(activated,
"deactivate returns true if the handler was active already");
map.destroy();
}
function test_Handler_RegularPolygon_deactivation(t) {
t.plan(1);
var map = new OpenLayers.Map('map');
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.RegularPolygon(control, {foo: 'bar'});
handler.activate();
handler.layer.destroy();
handler.deactivate();
t.eq(handler.layer, null,
"deactivate doesn't throw an error if layer was" +
" previously destroyed");
map.destroy();
}
function test_Handler_RegularPolygon_four_corners(t) {
t.plan(7);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.RegularPolygon(control, {});
var activated = handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.down(evt);
var evt = {xy: new OpenLayers.Pixel(175, 75), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-35.15625,-35.15625,35.15625,35.15625",
"correct bounds after move");
t.eq(handler.feature.geometry.components[0].components.length, 5,
"geometry has 5 components");
t.eq(handler.feature.geometry.CLASS_NAME,
"OpenLayers.Geometry.Polygon",
"geometry is a polygon");
t.eq(handler.radius, 25*1.40625, "feature radius as set on handler");
var evt = {xy: new OpenLayers.Pixel(175, 80), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-35.15625,-35.15625,35.15625,35.15625",
"correct bounds after move with a fixed radius");
handler.cancel();
handler.setOptions({radius:2 / Math.sqrt(2)});
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.down(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-1,-1,1,1",
"bounds with manual radius setting");
var evt = {xy: new OpenLayers.Pixel(175, 90), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"34.15625,-22.09375,36.15625,-20.09375",
"bounds with manual radius setting and mousemove");
map.destroy();
}
function test_Handler_RegularPolygon_circle(t) {
t.plan(7);
var map = new OpenLayers.Map('map');
map.addLayer(new OpenLayers.Layer.WMS("", "", {}));
map.zoomToMaxExtent();
var control = new OpenLayers.Control();
map.addControl(control);
var handler = new OpenLayers.Handler.RegularPolygon(control, {}, {'sides':40});
var activated = handler.activate();
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.down(evt);
var evt = {xy: new OpenLayers.Pixel(175, 75), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-35.15625,-35.15625,35.15625,35.15625",
"correct bounds after move");
t.eq(handler.feature.geometry.components[0].components.length, 41,
"geometry has correct numbre of components");
t.eq(handler.feature.geometry.CLASS_NAME,
"OpenLayers.Geometry.Polygon",
"geometry is a polygon");
t.eq(handler.radius, 25*1.40625, "feature radius as set on handler");
var evt = {xy: new OpenLayers.Pixel(175, 80), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-35.823348,-35.823348,35.823348,35.823348",
"correct bounds after move with fixed radius");
handler.cancel();
handler.setOptions({radius:1});
var evt = {xy: new OpenLayers.Pixel(150, 75), which: 1};
handler.down(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"-0.996917,-0.996917,0.996917,0.996917",
"bounds with manual radius setting");
var evt = {xy: new OpenLayers.Pixel(175, 80), which: 1};
handler.move(evt);
t.eq(handler.feature.geometry.getBounds().toBBOX(),
"34.159333,-8.028167,36.153167,-6.034333",
"bounds with manual radius setting and mousemove");
map.destroy();
}
function test_Handler_RegularPolygon_irregular(t) {
t.plan(4);
var map = {
getLonLatFromPixel: function(px) {
return {lon: px.x, lat: px.y};
},
getResolution: function() {
return 1;
}
};
var layer = {
addFeatures: function() {},
drawFeature: function(feature, style) {
var ring = feature.geometry.components[0];
t.eq(ring.components[0].x, 20, "correct right");
t.eq(ring.components[0].y, 10, "correct bottom");
t.eq(ring.components[2].x, 10, "correct left");
t.eq(ring.components[2].y, 15, "correct top");
}
};
var control = {};
var options = {
sides: 4,
irregular: true,
layer: layer,
map: map
};
var handler = new OpenLayers.Handler.RegularPolygon(
control, null, options
);
handler.origin = new OpenLayers.Geometry.Point(10, 10);
handler.feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Polygon(
[new OpenLayers.Geometry.LinearRing()]
)
);
// should result in a 10 x 5 rectangle
handler.move({xy: {x: 20, y: 15}});
}
function test_callbacks(t) {
t.plan(1);
// setup
var map = new OpenLayers.Map("map", {
getLonLatFromPixel: function(px) {
return {lon: px.x, lat: px.y};
}
});
var control = {"map": map};
var done = function(geom) {
t.ok(true,
"done callback called even if no move between down and up");
};
var handler = new OpenLayers.Handler.RegularPolygon(
control, {"done": done});
handler.activate();
var xy = new OpenLayers.Pixel(Math.random(), Math.random());
var isLeftClick = OpenLayers.Event.isLeftClick;
OpenLayers.Event.isLeftClick = function() { return true; };
// test
map.events.triggerEvent("mousedown", {"xy": xy});
map.events.triggerEvent("mouseup", {"xy": xy});
// tear down
OpenLayers.Event.isLeftClick = isLeftClick;
}
</script>
</head>
<body>
<div id="map" style="width: 300px; height: 150px;"/>
</body>
</html>

View File

@ -1,68 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var icon;
function test_Icon_constructor (t) {
t.plan( 4 );
var size = new OpenLayers.Size(5,6);
icon = new OpenLayers.Icon("", size);
t.ok( icon instanceof OpenLayers.Icon, "new OpenLayers.Icon returns Icon object" );
t.ok( icon.size instanceof OpenLayers.Size, "icon.size returns Size object" );
t.ok( icon.size.equals(size), "icon.size returns correct value" );
t.eq( icon.url, "", "icon.url returns str object" );
}
function test_Icon_clone (t) {
t.plan( 4 );
icon = new OpenLayers.Icon("a",new OpenLayers.Size(5,6));
t.ok( icon instanceof OpenLayers.Icon, "new OpenLayers.Icon returns Icon object" );
var cloned = icon.clone();
t.ok( cloned instanceof OpenLayers.Icon, "clone is an OpenLayers.Icon" );
cloned.url = "b"
t.eq( icon.url, "a", "icon.url doesn't change with clone's url" );
t.eq( cloned.url, "b", "cloned.url does change when edited" );
}
function test_Icon_setOpacity(t) {
t.plan( 2 );
icon = new OpenLayers.Icon("a",new OpenLayers.Size(5,6));
t.ok(!icon.imageDiv.style.opacity, "default icon has no opacity");
icon.setOpacity(0.5);
t.eq(parseFloat(icon.imageDiv.style.opacity), 0.5, "icon.setOpacity() works");
}
function test_Icon_isDrawn(t) {
t.plan(4);
var icon = {};
//no imageDiv
var drawn = OpenLayers.Icon.prototype.isDrawn.apply(icon, []);
t.ok(!drawn, "icon with no imageDiv not drawn");
//imageDiv no parentNode
icon.imageDiv = {};
drawn = OpenLayers.Icon.prototype.isDrawn.apply(icon, []);
t.ok(!drawn, "icon with imageDiv with no parentNode not drawn");
//imageDiv with parent
icon.imageDiv.parentNode = {};
drawn = OpenLayers.Icon.prototype.isDrawn.apply(icon, []);
t.ok(drawn, "icon with imageDiv with parentNode drawn");
//imageDiv with parent but nodetype 11
icon.imageDiv.parentNode = {'nodeType': 11};
drawn = OpenLayers.Icon.prototype.isDrawn.apply(icon, []);
t.ok(!drawn, "imageDiv with parent but nodetype 11 not drawn");
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,106 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script src="../lib/OpenLayers/Lang/en-CA.js" type="text/javascript"></script>
<script src="../lib/OpenLayers/Lang/fr.js" type="text/javascript"></script>
<script type="text/javascript">
function test_setCode(t) {
t.plan(4);
OpenLayers.Lang.code = null;
// test with no argument - this could result in the default or the
// browser language if a dictionary exists
OpenLayers.Lang.setCode();
t.ok(OpenLayers.Lang.code != null,
"code set when no argument is sent");
var primary = "xx";
var subtag = "XX";
var code = primary + "-" + subtag;
OpenLayers.Lang[code] = {};
// test code for dictionary that exists
OpenLayers.Lang.setCode(code);
t.eq(OpenLayers.Lang.code, code,
"code properly set for existing dictionary");
// test code for dictionary that doesn't exist
OpenLayers.Lang.setCode(primary + "-YY");
t.eq(OpenLayers.Lang.code, OpenLayers.Lang.defaultCode,
"code set to default for non-existing dictionary");
// test code for existing primary but missing subtag
OpenLayers.Lang[primary] = {};
OpenLayers.Lang.setCode(primary + "-YY");
t.eq(OpenLayers.Lang.code, primary,
"code set to primary when subtag dictionary is missing");
// clean up
delete OpenLayers.Lang[code];
delete OpenLayers.Lang[primary];
OpenLayers.Lang.code = null;
}
function test_getCode(t) {
t.plan(3);
OpenLayers.Lang.code = null;
// test that a non-null value is retrieved - could be browser language
// or defaultCode
var code = OpenLayers.Lang.getCode();
t.ok(code != null, "returns a non-null code");
t.ok(OpenLayers.Lang.code != null, "sets the code to a non-null value");
// test that the code is returned if non-null
OpenLayers.Lang.code = "foo";
t.eq(OpenLayers.Lang.getCode(), "foo", "returns the code if non-null");
// clean up
OpenLayers.Lang.code = null;
}
function test_i18n(t) {
t.plan(1);
t.ok(OpenLayers.i18n === OpenLayers.Lang.translate,
"i18n is an alias for OpenLayers.Lang.translate");
}
function test_translate(t) {
var keys = ['test1', 'test3', 'noKey'];
var codes = ['en', 'en-CA', 'fr', 'fr-CA', 'sw'];
var result = {
'en': {'overlays':'Overlays',
'unhandledRequest':'Unhandled request return foo',
'noKey':'noKey'},
'en-CA': {'overlays':'Overlays',
'unhandledRequest':'Unhandled request return foo',
'noKey':'noKey'},
'fr': {'overlays':'Calques',
'unhandledRequest':'Requête non gérée, retournant foo',
'noKey':'noKey'},
'fr-CA': {'overlays':'Calques', //this should result in 'fr'
'unhandledRequest':'Requête non gérée, retournant foo',
'noKey':'noKey'},
'sw': {'overlays':'Overlays', //this should result in 'en'
'unhandledRequest':'Unhandled request return foo',
'noKey':'noKey'}
};
t.plan(keys.length*codes.length);
for (var i=0; i<codes.length; ++i) {
var code = codes[i];
OpenLayers.Lang.setCode(code);
t.eq(OpenLayers.Lang.translate('overlays'), result[code]['overlays'], "simple key lookup in "+code);
t.eq(OpenLayers.Lang.translate('unhandledRequest',{'statusText':'foo'}),
result[code]['unhandledRequest'], "lookup with argument substitution in "+code);
t.eq(OpenLayers.Lang.translate('noKey'), result[code]['noKey'], "invalid key returns the key in "+code);
}
}
</script>
</head>
<body>
</body>
</html>

View File

@ -1,513 +0,0 @@
<html>
<head>
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var layer;
function test_Layer_constructor (t) {
t.plan( 15 );
var options = { chicken: 151, foo: "bar", projection: "none" };
var layer = new OpenLayers.Layer('Test Layer', options);
t.ok( layer instanceof OpenLayers.Layer, "new OpenLayers.Layer returns object" );
t.eq( layer.CLASS_NAME, "OpenLayers.Layer", "CLASS_NAME variable set correctly");
t.eq( layer.name, "Test Layer", "layer.name is correct" );
t.ok( layer.id != null, "Layer is given an id");
t.ok( layer.projection, "none", "default layer projection correctly set");
t.ok( ((layer.chicken == 151) && (layer.foo == "bar")), "layer.options correctly set to Layer Object" );
t.ok( ((layer.options["chicken"] == 151) && (layer.options["foo"] == "bar")), "layer.options correctly backed up" );
t.ok( typeof layer.div == "object" , "layer.div is created" );
t.eq( layer.div.id, layer.id, "layer.div.id is correct" );
options.chicken = 552;
t.eq( layer.options["chicken"], 151 , "layer.options correctly made fresh copy" );
t.eq( layer.isBaseLayer, false, "Default layer is not base layer" );
layer = new OpenLayers.Layer('Test Layer');
t.ok( layer instanceof OpenLayers.Layer, "new OpenLayers.Layer returns object" );
t.eq( layer.name, "Test Layer", "layer.name is correct" );
t.ok( layer.projection == null, "default layer projection correctly set");
t.ok( layer.options instanceof Object, "layer.options correctly initialized as a non-null Object" );
}
function test_Layer_clone (t) {
t.plan( 8 );
var mapone = new OpenLayers.Map('map');
var options = { chicken: 151, foo: "bar", maxResolution: "auto" };
var layer = new OpenLayers.Layer('Test Layer', options);
mapone.addLayer(layer);
// randomly assigned property
layer.chocolate = 5;
var clone = layer.clone();
t.ok( clone.map == null, "cloned layer has map property set to null")
var maptwo = new OpenLayers.Map('map2');
maptwo.addLayer(clone);
t.ok( clone instanceof OpenLayers.Layer, "new OpenLayers.Layer returns object" );
t.eq( clone.name, "Test Layer", "default clone.name is correct" );
t.ok( ((clone.options["chicken"] == 151) && (clone.options["foo"] == "bar")), "clone.options correctly set" );
t.eq(clone.chocolate, 5, "correctly copied randomly assigned property");
layer.addOptions({chicken:152});
t.eq(clone.options["chicken"], 151, "made a clean copy of options");
t.ok( (layer.maxResolution != clone.maxResolution), "maxresolution of clone reset to new map div");
t.ok( (layer.minResolution != clone.minResolution), "minresolution of clone reset to new map div");
mapone.destroy();
maptwo.destroy();
}
function test_Layer_setName (t) {
t.plan( 1 );
layer = new OpenLayers.Layer('Test Layer');
layer.setName("chicken");
t.eq(layer.name, "chicken", "setName() works")
}
function test_Layer_addOptions (t) {
t.plan( 4 );
var options = { chicken: 151, foo: "bar" };
var layer = new OpenLayers.Layer('Test Layer', options);
layer.addOptions({bark:55, chicken: 171});
t.eq(layer.bark, 55, "addOptions() assigns new option correctly to Layer");
t.eq(layer.options.bark, 55, "addOptions() adds new option correctly to backup");
t.eq(layer.chicken, 171, "addOptions() overwrites option correctly to Layer");
t.eq(layer.options.chicken, 171, "addOptions() overwrites option correctly to backup");
}
function test_Layer_StandardOptionsAccessors (t) {
t.plan( 4 );
var projection = "chicken";
var maxExtent = new OpenLayers.Bounds(50,50,100,100);
var maxResolution = 1.5726;
var numZoomLevels = 11;
var options = { projection: projection,
maxExtent: maxExtent,
maxResolution: maxResolution,
numZoomLevels: numZoomLevels
};
var layer = new OpenLayers.Layer('Test Layer', options);
t.eq(layer.projection, projection, "projection set correctly");
t.ok(layer.maxExtent.equals(maxExtent), "maxExtent set correctly");
t.eq(layer.maxResolution, maxResolution, "maxResolution set correctly");
t.eq(layer.numZoomLevels, numZoomLevels, "numZoomLevels set correctly");
}
function test_eventListeners(t) {
t.plan(1);
var method = OpenLayers.Events.prototype.on;
// test that events.on is called at layer construction
var options = {
eventListeners: {foo: "bar"}
};
OpenLayers.Events.prototype.on = function(obj) {
t.eq(obj, options.eventListeners, "events.on called with eventListeners");
}
var layer = new OpenLayers.Layer("test", options);
OpenLayers.Events.prototype.on = method;
layer.destroy();
// if events.on is called again, this will fail due to an extra test
// test layer without eventListeners
OpenLayers.Events.prototype.on = function(obj) {
t.fail("events.on called without eventListeners");
}
var layer2 = new OpenLayers.Layer("test");
OpenLayers.Events.prototype.on = method;
layer2.destroy();
}
function test_Layer_initResolutions(t) {
t.plan(15);
var map = new OpenLayers.Map("map");
var options, layer;
// tests for minResolution, maxResolution, and numZoomLevels
options = {
minResolution: 1.5,
maxResolution: 10.5,
numZoomLevels: 5,
map: map
};
layer = new OpenLayers.Layer("test", options);
layer.initResolutions();
t.eq(layer.minResolution.toPrecision(6), (1.5).toPrecision(6),
"(with numZoomLevels) layer minResolution preserved");
t.eq(layer.maxResolution.toPrecision(6), (10.5).toPrecision(6),
"(with numZoomLevels) layer maxResolution preserved");
t.eq(layer.numZoomLevels, 5, "(with numZoomLevels) layer numZoomLevels preserved");
t.eq(layer.alwaysInRange, false, "Always in range is set to false due to passed options.")
// three tests for minResolution, and maxResolution
options = {
minResolution: 1.5,
maxResolution: 10.5,
map: map
};
layer = new OpenLayers.Layer("test", options);
layer.initResolutions();
t.eq(layer.minResolution.toPrecision(6), (1.5).toPrecision(6),
"(without numZoomLevels) layer minResolution preserved");
t.eq(layer.maxResolution.toPrecision(6), (10.5).toPrecision(6),
"(without numZoomLevels) layer maxResolution preserved");
t.eq(layer.numZoomLevels, 3, "(without numZoomLevels) layer numZoomLevels calculated");
// three tests for minScale, maxScale, and numZoomLevels
options = {
minScale: 105,
maxScale: 15,
numZoomLevels: 10,
map: map
};
layer = new OpenLayers.Layer("test", options);
layer.initResolutions();
t.eq(layer.minScale.toPrecision(6), (105).toPrecision(6),
"(with numZoomLevels) layer minScale preserved");
t.eq(layer.maxScale.toPrecision(6), (15).toPrecision(6),
"(with numZoomLevels) layer maxScale preserved");
t.eq(layer.numZoomLevels, 10, "(with numZoomLevels) layer numZoomLevels preserved");
// three tests for minScale, and maxScale
options = {
minScale: 1555,
maxScale: 155,
map: map
};
layer = new OpenLayers.Layer("test", options);
layer.initResolutions();
t.eq(layer.minScale.toPrecision(6), (1555).toPrecision(6),
"(without numZoomLevels) layer minScale preserved");
t.eq(layer.maxScale.toPrecision(6), (155).toPrecision(6),
"(without numZoomLevels) layer maxScale preserved");
t.eq(layer.numZoomLevels, 4, "(without numZoomLevels) layer numZoomLevels calculated");
layer = new OpenLayers.Layer("test", {'projection': 'EPSG:4326', 'map': map});
layer.initResolutions();
t.eq(layer.alwaysInRange, true, "always in range true if only get projection.");
OpenLayers.Layer.prototype.alwaysInRange = false;
layer = new OpenLayers.Layer("test", {'projection': 'EPSG:4326', 'map': map});
layer.initResolutions();
t.eq(layer.alwaysInRange, false, "always in range true if overridden on prototype.");
OpenLayers.Layer.prototype.alwaysInRange = null;
map.destroy();
}
function test_Layer_visibility(t) {
t.plan(7);
var layer = new OpenLayers.Layer('Test Layer');
t.eq(layer.getVisibility(), true, "default for layer creation is visible");
layer.setVisibility(false);
t.eq(layer.getVisibility(), false, "setVisibility false works");
layer.setVisibility(true);
t.eq(layer.getVisibility(), true, "setVisibility true works");
// Need a map in order to have moveTo called.
// Tests added for #654.
var layer = new OpenLayers.Layer.WMS('Test Layer','http://example.com');
var m = new OpenLayers.Map('map');
m.addLayer(layer);
m.zoomToMaxExtent();
layermoved = false;
layer.moveTo = function() { layermoved = true; }
layer.events.register('visibilitychanged', t, function() {
this.ok(true, "Visibility changed calls layer event.");
});
layer.setVisibility(false);
t.eq(layermoved, false, "Layer didn't move when calling setvis false");
layer.setVisibility(true);
t.eq(layermoved, true, "Layer moved when calling setvis true.");
}
function test_Layer_getZoomForResolution(t) {
t.plan(12);
var layer = new OpenLayers.Layer('Test Layer');
layer.map = {};
//make some dummy resolutions
layer.resolutions = [128, 64, 32, 16, 8, 4, 2];
t.eq(layer.getZoomForResolution(200), 0, "zoom all the way out");
t.eq(layer.getZoomForResolution(25), 2, "zoom in middle");
t.eq(layer.getZoomForResolution(3), 5, "zoom allmost all the way in");
t.eq(layer.getZoomForResolution(1), 6, "zoom all the way in");
t.eq(layer.getZoomForResolution(65), 0, "smallest containing res");
t.eq(layer.getZoomForResolution(63), 1, "smallest containing res");
t.eq(layer.getZoomForResolution(65, true), 1, "closest res");
t.eq(layer.getZoomForResolution(63, true), 1, "closest res");
layer.map.fractionalZoom = true;
t.eq(layer.getZoomForResolution(64), 1,
"(fractionalZoom) correct zoom for res in array");
t.eq(layer.getZoomForResolution(48).toPrecision(6), (1.5).toPrecision(6),
"(fractionalZoom) linear scaling for res between entries");
t.eq(layer.getZoomForResolution(200).toPrecision(6), (0).toPrecision(6),
"(fractionalZoom) doesn't return zoom below zero");
t.eq(layer.getZoomForResolution(1).toPrecision(6), (layer.resolutions.length - 1).toPrecision(6),
"(fractionalZoom) doesn't return zoom above highest index");
}
function test_Layer_redraw(t) {
t.plan(11)
var name = 'Test Layer';
var url = "http://octo.metacarta.com/cgi-bin/mapserv";
var params = { map: '/mapdata/vmap_wms.map',
layers: 'basic',
format: 'image/jpeg'};
var layer = new OpenLayers.Layer.WMS(name, url, params);
t.ok(!layer.redraw(),
"redraw on an orphan layer returns false");
var map = new OpenLayers.Map('map');
map.addLayer(layer);
t.ok(!layer.redraw(),
"redraw returns false if map does not yet have a center");
map.zoomToMaxExtent();
t.ok(layer.redraw(),
"redraw returns true after map has a center");
layer.setVisibility(false);
t.ok(!layer.redraw(),
"redraw returns false if a layer is not visible");
layer.setVisibility(true);
t.ok(layer.redraw(),
"redraw returns true even if extent has not changed");
var log = {};
var onMoveend = function(e) {
log.event = e;
};
layer.events.on({"moveend": onMoveend});
layer.redraw();
layer.events.un({"moveend": onMoveend});
// test that the moveend event was triggered
t.ok(log.event, "an event was logged");
t.eq(log.event.type, "moveend", "moveend was triggered");
t.eq(log.event.zoomChanged, true, "event says zoomChanged true - poor name");
layer.moveTo = function(bounds, zoomChanged, dragging) {
var extent = layer.map.getExtent();
t.ok(bounds.equals(extent),
"redraw calls moveTo with the map extent");
t.ok(zoomChanged,
"redraw calls moveTo with zoomChanged true");
t.ok(!dragging,
"redraw calls moveTo with dragging false");
}
layer.redraw();
}
function test_layer_setIsBaseLayer(t) {
t.plan(2);
var map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer();
map.events.register("changebaselayer", t, function() {
this.ok(true, "setIsBaseLayer() trig changebaselayer event.")
});
map.addLayer(layer);
layer.setIsBaseLayer(true);
t.ok(layer.isBaseLayer, "setIsBaseLayer() change isBaseLayer property.");
}
function test_layer_setTileSize(t) {
t.plan(6);
layer = new OpenLayers.Layer();
g_MapTileSize = new OpenLayers.Size(25,67);
layer.map = {
getTileSize: function() {
return g_MapTileSize;
}
};
var layerTileSize = new OpenLayers.Size(1,1);
//TILE SIZE
layer.tileSize = layerTileSize;
//parameter
var size = new OpenLayers.Size(2,2);
layer.setTileSize(size);
t.ok(layer.tileSize.equals(size), "size paramater set correctly to layer's tile size");
t.ok(layer.imageOffset == null, "imageOffset and imageSize null when no gutters")
//set on layer
layer.tileSize = layerTileSize;
layer.setTileSize();
t.ok(layer.tileSize.equals(layerTileSize), "layer's tileSize property preserved if no parameter sent in");
//take it from map
layer.tileSize = null;
layer.setTileSize();
t.ok(layer.tileSize.equals(g_MapTileSize), "layer's tileSize property is null and so correctly taken from the map");
//GUTTERS
layer.gutter = 15;
size = new OpenLayers.Size(10,100);
layer.setTileSize(size);
var desiredImageOffset = new OpenLayers.Pixel(-15, -15);
var desiredImageSize = new OpenLayers.Size(40, 130);
t.ok(layer.imageOffset.equals(desiredImageOffset), "image offset correctly calculated");
t.ok(layer.imageSize.equals(desiredImageSize), "image size correctly calculated");
}
function test_Layer_getResolution(t) {
t.plan(1);
var layer = new OpenLayers.Layer("test");
layer.map = {
getZoom: function() {return "foo";}
};
layer.getResolutionForZoom = function(zoom) {
t.eq(zoom, "foo", "getResolution calls getResolutionForZoom");
}
layer.getResolution();
layer.map = null;
layer.destroy();
}
function test_Layer_getResolutionForZoom(t) {
t.plan(8);
var layer = new OpenLayers.Layer("test");
layer.map = {fractionalZoom: false};
layer.resolutions = ["zero", "one", "two"];
t.eq(layer.getResolutionForZoom(0), "zero",
"(fractionalZoom false) returns resolution for given index");
t.eq(layer.getResolutionForZoom(0.9), "one",
"(fractionalZoom false) returns resolution for float index");
layer.resolutions = [2, 4, 6, 8];
layer.map.fractionalZoom = true;
t.eq(layer.getResolutionForZoom(1).toPrecision(6), (4).toPrecision(6),
"(fractionalZoom true) returns resolution for integer zoom");
t.eq(layer.getResolutionForZoom(1.3).toPrecision(6), (4.6).toPrecision(6),
"(fractionalZoom true) for zoom 1.3 should be 4.6");
t.eq(layer.getResolutionForZoom(1.6).toPrecision(6), (5.2).toPrecision(6),
"(fractionalZoom true) for zoom 1.6 should be 5.2");
t.eq(layer.getResolutionForZoom(1.8).toPrecision(6), (5.6).toPrecision(6),
"(fractionalZoom true) for zoom 1.8 should be 5.6");
t.eq(layer.getResolutionForZoom(1.5).toPrecision(6), (5).toPrecision(6),
"(fractionalZoom true) returns resolution for float zoom");
t.eq(layer.getResolutionForZoom(3.5).toPrecision(6), (8).toPrecision(6),
"(fractionalZoom true) returns resolution for zoom beyond res length - 1");
}
function test_afterAdd(t) {
t.plan(1);
var map = new OpenLayers.Map("map");
var layer = new OpenLayers.Layer(null, {isBaseLayer: true});
var hasBase = false;
layer.afterAdd = function() {
hasBase = !!(layer.map && layer.map.baseLayer);
}
map.addLayer(layer);
t.eq(hasBase, true, "when afterAdd is called, map has a base layer");
}
/******
*
*
* HERE IS WHERE SOME TESTS SHOULD BE PUT TO CHECK ON THE LONLAT-PX TRANSLATION
* FUNCTIONS AND RESOLUTION AND GETEXTENT GETZOOMLEVEL, ETC
*
*
*/
function test_Layer_destroy (t) {
t.plan( 5 );
var map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer('Test Layer');
map.addLayer(layer);
layer.destroy();
t.eq( layer.name, null, "layer.name is null after destroy" );
t.eq( layer.div, null, "layer.div is null after destroy" );
t.eq( layer.map, null, "layer.map is null after destroy" );
t.eq( layer.options, null, "layer.options is null after destroy" );
t.eq(map.layers.length, 0, "layer removed from map");
map.destroy();
}
</script>
</head>
<body>
<div id="map" style="width:500px;height:500px"></div>
<div id="map2" style="width:100px;height:100px"></div>
</body>
</html>

View File

@ -1,363 +0,0 @@
<html>
<head>
<script type="text/javascript">var oldAlert = window.alert, gMess; window.alert = function(message) {gMess = message; return true;};</script>
<script type="text/javascript">window.alert = oldAlert;</script>
<script src="../../lib/OpenLayers.js"></script>
<script type="text/javascript">
var isMozilla = (navigator.userAgent.indexOf("compatible") == -1);
var layer;
var name = 'Test Layer';
var url = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/export";
var params = {layers: "show:0,2"};
function test_Layer_AGS93_constructor (t) {
var params = {layers: "show:0,2"};
t.plan( 14 );
var trans_format = "png";
if (OpenLayers.Util.alphaHack()) { trans_format = "gif"; }
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.ok( layer instanceof OpenLayers.Layer.ArcGIS93Rest, "new OpenLayers.Layer.ArcGIS93Rest returns object" );
t.eq( layer.url, url, "layer.url is correct (HTTPRequest inited)" );
t.eq( layer.params.LAYERS, "show:0,2", "params passed in correctly uppercased" );
t.eq( layer.params.FORMAT, "png", "default params correclty uppercased and copied");
t.eq(layer.isBaseLayer, true, "no transparency setting, wms is baselayer");
params.format = 'jpg';
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq( layer.params.FORMAT, "jpg", "default params correclty uppercased and overridden");
params.TRANSPARENT = "true";
var layer2 = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq(layer2.isBaseLayer, false, "transparency == 'true', wms is not baselayer");
params.TRANSPARENT = "TRUE";
var layer3 = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq(layer3.isBaseLayer, false, "transparency == 'TRUE', wms is not baselayer");
t.eq(layer3.params.FORMAT, trans_format, "transparent = TRUE causes non-image/jpeg format");
params.TRANSPARENT = "TRuE";
var layer4 = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq(layer4.isBaseLayer, false, "transparency == 'TRuE', wms is not baselayer");
t.eq(layer4.params.FORMAT, trans_format, "transparent = TRuE causes non-image/jpeg format");
params.TRANSPARENT = true;
var layer5 = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq(layer5.isBaseLayer, false, "transparency == true, wms is not baselayer");
t.eq(layer5.params.FORMAT, trans_format, "transparent = true causes non-image/jpeg format");
params.TRANSPARENT = false;
var layer6 = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.eq(layer6.isBaseLayer, true, "transparency == false, wms is baselayer");
}
function test_Layer_AGS93_addtile (t) {
var params = {layers: "show:0,2"};
t.plan( 6 );
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
var map = new OpenLayers.Map('map');
map.addLayer(layer);
var pixel = new OpenLayers.Pixel(5,6);
var tile = layer.addTile(new OpenLayers.Bounds(1,2,3,4), pixel);
tile.draw();
var img = tile.imgDiv;
var tParams = OpenLayers.Util.extend({},
OpenLayers.Util.upperCaseObject(params));
tParams = OpenLayers.Util.extend(tParams, {
FORMAT: "png", BBOX: "1,2,3,4", SIZE: "256,256", F: "image", BBOXSR: "4326", IMAGESR: "4326"
});
t.eq( img.src,
url + "?" + OpenLayers.Util.getParameterString(tParams),
"image src is created correctly via addtile" );
t.eq( tile.frame.style.top, "6px", "image top is set correctly via addtile" );
t.eq( tile.frame.style.left, "5px", "image top is set correctly via addtile" );
var firstChild = layer.div.firstChild.firstChild;
if (!isMozilla)
t.ok( true, "skipping element test outside of Mozilla");
else
t.ok( firstChild instanceof HTMLElement, "div first child is an image object" );
t.eq( firstChild.src,
url + "?" + OpenLayers.Util.getParameterString(tParams),
"div first child is correct image object" );
t.eq( tile.position.toString(), "x=5,y=6", "Position of tile is set correctly." );
map.destroy();
}
function test_Layer_AGS93_inittiles (t) {
var params = {layers: "show:0,2"};
t.plan( 2 );
var map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0,0),5);
t.eq( layer.grid.length, 7, "Grid rows is correct." );
t.eq( layer.grid[0].length, 6, "Grid cols is correct." );
map.destroy();
}
function test_Layer_AGS93_clone (t) {
var params = {layers: "show:0,2"};
t.plan(4);
var options = {tileSize: new OpenLayers.Size(500,50)};
var map = new OpenLayers.Map('map', options);
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
map.addLayer(layer);
layer.grid = [ [6, 7],
[8, 9]];
var clone = layer.clone();
t.ok( clone.grid != layer.grid, "clone does not copy grid");
t.ok( clone.tileSize.equals(layer.tileSize), "tileSize correctly cloned");
layer.tileSize.w += 40;
t.eq( clone.tileSize.w, 500, "changing layer.tileSize does not change clone.tileSize -- a fresh copy was made, not just copied reference");
t.eq( clone.alpha, layer.alpha, "alpha copied correctly");
layer.grid = null;
map.destroy();
}
function test_Layer_AGS93_isBaseLayer(t) {
var params = {layers: "show:0,2"};
t.plan(3);
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
t.ok( layer.isBaseLayer, "baselayer is true by default");
var newParams = OpenLayers.Util.extend({}, params);
newParams.transparent = "true";
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, newParams);
t.ok( !layer.isBaseLayer, "baselayer is false when transparent is set to true");
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params, {isBaseLayer: false});
t.ok( !layer.isBaseLayer, "baselayer is false when option is set to false" );
}
function test_Layer_AGS93_mergeNewParams (t) {
var params = {layers: "show:0,2"};
t.plan( 4 );
var map = new OpenLayers.Map("map");
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
var newParams = { layers: 'sooper',
chickpeas: 'png'};
map.addLayer(layer);
map.zoomToMaxExtent();
layer.redraw = function() {
t.ok(true, "layer is redrawn after new params merged");
}
layer.mergeNewParams(newParams);
t.eq( layer.params.LAYERS, "sooper", "mergeNewParams() overwrites well");
t.eq( layer.params.CHICKPEAS, "png", "mergeNewParams() adds well");
newParams.CHICKPEAS = 151;
t.eq( layer.params.CHICKPEAS, "png", "mergeNewParams() makes clean copy of hashtable");
map.destroy();
}
function test_Layer_AGS93_getFullRequestString (t) {
var params = {layers: "show:0,2"};
t.plan( 1 );
var map = new OpenLayers.Map('map');
map.projection = "xx";
tParams = { layers: 'show:0,2',
format: 'png'};
var tLayer = new OpenLayers.Layer.ArcGIS93Rest(name, url, tParams);
map.addLayer(tLayer);
str = tLayer.getFullRequestString();
var tParams = {
LAYERS: "show:0,2", FORMAT: "png"
};
t.eq(str,
url + "?" + OpenLayers.Util.getParameterString(tParams),
"getFullRequestString() adds SRS value");
map.destroy();
}
function test_Layer_AGS93_setOpacity (t) {
var params = {layers: "show:0,2"};
t.plan( 5 );
var map = new OpenLayers.Map('map');
map.projection = "xx";
tParams = { layers: 'show:0,2',
format: 'png'};
tOptions = { 'opacity': '0.5' };
var tLayer = new OpenLayers.Layer.ArcGIS93Rest(name, url, tParams, tOptions);
map.addLayer(tLayer);
map.zoomToMaxExtent();
t.eq(tLayer.opacity, "0.5", "Opacity is set correctly");
t.eq(parseFloat(tLayer.div.firstChild.firstChild.style.opacity), 0.5, "Opacity on tile is correct");
tLayer.setOpacity("0.6");
t.eq(tLayer.opacity, "0.6", "setOpacity works properly");
t.eq(parseFloat(tLayer.div.firstChild.firstChild.style.opacity), 0.6, "Opacity on tile is changed correctly");
var pixel = new OpenLayers.Pixel(5,6);
var tile = tLayer.addTile(new OpenLayers.Bounds(1,2,3,4), pixel);
tile.draw();
t.eq(parseFloat(tile.imgDiv.style.opacity), 0.6, "Tile opacity is set correctly");
map.destroy();
}
function test_Layer_AGS93_noGutters (t) {
t.plan(2);
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.ArcGIS93Rest("no gutter layer", url, params, {gutter: 0});
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0,0), 5);
var tile = layer.grid[0][0];
var request = layer.getURL(tile.bounds);
var args = OpenLayers.Util.getParameters(request);
t.eq(parseInt(args['SIZE'].split(",")[0]),
tile.size.w,
"layer without gutter requests images that are as wide as the tile");
t.eq(parseInt(args['SIZE'].split(",")[1]),
tile.size.h,
"layer without gutter requests images that are as tall as the tile");
layer.destroy();
map.destroy();
}
function test_Layer_AGS93_gutters (t) {
var params = {layers: "show:0,2"};
t.plan(2);
var gutter = 15;
var map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.ArcGIS93Rest("gutter layer", url, params, {gutter: gutter});
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0,0), 5);
var tile = layer.grid[0][0];
var request = layer.getURL(tile.bounds);
var args = OpenLayers.Util.getParameters(request);
t.eq(parseInt(args['SIZE'].split(",")[0]),
tile.size.w + (2 * gutter),
"layer with gutter requests images that are wider by twice the gutter");
t.eq(parseInt(args['SIZE'].split(",")[1]),
tile.size.h + (2 * gutter),
"layer with gutter requests images that are taller by twice the gutter");
layer.destroy();
map.destroy();
}
function test_Layer_AGS93_destroy (t) {
t.plan( 1 );
var map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(0,0), 5);
//grab a reference to one of the tiles
var tile = layer.grid[0][0];
layer.destroy();
// checks to make sure superclass (grid) destroy() was called
t.ok( layer.grid == null, "grid set to null");
}
function test_Layer_ADG93_Filter(t) {
var params = {layers: "show:0,2"};
t.plan( 9 );
layer = new OpenLayers.Layer.ArcGIS93Rest(name, url, params);
var map = new OpenLayers.Map('map');
map.addLayer(layer);
var pixel = new OpenLayers.Pixel(5,6);
var tile = layer.addTile(new OpenLayers.Bounds(1,2,3,4), pixel);
// Set up basic params.
var tParams = OpenLayers.Util.extend({}, OpenLayers.Util.upperCaseObject(params));
tParams = OpenLayers.Util.extend(tParams, {
FORMAT: "png", BBOX: "1,2,3,4", SIZE: "256,256", F: "image", BBOXSR: "4326", IMAGESR: "4326"
});
// We need to actually set the "correct" url on a dom element, because doing so encodes things not encoded by getParameterString.
var encodingHack = document.createElement("img");
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src no filter" );
layer.setLayerFilter('1', "MR_TOAD = 'FLYING'");
tParams["LAYERDEFS"] = "1:MR_TOAD = 'FLYING';";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src one filter" );
layer.setLayerFilter('1', "MR_TOAD = 'NOT FLYING'");
tParams["LAYERDEFS"] = "1:MR_TOAD = 'NOT FLYING';";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src change one filter" );
layer.setLayerFilter('2', "true = false");
tParams["LAYERDEFS"] = "1:MR_TOAD = 'NOT FLYING';2:true = false;";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src two filters" );
layer.setLayerFilter('99', "some_col > 5");
tParams["LAYERDEFS"] = "1:MR_TOAD = 'NOT FLYING';2:true = false;99:some_col > 5;";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src three filters" );
layer.clearLayerFilter('2');
tParams["LAYERDEFS"] = "1:MR_TOAD = 'NOT FLYING';99:some_col > 5;";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src removed middle filter" );
layer.clearLayerFilter('2');
tParams["LAYERDEFS"] = "1:MR_TOAD = 'NOT FLYING';99:some_col > 5;";
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src removed missing filter (no change)" );
layer.clearLayerFilter();
delete tParams["LAYERDEFS"];
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src removed all filters" );
layer.clearLayerFilter();
tile.draw();
encodingHack.src = (url + "?" + OpenLayers.Util.getParameterString(tParams));
t.eq( tile.imgDiv.src, encodingHack.src, "image src removed all (no) filters" );
}
</script>
</head>
<body>
<div id="map" style="width:500px;height:550px"></div>
</body>
</html>

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