diff --git a/doc/Jugl.js b/doc/Jugl.js new file mode 100644 index 0000000000..5dcf1a521d --- /dev/null +++ b/doc/Jugl.js @@ -0,0 +1,74 @@ +/** + * Jugl.js -- JavaScript Template Attribute Language + * This code is not yet licensed for release or distribution. + * + * Copyright 2007 Tim Schaub + */ + +/** + * Contains portions of OpenLayers.js -- OpenLayers Map Viewer Library + * + * Copyright 2005-2006 MetaCarta, Inc., released under a modified BSD license. + * Please see http://svn.openlayers.org/trunk/openlayers/repository-license.txt + * for the full text of the license. + */ + +/** + * Contains portions of Prototype.js: + * + * Prototype JavaScript framework, version 1.4.0 + * (c) 2005 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://prototype.conio.net/ + */ + +(function(){var uri="http://jugl.tschaub.net/trunk/lib/Jugl.js";var Jugl={singleFile:true};window[uri]=Jugl;})();(function(){var uri="http://jugl.tschaub.net/trunk/lib/Jugl.js";var singleFile=(typeof window[uri]=="object"&&window[uri].singleFile);var Jugl={prefix:"jugl",namespaceURI:"http://namespace.jugl.org/",scriptName:(!singleFile)?"lib/Jugl.js":"Jugl.js",getScriptLocation:function(){var scriptLocation="";var scriptName=Jugl.scriptName;var scripts=document.getElementsByTagName('script');for(var i=0;i-1)&&(index+scriptName.length==src.length)){scriptLocation=src.slice(0,-scriptName.length);break;}}} +return scriptLocation;}};if(!singleFile){var jsfiles=new Array("Jugl/Util.js","Jugl/Class.js","Jugl/Async.js","Jugl/Node.js","Jugl/Attribute.js","Jugl/Console.js","Jugl/Template.js");var allScriptTags="";var host=Jugl.getScriptLocation()+"lib/";for(var i=0;i";allScriptTags+=currentScriptTag;}else{var s=document.createElement("script");s.src=host+jsfiles[i];var h=document.getElementsByTagName("head").length?document.getElementsByTagName("head")[0]:document.body;h.appendChild(s);}} +if(allScriptTags){document.write(allScriptTags);}} +window[uri]=Jugl;})();(function(){var uri="http://jugl.tschaub.net/trunk/lib/Jugl.js";var Jugl=window[uri];Jugl.Class=function(){var Class=function(){this.initialize.apply(this,arguments);} +var extended={};var parent;for(var i=0;i + + + OL Docs + + + + + + +
+
+
+ Example # goes here +
+
+ Title goes here +
+ +
+ + Short Description goes here + +
+
+ + Related Classes go here + +
+
+
+ + \ No newline at end of file diff --git a/examples/GMLParser.html b/examples/GMLParser.html index 44718139f2..20c6ee79a7 100644 --- a/examples/GMLParser.html +++ b/examples/GMLParser.html @@ -1,5 +1,6 @@ + OpenLayers GML Parser + OpenLayers KML Parser Example +

KML Parser Example

+ +
+ +

+ Demonstrate the operation of the KML parser. +

+ +
+ +
+ This script reads data from a KML file and parses out the coordinates, appending them to a HTML string with markup tags. + This markup is dumped to an element in the page. +
- + diff --git a/examples/accessible.html b/examples/accessible.html index d0ca058719..272bd28daf 100644 --- a/examples/accessible.html +++ b/examples/accessible.html @@ -1,9 +1,11 @@ + OpenLayers Accessible Example + -

OpenLayers Example

+

Accessible Example

+ +
+
+ +

+ Demonstrate how to use the KeyboardDefaults option parameter for layer types. +

+ @@ -95,30 +109,35 @@

OpenLayers Example

-

Navigate the map in one of three ways: -

    -
  • Click on the named links to zoom and pan
  • -
  • Use following keys to pan and zoom: -
      -
    • + (zoom in)
    • -
    • - (zoom out)
    • -
    • up-arrow (pan north)
    • -
    • down-arrow (pan south)
    • -
    • left-arrow (pan east)
    • -
    • right-arrow (pan west)
    • -
    -
  • -
  • If access keys work for links in your browser, use: -
      -
    • i (zoom in)
    • -
    • o (zoom out)
    • -
    • n (pan north)
    • -
    • s (pan south)
    • -
    • e (pan east)
    • -
    • w (pan west)
    • -
    -
  • -
-

+ +
+

Navigate the map in one of three ways: +

    +
  • Click on the named links to zoom and pan
  • +
  • Use following keys to pan and zoom: +
      +
    • + (zoom in)
    • +
    • - (zoom out)
    • +
    • up-arrow (pan north)
    • +
    • down-arrow (pan south)
    • +
    • left-arrow (pan east)
    • +
    • right-arrow (pan west)
    • +
    +
  • +
  • If access keys work for links in your browser, use: +
      +
    • i (zoom in)
    • +
    • o (zoom out)
    • +
    • n (pan north)
    • +
    • s (pan south)
    • +
    • e (pan east)
    • +
    • w (pan west)
    • +
    +
  • +
+

+ + This is an example of using alternate methods to control panning and zooming. This approach uses map.pan() and map.zoom(). You'll note that to pan, additional math is necessary along with map.size() in order to set the distance to pan. +
diff --git a/examples/attribution.html b/examples/attribution.html index 5383db471f..79bef75b0e 100644 --- a/examples/attribution.html +++ b/examples/attribution.html @@ -1,36 +1,52 @@ - - - - + - - -

OpenLayers Example

-
- + map.addLayers([ol_wms, jpl_wms]); + map.addControl(new OpenLayers.Control.LayerSwitcher()); + map.addControl(new OpenLayers.Control.Attribution()); + // map.setCenter(new OpenLayers.LonLat(0, 0), 0); + map.zoomToMaxExtent(); + } + + + +

Attribution Example

+ +
+
+ +

+ Shows the use of the attribution layer option on a number of layer types. +

+ +
+ +
+ This is an example of how to add an attribution block to the OpenLayers window. In order to use an + attribution block, an attribution parameter must be set in each layer that requires attribution. In + addition, an attribution control must be added to the map. +
+ diff --git a/examples/baseLayers.html b/examples/baseLayers.html index 2114d3f08e..714c742118 100644 --- a/examples/baseLayers.html +++ b/examples/baseLayers.html @@ -1,80 +1,100 @@ - - - - - - - - - - - - + + + + + + + - - -

OpenLayers With WMS, Google, VE Example

-
-
click to add a marker to the map
-
click to remove the marker from the map
- + map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); + map.addControl( new OpenLayers.Control.LayerSwitcher() ); + map.addControl( new OpenLayers.Control.MousePosition() ); + + } + + function add() { + var url = 'http://boston.openguides.org/markers/AQUA.png'; + var sz = new OpenLayers.Size(10, 17); + var calculateOffset = function(size) { + return new OpenLayers.Pixel(-(size.w/2), -size.h); + }; + var icon = new OpenLayers.Icon(url, sz, null, calculateOffset); + marker = new OpenLayers.Marker(barcelona, icon); + markers.addMarker(marker); + + marker = new OpenLayers.Marker(madrid, icon.clone()); + markers.addMarker(marker); + + } + + function remove() { + markers.removeMarker(marker); + } + + + + +

Base Layers Example

+ +
+
+ +

+ This example shows the use base layers from multiple commercial map image providers. +

+ +
+
+ +
click to add a marker to the map
+
click to remove the marker from the map
+
+ +
+
+ diff --git a/examples/boxes.html b/examples/boxes.html index 1b18984d3d..f6ee49247b 100644 --- a/examples/boxes.html +++ b/examples/boxes.html @@ -1,47 +1,58 @@ - - - - + + + +

Boxes Example

+ +
+
+ +

+ Demonstrate marker and box type annotations on a map. +

+ +
- map.addLayers([ol_wms, boxes]); - map.addControl(new OpenLayers.Control.LayerSwitcher()); - map.zoomToMaxExtent(); - } - - - -

OpenLayers Example

-
- +
+ diff --git a/examples/buffer.html b/examples/buffer.html index 03f86b565f..87b1e7d69e 100644 --- a/examples/buffer.html +++ b/examples/buffer.html @@ -1,41 +1,54 @@ - - - - + - - -
-

Use the buffer property to control how many tiles are included - outside the visible map area. Default is 2

- + function init(){ + map = new OpenLayers.Map( 'map' ); + layer = new OpenLayers.Layer.WMS( "0 buffer: OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0", + {layers: 'basic'}, {'buffer':0} ); + map.addLayer(layer); + layer = new OpenLayers.Layer.WMS( "1 buffer: OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0", + {layers: 'basic'}, {'buffer':1} ); + map.addLayer(layer); + layer = new OpenLayers.Layer.WMS( "4 buffer: OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0", + {layers: 'basic'}, {'buffer':4} ); + map.addLayer(layer); + map.addControl(new OpenLayers.Control.LayerSwitcher()) + map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); + } + + + +

Buffer Example

+ +
+
+ +

+ This example shows the use of the buffer layer option for any layer that inherits from OpenLayers.Layer.Grid. +

+ +
+ +
+ Use the buffer property to control how many tiles are included + outside the visible map area. Default is 2. +
+ diff --git a/examples/click.html b/examples/click.html index 8a5b73a1af..b7be3f90a1 100644 --- a/examples/click.html +++ b/examples/click.html @@ -1,41 +1,53 @@ - - - - + - - -

OpenLayers Example

-
- + map.addLayers([ol_wms, jpl_wms]); + map.addControl(new OpenLayers.Control.LayerSwitcher()); + // map.setCenter(new OpenLayers.LonLat(0, 0), 0); + map.zoomToMaxExtent(); + map.events.register("click", map, function(e) { + var lonlat = map.getLonLatFromViewPortPx(e.xy); + alert("You clicked near " + lonlat.lat + " N, " + + + lonlat.lon + " E"); + }); + } + + + +

Click Event Example

+ +
+
+ +

+ This example shows the use of the register and getLonLatFromViewPortPx functions to trigger events on mouse click. +

+ +
+ +
+ diff --git a/examples/controls.html b/examples/controls.html index 07d88e6265..9fd94ec774 100644 --- a/examples/controls.html +++ b/examples/controls.html @@ -1,52 +1,61 @@ - - - - + + + +

Map Controls Example

- var dm_wms = new OpenLayers.Layer.WMS( "DM Solutions Demo", - "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap", - {layers: "bathymetry,land_fn,park,drain_fn,drainage," + - "prov_bound,fedlimit,rail,road,popplace", - transparent: "true", format: "image/png" }); +
+
- jpl_wms.setVisibility(false); - dm_wms.setVisibility(false); +

+ Attach zooming, panning, layer switcher, overview map, and permalink map controls to an OpenLayers window. +

- map.addLayers([ol_wms, jpl_wms, dm_wms]); - if (!map.getCenter()) map.zoomToMaxExtent(); - } - - - -

OpenLayers Example

- -
- + +
+ +
+ diff --git a/examples/custom-control-point.html b/examples/custom-control-point.html index ffd4e92037..24e08073ec 100644 --- a/examples/custom-control-point.html +++ b/examples/custom-control-point.html @@ -1,9 +1,10 @@ + OpenLayers Custom Control Point Examle @@ -45,7 +46,18 @@ +

Custom Control Point Example

+ +
+
+ +

+ Demonstrate the addition of a point reporting control to the OpenLayers window. +

+
+ +
diff --git a/examples/custom-control.html b/examples/custom-control.html index 1fce366b7f..ae684f05a6 100644 --- a/examples/custom-control.html +++ b/examples/custom-control.html @@ -1,49 +1,61 @@ - - - - - - -
- + notice: function (bounds) { + alert(bounds); + } + }); + + map.addLayer(layer); + map.addControl(control); + map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); + } + // --> + + + +

Custom Control Example

+ +
+
+ +

+ Demonstrate the addition of a draggable rectangle to the OpenLayers window. +

+ +
+ +
+ diff --git a/examples/custom-style.html b/examples/custom-style.html index 79bab7ae1e..b03ad8dfb9 100644 --- a/examples/custom-style.html +++ b/examples/custom-style.html @@ -1,53 +1,67 @@ - - - - - - - -
-

If you care to modify the style of any OpenLayers element, include - the default stylesheet as a link and declare any style modifications - below that link. These style declarations can be in other linked - stylesheets or in style tags. In addition, construct your map with - options that include {theme: null}. This will disable the default - method of loading the stylesheet and allow you to declare style rules - in your own linked stylesheets or style tags.

-

This example shows how to declare the font family, size, and color - for the mouse position. Note that only the style keys that you want to - modify (change from the default) need to be specified.

- + function init(){ + var options = {theme: null}; + map = new OpenLayers.Map('map', options); + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); + + map.addControl(new OpenLayers.Control.MousePosition()); + map.addLayer(layer); + map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); + } + // --> + + + +

Custom Style Example

+ +
+
+ +

+ Demonstrate changing CSS styles on controls in the OpenLayers window. +

+ +
+ +
+

If you care to modify the style of any OpenLayers element, include + the default stylesheet as a link and declare any style modifications + below that link. These style declarations can be in other linked + stylesheets or in style tags. In addition, construct your map with + options that include {theme: null}. This will disable the default + method of loading the stylesheet and allow you to declare style rules + in your own linked stylesheets or style tags.

+

This example shows how to declare the font family, size, and color + for the mouse position. Note that only the style keys that you want to + modify (change from the default) need to be specified.

+
+ diff --git a/examples/debug.html b/examples/debug.html index f0d1ae5c8e..3317de090d 100644 --- a/examples/debug.html +++ b/examples/debug.html @@ -1,64 +1,75 @@ - - - - - - -

OpenLayers Debug Example

-

To run OpenLayers in debug mode, include the following script - tag before the tag that loads OpenLayers: -

-    <script src="../lib/Firebug/firebug.js"></script>
-    
- The path to firebug.js must be relative to your - html file. With this script included calls to OpenLayers.Console - will be displayed in the Firebug console. For browsers without - the Firebug extension, the script creates a Firebug Lite console. - This console can be opened by hitting F12 or Ctrl+Shift+L - (?+Shift+L on a Mac). If you want the Firebug Lite console - to be open when the page loads, add debug="true" to the opening - html tag of your page. Open the console and click on the links below - to see console calls.

- -

The Firebug website has a complete list of - console calls. - Note that not all are supported with Firebug Lite.

- + + OpenLayers Debug Example + + + + + + +

Debug Example

+ +
+ +

+ Demonstrate console calls to a Firebug console. Requires Firefox. Mostly for developers. +

+ +
+

To run OpenLayers in debug mode, include the following script + tag before the tag that loads OpenLayers: + +

	<script src="../lib/Firebug/firebug.js"></script>
+ + The path to firebug.js must be relative to your + html file. With this script included calls to OpenLayers.Console + will be displayed in the Firebug console. For browsers without + the Firebug extension, the script creates a Firebug Lite console. + This console can be opened by hitting F12 or Ctrl+Shift+L + (?+Shift+L on a Mac). If you want the Firebug Lite console + to be open when the page loads, add debug="true" to the opening + html tag of your page. Open the console and click on the links below + to see console calls.

+ +

The Firebug website has a complete list of + console calls. + Note that not all are supported with Firebug Lite.

+
+ diff --git a/examples/doubleSetCenter.html b/examples/doubleSetCenter.html index d982532b12..10514ae17b 100644 --- a/examples/doubleSetCenter.html +++ b/examples/doubleSetCenter.html @@ -1,17 +1,36 @@ - - - - -
- - + + OpenLayers Double Set Center Example + + + + + +

Double Set Center Example

+ +
+ +

+ Demonstrate the behavior of two calls to set the center after instatiating the layer object. +

+ +
+ + + +
+ diff --git a/examples/drag-feature.html b/examples/drag-feature.html index 8dfe33958c..ae7fd15365 100644 --- a/examples/drag-feature.html +++ b/examples/drag-feature.html @@ -1,97 +1,108 @@ - - Drag Feature - - - + + +

Drag Feature Example

+ +
+ +

+ Demonstrates point, line and polygon creation and editing. +

+ +
- // --> - - - -

OpenLayers Drag Feature Example

-
-
-
    -
  • - - -
  • -
  • - - -
  • -
  • - - -
  • -
  • - - -
  • -
  • - - -
  • -
-
- +
+
    +
  • + + +
  • +
  • + + +
  • +
  • + + +
  • +
  • + + +
  • +
  • + + +
  • +
+
+ +
+ diff --git a/examples/draw-feature.html b/examples/draw-feature.html index 760fef8e71..731a804d66 100644 --- a/examples/draw-feature.html +++ b/examples/draw-feature.html @@ -1,96 +1,108 @@ - - - - - - -

OpenLayers Draw Feature Example

-
-
    -
  • - - -
  • -
  • - - -
  • -
  • - - -
  • -
  • - - -
  • -
-

Feature digitizing is in freehand mode by default. In freehand mode, the mouse is treated as a pen. - Drawing begins on mouse down, continues with every mouse move, and ends with mouse up.

-

To turn freehand mode off, hold down the shift key while digitizing. With freehand mode off, one - vertex is added with each click and double-clicks finish drawing. Freehand mode can be toggled on and off - at any time while drawing.

- - + // --> + + + +

OpenLayers Draw Feature Example

+ +
+ +

+ Demonstrate on-screen digitizing tools for point, line, and polygon creation. +

+ +
+ +
    +
  • + + +
  • +
  • + + +
  • +
  • + + +
  • +
  • + + +
  • +
+ +
+

Feature digitizing is in freehand mode by default. In freehand mode, the mouse is treated as a pen. + Drawing begins on mouse down, continues with every mouse move, and ends with mouse up.

+

To turn freehand mode off, hold down the shift key while digitizing. With freehand mode off, one + vertex is added with each click and double-clicks finish drawing. Freehand mode can be toggled on and off + at any time while drawing.

+
+ diff --git a/examples/editingtoolbar.html b/examples/editingtoolbar.html index 06e63d9f3b..42b3d27953 100644 --- a/examples/editingtoolbar.html +++ b/examples/editingtoolbar.html @@ -1,40 +1,52 @@ - - - - - + + +

Editing Toolbar Example

- vlayer = new OpenLayers.Layer.Vector( "Editable" ); - map.addLayer(vlayer); - map.addControl(new OpenLayers.Control.PanZoomBar()); - map.addControl(new OpenLayers.Control.EditingToolbar(vlayer)); - - map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); - } - // --> - - - -
-
- +
+ +

+ Demonstrate polygon, polyline and point creation and editing tools. +

+ +
+
+ +
+ diff --git a/examples/example.html b/examples/example.html index 2185a823ff..cbe0c3e05e 100644 --- a/examples/example.html +++ b/examples/example.html @@ -1,5 +1,6 @@ + OpenLayers Example - - + - - -
- + var dm_wms = new OpenLayers.Layer.WMS( "DM Solutions Demo", + "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap", + {layers: "bathymetry,land_fn,park,drain_fn,drainage," + + "prov_bound,fedlimit,rail,road,popplace", + transparent: "true", format: "image/png" }); + + map.addLayers([ol_wms, jpl_wms, dm_wms]); + map.addControl(new OpenLayers.Control.LayerSwitcher()); + // map.setCenter(new OpenLayers.LonLat(0, 0), 0); + map.zoomToMaxExtent(); + } + + + +
+ +
+

Full Screen Example

+ +
+ +

+ Demonstrate a map that fill the entire browser window. +

+ +
+ This example uses CSS to define the dimensions of the map element in order to fill the screen. + When the user resizes the window, the map size changes correspondingly. No scroll bars! +
+
+ diff --git a/examples/fullScreen2.html b/examples/fullScreen2.html new file mode 100644 index 0000000000..900eb17c27 --- /dev/null +++ b/examples/fullScreen2.html @@ -0,0 +1,51 @@ + + + Full Screen Example 2 + + + + + + +
+ +
+

Full Screen Example

+ +
+ +

+ Demonstrate a map that fill the entire browser window. +

+ +
+ This example uses CSS to define the dimensions of the map element in order to fill the screen. + When the user resizes the window, the map size changes correspondingly. No scroll bars! +
+
+ + diff --git a/examples/fullscreen.jpg b/examples/fullscreen.jpg new file mode 100644 index 0000000000..ca054fd8a1 Binary files /dev/null and b/examples/fullscreen.jpg differ diff --git a/examples/georss-markers.html b/examples/georss-markers.html index 03952b976f..7019cc3993 100644 --- a/examples/georss-markers.html +++ b/examples/georss-markers.html @@ -1,9 +1,10 @@ + OpenLayers GeoRSS Marker Example @@ -14,7 +15,7 @@ OpenLayers.ProxyHost = "/proxy/?url="; function init(){ map = new OpenLayers.Map('map', {maxResolution:'auto'}); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); map.setCenter(new OpenLayers.LonLat(0, 0), 0); @@ -28,7 +29,16 @@ -

GeoRSS in OpenLayers

+

GeoRSS Marker Example

+ +
+ +

+ Demonstrate loading a GeoRSS feed using the GeoRSS parser. +

+
+ +
diff --git a/examples/georss-serialize.html b/examples/georss-serialize.html index 94a6925cf5..f68151df53 100644 --- a/examples/georss-serialize.html +++ b/examples/georss-serialize.html @@ -1,9 +1,10 @@ + OpenLayers GeoRSS Serialize Example @@ -20,9 +21,9 @@ function init(){ g = new OpenLayers.Format.GeoRSS(); map = new OpenLayers.Map('map'); - - var wmsLayer = new OpenLayers.Layer.WMS( "OpenLayers WMS", - "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); + + var wmsLayer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); var pointLayer = new OpenLayers.Layer.Vector("Point Layer"); pointLayer.onFeatureInsert = serialize; @@ -30,17 +31,27 @@ map.addLayers([wmsLayer, pointLayer]); map.addControl(new OpenLayers.Control.EditingToolbar(pointLayer)); map.addControl(new OpenLayers.Control.MousePosition()); - - + + map.setCenter(new OpenLayers.LonLat(0, 0), 3); } -

OpenLayers Draw Point Example

+

Draw Point Example

+ +
+ +

+ Demonstrate serialization of features in a Vector layer to GeoRSS. +

+
- +
+
+ +
diff --git a/examples/georss.html b/examples/georss.html index de4c66e549..6d737e8781 100644 --- a/examples/georss.html +++ b/examples/georss.html @@ -1,9 +1,10 @@ + OpenLayers GeoRSS Example @@ -14,14 +15,14 @@ OpenLayers.ProxyHost = "/proxy/?url="; function init(){ map = new OpenLayers.Map('map', {maxResolution:'auto'}); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); map.setCenter(new OpenLayers.LonLat(0, 0), 0); map.addControl(new OpenLayers.Control.LayerSwitcher()); } function addUrl() { - var urlObj = OpenLayers.Util.getElement('url'); + var urlObj = OpenLayers.Util.getElement('url'); var value = urlObj.value; var parts = value.split("/"); var newl = new OpenLayers.Layer.GeoRSS( parts[parts.length-1], value); @@ -31,12 +32,31 @@ -

GeoRSS in OpenLayers

-

This demo uses the OpenLayers GeoRSS parser, which supports GeoRSS Simple and W3C GeoRSS. Only points are currently supported. Get the code!

-
- GeoRSS URL: -
-

The above input box allows the input of a URL to a GeoRSS feed. This feed can be local to the HTML page -- for example, entering 'georss.xml' will work by default, because there is a local file in the directory called georss.xml -- or, with a properly set up ProxyHost variable (as is used here), it will be able to load any HTTP URL which contains GeoRSS and display it. Anything else will simply have no effect.

+

GeoRSS Example

+ +
+ +

+ Display a couple of locally cached georss feeds on an a basemap. +

+
+ +
+

This demo uses the OpenLayers GeoRSS parser, which supports GeoRSS Simple and W3C GeoRSS. Only points are + currently supported. The OpenLayers GeoRSS parser will automatically connect an information bubble to the map + markers, similar to Google maps. In addition, the parser can use custom PNG icons for markers. A sample GeoRSS + file (georss.xml) is included. + +

+ GeoRSS URL: + +
+ +

The above input box allows the input of a URL to a GeoRSS feed. This feed can be local to the HTML page -- + for example, entering 'georss.xml' will work by default, because there is a local file in the directory called + georss.xml -- or, with a properly set up ProxyHost variable (as is used here), it will be able to load any + HTTP URL which contains GeoRSS and display it. Anything else will simply have no effect.

+
diff --git a/examples/georss.xml b/examples/georss.xml index 053749b943..fecf77aeac 100644 --- a/examples/georss.xml +++ b/examples/georss.xml @@ -375,4 +375,4 @@ crschmidt 2006-01-03T23:23:26.706763+00:00 - \ No newline at end of file + diff --git a/examples/getfeatureinfo.html b/examples/getfeatureinfo.html index 301398ecc9..e529d3630f 100644 --- a/examples/getfeatureinfo.html +++ b/examples/getfeatureinfo.html @@ -1,25 +1,35 @@ - - - -World Map Query - - -
-
-

CIA Factbook

-

Click a country to see statistics about the country below.

-
+ + OpenLayers Feature Info Example + + + + +

Feature Info Example

+ +
+ +

+ Demonstrates sending a GetFeatureInfo query to an OWS. Returns information about a map feature in the side DIV. +

+ +
+ +
+

CIA Factbook

+

Click a country to see statistics about the country below.

+
+
-
-
+
+ - + +
+
+ diff --git a/examples/gml-layer.html b/examples/gml-layer.html index 4e838451f6..3904c0eb31 100644 --- a/examples/gml-layer.html +++ b/examples/gml-layer.html @@ -1,9 +1,10 @@ + OpenLayers GML Layer Example @@ -16,7 +17,7 @@ function init(){ map = new OpenLayers.Map('map'); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); map.zoomToExtent(new OpenLayers.Bounds(-3.922119,44.335327,4.866943,49.553833)); @@ -25,6 +26,16 @@ +

GML Layer Example

+ +
+ +

+ Loads locally stored GML vector data on a basemap. Includes GML example file. +

+
+ +
diff --git a/examples/gml-serialize.html b/examples/gml-serialize.html index cdf4eaeb63..863af02a63 100644 --- a/examples/gml-serialize.html +++ b/examples/gml-serialize.html @@ -1,5 +1,6 @@ + OpenLayers GML Serialization Example - - - - -

OpenLayers Gutter Example

-
-

- When you render tiles with certain types of symbols, there are artifacts - at tile edges that make symbology not look continuous. In the center of - the above map (when it first loads), the large orange road is split - vertically by a tile. Open the layer switcher and change to the layer - with a 15 pixel gutter to see how the symbology looks nicer. -

- - + + + OpenLayers Gutter Example + + + + + +

Gutter Example

+ +
+ +

+ Demonstrates map tiling artifacts, and OpenLayer's facility for correcting this distortion. +

+ +
+ +
+

+ When you render tiles with certain types of symbols, there are artifacts + at tile edges that make symbology not look continuous. In the center of + the above map (when it first loads), the large orange road is split + vertically by a tile. Open the layer switcher and change to the layer + with a 15 pixel gutter to see how the symbology looks nicer. +

+
+ diff --git a/examples/image-layer.html b/examples/image-layer.html index 39ca3fbdc7..cfeef1273e 100644 --- a/examples/image-layer.html +++ b/examples/image-layer.html @@ -1,12 +1,13 @@ + OpenLayers Image Layer Example @@ -17,7 +18,7 @@ map = new OpenLayers.Map('map'); var options = {numZoomLevels: 3}; - + var graphic = new OpenLayers.Layer.Image( 'City Lights', 'http://earthtrends.wri.org/images/maps/4_m_citylights_lg.gif', @@ -26,7 +27,7 @@ options); var jpl_wms = new OpenLayers.Layer.WMS( "NASA Global Mosaic", - "http://t1.hypercube.telascience.org/tiles/landsat7", + "http://t1.hypercube.telascience.org/cgi-bin/landsat7", {layers: "landsat7"}, options); map.addLayers([graphic, jpl_wms]); @@ -36,15 +37,25 @@ -

OpenLayers Image Layer Example

-
-

- The "City Lights" layer above is created from a single web accessible - image. If you construct it without any resolution related options, - the layer will be given a single resolution based on the extent/size. - Otherwise, it behaves much like a regular layer. This is primarily - intended to be used in an overview map - where another layer type - might not make a good overview. +

Image Layer Example

+ +
+ +

+ Demonstrate a single non-tiled image as a selectable base layer.

+ +
+ +
+

+ The "City Lights" layer above is created from a single web accessible + image. If you construct it without any resolution related options, + the layer will be given a single resolution based on the extent/size. + Otherwise, it behaves much like a regular layer. This is primarily + intended to be used in an overview map - where another layer type + might not make a good overview. +

+
diff --git a/examples/kamap.html b/examples/kamap.html index 366a22f169..6c38909c04 100644 --- a/examples/kamap.html +++ b/examples/kamap.html @@ -1,9 +1,10 @@ + OpenLayers KaMap Example @@ -28,7 +29,16 @@ -

OpenLayers Example

+

KaMap Example

+ +
+ +

+ Demonstrate a tiled kamap layer as the base map, which can be pre-cached for higher performance. +

+
+ +
diff --git a/examples/kml-layer.html b/examples/kml-layer.html index da99f9c184..cfc461bbe4 100644 --- a/examples/kml-layer.html +++ b/examples/kml-layer.html @@ -2,8 +2,8 @@ @@ -16,7 +16,7 @@ function init(){ map = new OpenLayers.Map('map'); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); map.addLayer(new OpenLayers.Layer.GML("KML", "kml/lines.kml", {format: OpenLayers.Format.KML})); @@ -25,6 +25,16 @@ +

KML Layer Example

+ +
+ +

+ Demonstrates loading and displaying a KML file on top of a basemap. +

+
+ +
diff --git a/examples/layer-opacity.html b/examples/layer-opacity.html index fc46aaf7ff..2a5b2365a8 100644 --- a/examples/layer-opacity.html +++ b/examples/layer-opacity.html @@ -1,12 +1,13 @@ + OpenLayers Layer Opacity Example +

Basic Single WMS Example

+ +
+ +
Show a Simple Map
+
+ +
+ This example shows a very simple layout with minimal controls. This example uses a single WMS base layer. +
diff --git a/examples/mapserver.html b/examples/mapserver.html index 0cddfe925a..ab51fce6a9 100644 --- a/examples/mapserver.html +++ b/examples/mapserver.html @@ -1,5 +1,6 @@ + MapServer Layer + NavToolbar Demo +

NavToolbar Demo

+

+ Demo the NavToolbar, a subclass of Control.Panel which shows icons for + navigation. +

diff --git a/examples/notile.html b/examples/notile.html index fa8b20bc5b..36edfd8fd0 100644 --- a/examples/notile.html +++ b/examples/notile.html @@ -29,7 +29,11 @@ -

OpenLayers Example

+

Untiled Example

+

+ Create an untiled WMS layer using the singleTile: true, option or the deprecated + WMS.Untiled layer. +

The first layer is an old OpenLayers.Layer.WMS.Untiled layer, using a default ratio value of 1.5. diff --git a/examples/openmnnd.html b/examples/openmnnd.html index 08695673dd..f853f9b4f2 100644 --- a/examples/openmnnd.html +++ b/examples/openmnnd.html @@ -17,60 +17,60 @@ function init(){ OpenLayers.ProxyHost="/proxy/?url="; map = new OpenLayers.Map('map', {'maxResolution':'auto', maxExtent: new OpenLayers.Bounds(-203349.72008129774,4816309.33,1154786.8041952979,5472346.5), projection: 'EPSG:26915' } ); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", ["http://geoint.lmic.state.mn.us/cgi-bin/wms"], {layers: 'fsa'} ); map.addLayer(layer); - + wfs_url = "http://prototype.openmnnd.org/cgi-bin/mapserv.exe?map=openmnndwfs/openmnndwfs.map"; wms = new OpenLayers.Layer.WMS("Minnesota Parcels (WMS)", wfs_url, {'layers':'streams', 'transparent': true, 'format':'image/gif'}); - + map.addLayer(wms); - + wfs = new OpenLayers.Layer.WFS("Minnesota Streams (WFS)", wfs_url, {'typename':'streams'}, {ratio:1.25, minZoomLevel:4}); - - // preFeatureInsert can be used to set style before the feature is drawn - wfs.preFeatureInsert= function(feature) { feature.style.strokeWidth="3"; feature.style.strokeColor="blue"; + + // preFeatureInsert can be used to set style before the feature is drawn + wfs.preFeatureInsert= function(feature) { feature.style.strokeWidth="3"; feature.style.strokeColor="blue"; } wfs.onFeatureInsert = function(feature) { OpenLayers.Util.getElement('stream_features').innerHTML = feature.layer.features.length; - } + } map.addLayer(wfs); - + // Or a style can be set on the layer. pwfsstyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']); - OpenLayers.Util.extend(pwfsstyle, {'fillColor': 'green'}); - - pwfs = new OpenLayers.Layer.WFS("Minnesota Plat (WFS)", wfs_url, - {'typename':'plat'}, + OpenLayers.Util.extend(pwfsstyle, {'fillColor': 'green'}); + + pwfs = new OpenLayers.Layer.WFS("Minnesota Plat (WFS)", wfs_url, + {'typename':'plat'}, { - ratio:1.25, - minZoomLevel:8, - extractAttributes: true, + ratio:1.25, + minZoomLevel:8, + extractAttributes: true, style: pwfsstyle }); - - pwfs.onFeatureInsert= function(feature) { + + pwfs.onFeatureInsert= function(feature) { OpenLayers.Util.getElement('plat_features').innerHTML = feature.layer.features.length; } - map.addLayer(pwfs); - + map.addLayer(pwfs); + rstyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']); - OpenLayers.Util.extend(rstyle, {'strokeColor': 'white', strokeWIdth: "4"}); - rwfs = new OpenLayers.Layer.WFS("Minnesota Roads (WFS)", wfs_url, {'typename':'roads'}, + OpenLayers.Util.extend(rstyle, {'strokeColor': 'white', strokeWIdth: "4"}); + rwfs = new OpenLayers.Layer.WFS("Minnesota Roads (WFS)", wfs_url, {'typename':'roads'}, {ratio:1.25, minZoomLevel:7, extractAttributes: true, style:rstyle}); - - rwfs.onFeatureInsert= function(feature) { - OpenLayers.Util.getElement('road_features').innerHTML = feature.layer.features.length; + + rwfs.onFeatureInsert= function(feature) { + OpenLayers.Util.getElement('road_features').innerHTML = feature.layer.features.length; } - - map.addLayer(rwfs); - - map.events.register('moveend', null, function() { + + map.addLayer(rwfs); + + map.events.register('moveend', null, function() { OpenLayers.Util.getElement('stream_features').innerHTML = "0"; OpenLayers.Util.getElement('road_features').innerHTML = "0"; OpenLayers.Util.getElement('plat_features').innerHTML = "0"; - }); + }); var ls = new OpenLayers.Control.LayerSwitcher(); map.addControl(ls); @@ -84,10 +84,10 @@ map.addControl(drawControls[key]); } drawControls.selectPlat.activate(); - + map.zoomToExtent(new OpenLayers.Bounds(303232.550864,5082911.694856,305885.161263,5084486.682281)); } - + function toggleControl(element) { for(key in drawControls) { var control = drawControls[key]; @@ -100,13 +100,13 @@ } var displayedFeature = null; function feature_info_hover(feature) { - if (displayedFeature != feature && - (!feature.layer.selectedFeatures.length || + if (displayedFeature != feature && + (!feature.layer.selectedFeatures.length || (feature.layer.selectedFeatures[0] == feature))) { feature_info(feature); displayedFeature = feature; } - } + } function feature_info(feature) { var html = "

    "; for(var i in feature.attributes) @@ -119,13 +119,13 @@
      -
    • Streams: Feature Count 0
    • -
    • Plat: Feature Count 0
    • -
    • Roads: Feature Count 0
    • +
    • Streams: Feature Count 0
    • +
    • Plat: Feature Count 0
    • +
    • Roads: Feature Count 0
    -
      +
      • @@ -134,8 +134,28 @@
      • -
      -
    +
+
+

This example shows the use of a WFS service rendered using the OpenLayers vector library.

+
+

+ This is an example that shows rendering a WFS service using OpenLayer vectors in the browser. The OpenLayers code will download the GML + from the WFS service for each layer, parse it and create features using the OL vector library to draw the features on the map. For + more information on the vector library, please visit vector support wiki. + In this example there are 4 layers shown on the map. The base layer and parcel layer are created from a WMS serivce using the OpenLayers.Layer.WMS object. + The streams, roads, and plat layers are drawn from a WFS service using the OpenLayers.Layer.WFS object. +

+ +

+ Rendering WFS layers into vectors is possible, but you need to be cautions when showing the features on the map. Testing has shown that when + you renderer more than 200 vectors in the browser the performance decreases dramatically. Also features that have a lot of vertices + can cause performance issues. In this example the parcel layer is rendered as a WMS layer because at the time of developing this example + there where a handful of features that had too many vertices to render without killing the browser resources. + + There are a number of properties that can be set for each WFS layer, such color and line weight using style properties such as strokeColor and strokeWidth. + You can also get feature attributes from the WFS services using the extractAttribute property. View the source to see the example code. +

+
diff --git a/examples/outOfRangeMarkers.html b/examples/outOfRangeMarkers.html index a62ef7fd04..6f853de1c3 100644 --- a/examples/outOfRangeMarkers.html +++ b/examples/outOfRangeMarkers.html @@ -1,5 +1,6 @@ + Using maxResolution to control overlays +

Overview Map

+ +
+
+

+ Enable a small Overview Map that moves/interacts with your main map. +

The above map has an overview map control that is created with the default options. Much like a regular map, the map contained by @@ -39,7 +46,7 @@ var jpl = new OpenLayers.Layer.WMS( "NASA Global Mosaic", - "http://t1.hypercube.telascience.org/tiles/landsat7", + "http://t1.hypercube.telascience.org/cgi-bin/landsat7", {layers: "landsat7"} ); diff --git a/examples/panel.html b/examples/panel.html index d042a5946f..da81a4ccf8 100644 --- a/examples/panel.html +++ b/examples/panel.html @@ -84,6 +84,11 @@ +

Custom Control.Panel

+

+ Create a custom control.panel, styled entirely with + CSS, and add your own controls to it. +

diff --git a/examples/popups.html b/examples/popups.html index 943e0f15e9..7cdbd19d5a 100644 --- a/examples/popups.html +++ b/examples/popups.html @@ -120,7 +120,15 @@ -
+

Popup Mayhem

+ +
+
+

+ All kinds of ways to create and interact with Popups. +

+ +

If you open an anchoredbubble and switch to google, it shouldn't crash. If it does, don't release OpenLayers.

click to add Popup to map
click to add a Marker with an AnchoredBubble popup
@@ -129,5 +137,8 @@
click to remove the markers layer
marker.onscreen()?
click to destroy the popup from map
+
+ Detailed description of this example needs to be written. +
diff --git a/examples/projected-map.html b/examples/projected-map.html index 32f2681e9b..f3f3d6c928 100644 --- a/examples/projected-map.html +++ b/examples/projected-map.html @@ -55,6 +55,13 @@ +

Layer Projections

+ +
+
+

+ Use different (not default) projections with your map +

When using alternative projections, you still use OpenLayers.LonLat objects, even though the properties are actually X/Y values at that point.

diff --git a/examples/regular-polygons.html b/examples/regular-polygons.html index 9bf2fc40f2..f9614c0d03 100644 --- a/examples/regular-polygons.html +++ b/examples/regular-polygons.html @@ -79,7 +79,11 @@ -

OpenLayers Regular Polygon Example

+

OpenLayers Regular Polygon Example

+

+ Shows how to use the RegularPolygon handler to draw features with + different numbers of sides. +

diff --git a/examples/resize-features.html b/examples/resize-features.html index 395b833929..e3de79ba1f 100644 --- a/examples/resize-features.html +++ b/examples/resize-features.html @@ -82,6 +82,11 @@ +

Resize Features Programatically

+

+ Demonstration of how to use the geometry resize methods to + change feature sizes programatically. +

This example demonstrates how features can be resized. There is not yet a control built that provides a tool for resizing, but the geometry.resize diff --git a/examples/restricted-extent.html b/examples/restricted-extent.html index 2f8dc0d6ef..a77293961a 100644 --- a/examples/restricted-extent.html +++ b/examples/restricted-extent.html @@ -1,5 +1,6 @@ + OpenLayers Restricted Extent Example @@ -46,10 +36,17 @@ +

TileCache Example

+ +
+ +

+ Demonstrates a TileCache layer that loads tiles from from a web accessible disk-based cache only. +

+
-
- OpenLayers (Read-Only) TileCache Example -
from a web accessible disk-based cache only + +
diff --git a/examples/tms.html b/examples/tms.html index 6215209e14..a6605a868d 100644 --- a/examples/tms.html +++ b/examples/tms.html @@ -1,5 +1,6 @@ + OpenLayers Tiled Map Service Example @@ -13,7 +13,7 @@ function init(){ map = new OpenLayers.Map('map'); - var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); @@ -24,14 +24,14 @@ var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']); layer_style.fillOpacity = 0.2; layer_style.graphicOpacity = 1; - + /* * Blue style */ var style_blue = OpenLayers.Util.extend({}, layer_style); - style_blue.strokeColor = "blue"; - style_blue.fillColor = "blue"; - + style_blue.strokeColor = "blue"; + style_blue.fillColor = "blue"; + /* * Green style */ @@ -61,9 +61,9 @@ style_mark.graphicXOffset = -(style_mark.graphicWidth/2); // this is the default value style_mark.graphicYOffset = -style_mark.graphicHeight; style_mark.externalGraphic = "../img/marker.png"; - + var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style}); - + // create a point feature var point = new OpenLayers.Geometry.Point(-111.04, 45.68); var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue); @@ -71,7 +71,7 @@ var pointFeature2 = new OpenLayers.Feature.Vector(point2,null,style_green); var point3 = new OpenLayers.Geometry.Point(-105.04, 49.68); var pointFeature3 = new OpenLayers.Feature.Vector(point3,null,style_mark); - + // create a line feature from a list of points var pointList = []; var newPoint = point; @@ -82,7 +82,7 @@ } var lineFeature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.LineString(pointList),null,style_green); - + // create a polygon feature from a linear ring of points var pointList = []; for(var p=0; p<6; ++p) { @@ -93,12 +93,12 @@ pointList.push(newPoint); } pointList.push(pointList[0]); - + var linearRing = new OpenLayers.Geometry.LinearRing(pointList); var polygonFeature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([linearRing])); - - + + map.addLayer(vectorLayer); map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5); vectorLayer.addFeatures([pointFeature, pointFeature3, pointFeature2, lineFeature, polygonFeature]); @@ -106,10 +106,20 @@ -
+

Drawing Simple Vector Features Example

+ +
+
+

+ Shows the use of the shows drawing simple vector features, in different styles. +

+ +
+ +

This example shows drawing simple vector features -- point, line, polygon in different styles, created 'manually', by constructing the entire style - object, via 'copy', extending the default style object, and by + object, via 'copy', extending the default style object, and by inheriting the default style from the layer.

It also shows how to use external graphic files for point features and how to set their size: If either graphicWidth or graphicHeight is set, @@ -118,5 +128,8 @@ and graphicHeight are omitted, pointRadius will be used to set the size of the image, which will then be twice the value of pointRadius with the original aspect ratio.

+
+ + diff --git a/examples/vector-formats.html b/examples/vector-formats.html index 8890c81efd..3f3d607af4 100644 --- a/examples/vector-formats.html +++ b/examples/vector-formats.html @@ -19,15 +19,15 @@ top: 0; left: 1em; padding: 0; - width: 455px; + width: 517px; } #map { - width: 450px; + width: 512px; height: 225px; border: 1px solid #ccc; } #input { - width: 450px; + width: 512px; } #text { font-size: 0.85em; @@ -38,12 +38,12 @@ #info { position: relative; padding: 2em 0; - margin-left: 470px; + margin-left: 540px; } #output { font-size: 0.8em; width: 100%; - height: 500px; + height: 512px; border: 0; } p { @@ -57,15 +57,15 @@ var map, vectors, formats; function init(){ map = new OpenLayers.Map('map'); - var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", - "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); + var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); vectors = new OpenLayers.Layer.Vector("Vector Layer"); map.addLayers([wms, vectors]); map.addControl(new OpenLayers.Control.MousePosition()); map.addControl(new OpenLayers.Control.EditingToolbar(vectors)); - + var options = { hover: true, onSelect: serialize @@ -73,7 +73,7 @@ var select = new OpenLayers.Control.SelectFeature(vectors, options); map.addControl(select); select.activate(); - + formats = { wkt: new OpenLayers.Format.WKT(), geojson: new OpenLayers.Format.GeoJSON(), @@ -81,10 +81,10 @@ gml: new OpenLayers.Format.GML(), kml: new OpenLayers.Format.KML() }; - + map.setCenter(new OpenLayers.LonLat(0, 0), 1); } - + function serialize(feature) { var type = document.getElementById("formatType").value; // second argument for pretty printing (geojson only) @@ -110,7 +110,7 @@ } else { bounds.extend(features[i].geometry.getBounds()); } - + } vectors.addFeatures(features); map.zoomToExtent(bounds); @@ -138,7 +138,14 @@
-

OpenLayers Vector Formats Example

+

Vector Formats Example

+ +
+
+

+ Shows the wide variety of vector formats that open layers supports. +

+

Use the drop-down below to select the input/output format @@ -161,6 +168,10 @@

OpenLayers Vector Formats Example


+ +
+
+

Use the tools to the left to draw new polygons, lines, and points. @@ -168,5 +179,6 @@

OpenLayers Vector Formats Example

serialized version below.

+ diff --git a/examples/wfs-scribble.html b/examples/wfs-scribble.html index 7afc6d672d..8f5e1a080b 100644 --- a/examples/wfs-scribble.html +++ b/examples/wfs-scribble.html @@ -2,8 +2,8 @@ @@ -14,44 +14,44 @@ function init(){ map = new OpenLayers.Map('map', {controls: [ new OpenLayers.Control.PanZoom(), new OpenLayers.Control.Permalink() ]} ); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", - "http://labs.metacarta.com/wms-c/Basic.py", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms-c/Basic.py", {layers: 'basic'} ); map.addLayer(layer); - - layer = new OpenLayers.Layer.WFS( "Scribble WFS", - "/geoserver/wfs", - { typename: 'topp:line' }, - { - typename: 'line', - featureNS: 'http://www.openplans.org/topp', + + layer = new OpenLayers.Layer.WFS( "Scribble WFS", + "/geoserver/wfs", + { typename: 'topp:line' }, + { + typename: 'line', + featureNS: 'http://www.openplans.org/topp', extractAttributes: false } ); map.addLayer(layer); - + var p = new OpenLayers.Control.Panel({'displayClass': 'olControlEditingToolbar'}); - + df = new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Path, {handlerOptions: {'freehand': false}, 'displayClass': 'olControlDrawFeaturePath'}); - df.featureAdded = function(feature) { - feature.state = OpenLayers.State.INSERT; - feature.style['strokeColor'] = "#ff0000"; - feature.layer.drawFeature(feature); + df.featureAdded = function(feature) { + feature.state = OpenLayers.State.INSERT; + feature.style['strokeColor'] = "#ff0000"; + feature.layer.drawFeature(feature); } p.addControls([ new OpenLayers.Control.Navigation(), df ]); - + map.addControl(p); p.activateControl(p.controls[0]) map.setCenter(new OpenLayers.LonLat(0,0), 3); } function save() { - for(var i = 0; i < map.layers[1].features.length; i++) { - var f = map.layers[1].features[i]; - f.style['strokeColor'] = '#ee9900'; - map.layers[1].drawFeature(f); - } + for(var i = 0; i < map.layers[1].features.length; i++) { + var f = map.layers[1].features[i]; + f.style['strokeColor'] = '#ee9900'; + map.layers[1].drawFeature(f); + } map.layers[1].commit(); return false; - } + } function serialize(type) { var xmls = new XMLSerializer(); var serialize = new OpenLayers.Format[type]({},map.layers[1]); @@ -62,18 +62,29 @@ -

Draw Lines, Save to GeoServer

-

Using GeoServer and the WFS-T support in OpenLayers, draw on a map, - save the results, reload the page and see the results still there!
- Hold shift to turn on freehand mode while drawing.

-
- Show WFS Transaction | - Export GML | - Export GeoRSS | - Save | +

Scribble on a WFS Example

+ +
+
+

+ Shows how you can draw features and save to GeoServer. +

+
+ +
+ Using GeoServer and the WFS-T support in OpenLayers, draw on a map, save the results, reload the page and see the results still there! + Hold shift to turn on freehand mode while drawing.
+ +
+ Show WFS Transaction | + Export GML | + Export GeoRSS | + Save | Refresh (removes all newly added lines)

-
+
+ + diff --git a/examples/wfs-states.html b/examples/wfs-states.html index e2b79d6a1f..b5c323f5d5 100644 --- a/examples/wfs-states.html +++ b/examples/wfs-states.html @@ -2,8 +2,8 @@ @@ -13,24 +13,39 @@ var map, layer; function init(){ - OpenLayers.ProxyHost="/cgi-bin/proxy.cgi?url="; + OpenLayers.ProxyHost="/cgi-bin/proxy.cgi?url="; map = new OpenLayers.Map('map', {controls: [ new OpenLayers.Control.PanZoom(), new OpenLayers.Control.Permalink(), new OpenLayers.Control.MouseDefaults() ]} ); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", - "http://labs.metacarta.com/wms-c/Basic.py", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms-c/Basic.py", {layers: 'basic'} ); map.addLayer(layer); - - layer = new OpenLayers.Layer.WFS( "States WFS", - "/geoserver/wfs", + + layer = new OpenLayers.Layer.WFS( "States WFS", + "/geoserver/wfs", { typename: 'topp:states' } ); map.addLayer(layer); - + map.zoomToExtent(new OpenLayers.Bounds(-140.444336,25.115234,-44.438477,50.580078)); } -

GeoServer WFS

-
+

WFS United States (GeoServer) Example

+ +
+
+ +

+ Shows the use of the WFS United States (GeoServer) +

+ +
+ +
see: + See WFS for more info on Geoserver and WFS
+ + + +
diff --git a/examples/wfs-t.html b/examples/wfs-t.html index 44796da9f3..eb6fdd2168 100644 --- a/examples/wfs-t.html +++ b/examples/wfs-t.html @@ -2,8 +2,8 @@ @@ -13,57 +13,75 @@ function init(){ map = new OpenLayers.Map('map'); - layer = new OpenLayers.Layer.WMS( "State", + layer = new OpenLayers.Layer.WMS( "State", "http://dev.openlayers.org/geoserver/wms", {layers: 'topp:tasmania_state_boundaries'} ); map.addLayer(layer); - layer = new OpenLayers.Layer.WMS( "Water", + layer = new OpenLayers.Layer.WMS( "Water", "http://dev.openlayers.org/geoserver/wms", {layers: 'topp:tasmania_water_bodies', 'transparent': true, format: 'image/gif' } ); map.addLayer(layer); - rlayer = new OpenLayers.Layer.WFS( "Roads", + rlayer = new OpenLayers.Layer.WFS( "Roads", "http://dev.openlayers.org/geoserver/wfs", {typename: 'topp:tasmania_roads'}, - { - typename: 'tasmania_roads', - featureNS: 'http://www.openplans.org/topp', + { + typename: 'tasmania_roads', + featureNS: 'http://www.openplans.org/topp', extractAttributes: false } ); rlayer.onFeatureInsert=function(feature) { feature.style.strokeColor = "#ff0000"; feature.layer.drawFeature(feature); } map.addLayer(rlayer); - layer = new OpenLayers.Layer.WFS( "Cities", - "http://dev.openlayers.org/geoserver/wfs", {typename: 'topp:tasmania_cities'}, - { - typename: 'tasmania_cities', - featureNS: 'http://www.openplans.org/topp', + layer = new OpenLayers.Layer.WFS( "Cities", + "http://dev.openlayers.org/geoserver/wfs", {typename: 'topp:tasmania_cities'}, + { + typename: 'tasmania_cities', + featureNS: 'http://www.openplans.org/topp', extractAttributes: false } ); map.addLayer(layer); map.addControl(new OpenLayers.Control.LayerSwitcher()); var p = new OpenLayers.Control.Panel({'displayClass': 'olControlEditingToolbar'}); - + df = new OpenLayers.Control.DrawFeature(rlayer, OpenLayers.Handler.Path, {handlerOptions: {'freehand': false}, 'displayClass': 'olControlDrawFeaturePath'}); - df.featureAdded = function(feature) { - feature.state = OpenLayers.State.INSERT; - feature.style['strokeColor'] = "#0000ff"; - feature.layer.drawFeature(feature); + df.featureAdded = function(feature) { + feature.state = OpenLayers.State.INSERT; + feature.style['strokeColor'] = "#0000ff"; + feature.layer.drawFeature(feature); } dp = new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Point, {handlerOptions: {'freehand': false}, 'displayClass': 'olControlDrawFeaturePoint'}); - dp.featureAdded = function(feature) { + dp.featureAdded = function(feature) { var oldgeom = feature.geometry; feature.layer.renderer.eraseGeometry(oldgeom); feature.geometry = new OpenLayers.Geometry.MultiPoint(oldgeom); - feature.state = OpenLayers.State.INSERT; - feature.style['strokeColor'] = "#0000ff"; - feature.layer.drawFeature(feature); + feature.state = OpenLayers.State.INSERT; + feature.style['strokeColor'] = "#0000ff"; + feature.layer.drawFeature(feature); } p.addControls([ new OpenLayers.Control.Navigation(), df, dp ]); - + map.addControl(p); map.zoomToExtent(new OpenLayers.Bounds(145.51045,-44.0,149.0,-40.5)); } - Save Roads
- Save Cities
-
+ +

WFS Example

+ +
+
+

+ Shows the use of the WFS layer type. +

+ + Save Roads
+ Save Cities
+
+ +
+ This is an example of using a WFS layer type. +
+ + + + + diff --git a/examples/wfs.html b/examples/wfs.html index 9c88880e35..742b7df472 100644 --- a/examples/wfs.html +++ b/examples/wfs.html @@ -29,7 +29,11 @@ -

OpenLayers Example

+

WFS Points

+

+ Using a Layer.WFS with a featureClass, one can take in XML data + from a WFS class and display it any way you like. +

diff --git a/examples/wkt.html b/examples/wkt.html index f2bed8219a..7d8d1a926e 100644 --- a/examples/wkt.html +++ b/examples/wkt.html @@ -10,7 +10,7 @@ } #map { width: 512px; - height: 350px; + height: 512px; border: 1px solid gray; } #controls { @@ -31,15 +31,15 @@ var map, vectors, drawControls, wkt; function init(){ map = new OpenLayers.Map('map'); - var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", - "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); + var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", + "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'}); vectors = new OpenLayers.Layer.Vector("Vector Layer"); map.addLayers([wms, vectors]); map.addControl(new OpenLayers.Control.LayerSwitcher()); map.addControl(new OpenLayers.Control.MousePosition()); - + var options = { hover: true, onSelect: displayWKT @@ -54,13 +54,13 @@ OpenLayers.Handler.Polygon), hover: new OpenLayers.Control.SelectFeature(vectors, options) }; - + for(var key in drawControls) { map.addControl(drawControls[key]); } - + wkt = new OpenLayers.Format.WKT(); - + map.setCenter(new OpenLayers.LonLat(0, 0), 3); document.getElementById('noneToggle').checked = true; } @@ -75,7 +75,7 @@ } } } - + function displayWKT(feature) { var str = wkt.write(feature); // not a good idea in general, just for this demo @@ -97,7 +97,7 @@ } else { bounds.extend(features[i].geometry.getBounds()); } - + } vectors.addFeatures(features); map.zoomToExtent(bounds); @@ -110,10 +110,18 @@ -

OpenLayers WKT Example

+

WKT Example

+

+ Shows the use of WKT (Well known text) to draw features in openlayers +

-
+
+ + + +
+

See Wikipedia for a description and examples of WKT.

@@ -145,6 +153,7 @@

OpenLayers WKT Example

+
diff --git a/examples/wms-untiled.html b/examples/wms-untiled.html index bb43316476..796cad25a1 100644 --- a/examples/wms-untiled.html +++ b/examples/wms-untiled.html @@ -2,8 +2,8 @@ @@ -16,7 +16,7 @@ function init(){ map = new OpenLayers.Map( 'map' ); - layer = new OpenLayers.Layer.WMS.Untiled( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS.Untiled( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); @@ -26,6 +26,20 @@ +

WMS Untiled Example

+ +
+
+

+ Shows an example of the Untiled wms layer, which requests a single image for the entire map view. +

+
+ +
+ An untiled map will only request a single image at a time. +
+ + diff --git a/examples/wms.html b/examples/wms.html index b29e51261c..ca58081617 100644 --- a/examples/wms.html +++ b/examples/wms.html @@ -2,8 +2,8 @@ @@ -16,7 +16,7 @@ function init(){ map = new OpenLayers.Map( 'map' ); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); @@ -26,6 +26,23 @@ -
+

WMS Example

+ +
+
+

+ Shows the basic use of openlayers using a WMS layer +

+ +
+ +
+ This is an example of how to add an WMS layer to the OpenLayers window. The images are tiled in this instance if you wanted to not use a tiled WMS + please use this example and pass the option ‘singleTile’ as true. +
+ + + + diff --git a/examples/wmst.html b/examples/wmst.html index a1740c55b7..835d2529f6 100644 --- a/examples/wmst.html +++ b/examples/wmst.html @@ -3,7 +3,7 @@ @@ -13,11 +13,11 @@ function init(){ map = new OpenLayers.Map('map'); - var ol_wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", + var ol_wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'} ); var jpl_wms = new OpenLayers.Layer.WMS( "NASA Global Mosaic", - "http://t1.hypercube.telascience.org/tiles/landsat7", + "http://t1.hypercube.telascience.org/cgi-bin/landsat7", {layers: "landsat7"}); ia_wms = new OpenLayers.Layer.WMS("Nexrad","http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi?",{layers:"nexrad-n0r-wmst",transparent:true,format:'image/png',time:"2005-08-29T13:00:00Z"}); @@ -29,22 +29,31 @@ map.zoomToExtent(new OpenLayers.Bounds(-100.898437,22.148438,-78.398437,39.726563)); } function update_date() { - var string = OpenLayers.Util.getElement('year').value + "-" + - OpenLayers.Util.getElement('month').value + "-" + - OpenLayers.Util.getElement('day').value + "T" + - OpenLayers.Util.getElement('hour').value + ":" + + var string = OpenLayers.Util.getElement('year').value + "-" + + OpenLayers.Util.getElement('month').value + "-" + + OpenLayers.Util.getElement('day').value + "T" + + OpenLayers.Util.getElement('hour').value + ":" + OpenLayers.Util.getElement('minute').value + ":00"; - ia_wms.mergeNewParams({'time':string}); - - } + ia_wms.mergeNewParams({'time':string}); + + } -

OpenLayers Example

-

WMS-T example: update the times, and the radar image will change. Uses Layer.mergeNewParams to update the date element with the strings from the input fields every time one of them is changed.

-

The inputs below describe a timestamp: The minute increments can only be updated in units of 5.

+

WMS Time Example

+
+
+

+ Shows the use of the layer WMS-T (time) layer +

--T::00
+
+ WMS-T example: update the times, and the radar image will change. Uses Layer.mergeNewParams to update the date element with the strings from the input fields every time one of them is changed. + The inputs below describe a timestamp: The minute increments can only be updated in units of 5. +
+ + diff --git a/examples/worldwind.html b/examples/worldwind.html index 88b3889946..ecd698a601 100644 --- a/examples/worldwind.html +++ b/examples/worldwind.html @@ -2,8 +2,8 @@ @@ -13,13 +13,13 @@ function init(){ map = new OpenLayers.Map('map', {'maxResolution': .28125, tileSize: new OpenLayers.Size(512, 512)}); - ol_wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", + ol_wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0?", {layers: 'basic'} ); - ww = new OpenLayers.Layer.WorldWind( "Bathy", + ww = new OpenLayers.Layer.WorldWind( "Bathy", "http://worldwind25.arc.nasa.gov/tile/tile.aspx?", 36, 4, {T:"bmng.topo.bathy.200406"}); - ww2 = new OpenLayers.Layer.WorldWind( "LANDSAT", + ww2 = new OpenLayers.Layer.WorldWind( "LANDSAT", "http://worldwind25.arc.nasa.gov/tile/tile.aspx", 2.25, 4, {T:"105"}); @@ -32,9 +32,21 @@ -

OpenLayers Example

-
-

This is a demonstration of using Tiled WorldWind layers. WorldWind requires you to define a "LZTD" -- the 3rd param of the constructor -- and the number of zoom levels it supports. When a worldwind layer is not visible at a given tile level, and empty tile is placed there instead. Note that the maxResolution of the map times 512px, must be a multiple of a power of two different from the LZTD -- in this case, .28125 * 512 is 144, which is 36*4, and 2.25*64.

-

This example has a 'Bathy' layer, visible as you zoom out, and a 'landsat' layer, visible as you zoom in, both visible at zoom level 6.

- +

WorldWind layers Example

+ +
+
+

+ Shows the use of the Tiled WorldWind layers. +

+ +
+ +
+ This is a demonstration of using Tiled WorldWind layers. WorldWind requires you to define a "LZTD" -- the 3rd param of the constructor -- and the number of zoom levels it supports. When a worldwind layer is not visible at a given tile level, and empty tile is placed there instead. Note that the maxResolution of the map times 512px, must be a multiple of a power of two different from the LZTD -- in this case, .28125 * 512 is 144, which is 36*4, and 2.25*64. + This example has a 'Bathy' layer, visible as you zoom out, and a 'landsat' layer, visible as you zoom in, both visible at zoom level 6. +
+ + + diff --git a/examples/wrapDateLine.html b/examples/wrapDateLine.html index 49aba45023..6f52fbcfb0 100644 --- a/examples/wrapDateLine.html +++ b/examples/wrapDateLine.html @@ -2,8 +2,8 @@ @@ -12,11 +12,11 @@ var map; function init(){ map = new OpenLayers.Map( 'map', {maxResolution: 1.40625} ); - var mapserv = new OpenLayers.Layer.MapServer( "OpenLayers Basic", + var mapserv = new OpenLayers.Layer.MapServer( "OpenLayers Basic", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'}, {wrapDateLine: true} ); - + var kamap = new OpenLayers.Layer.KaMap( "Blue Marble NG", "http://www.openlayers.org/world/index.php", {g: "satellite", map: "world"}, @@ -30,7 +30,7 @@ {wrapDateLine: true, reproject: false}); /* TMS is broken, too */ - tms = new OpenLayers.Layer.TMS( "OpenStreetMap", + tms = new OpenLayers.Layer.TMS( "OpenStreetMap", "http://labs.metacarta.com/wms-c/Basic.py/", {layername: 'osm-map', type:'png', wrapDateLine: true} ); @@ -41,7 +41,7 @@ {'maxResolution': .28125, tileSize: new OpenLayers.Size(512, 512), wrapDateLine: true}); - + map.addLayers([mapserv, kamap, wms]); map.addControl(new OpenLayers.Control.LayerSwitcher()); map.addControl(new OpenLayers.Control.MousePosition()); @@ -52,28 +52,28 @@

Wrapping the Date Line

- Related to: - Layer.WMS, - Layer.MapServer, + Related to: + Layer.WMS, + Layer.MapServer, wrapDateLine -
- -

This example shows the use of the wrapDateLine layer option on a number of layer types.

+
+ +

Shows how to work around dateline issues, by wrapping the dateline on a number of layer types.

- This is an example that shows wrapping the date line. Wrapping the - date line is an option on the layer. + This is an example that shows wrapping the date line. Wrapping the + date line is an option on the layer.

You can do it with a 'Layer.WMS' or a 'Layer.MapServer' layer.

-    var mapserv = new OpenLayers.Layer.MapServer( "OpenLayers Basic", 
+    var mapserv = new OpenLayers.Layer.MapServer( "OpenLayers Basic",
                 "http://labs.metacarta.com/wms/vmap0",
                 {layers: 'basic'},
                 {wrapDateLine: true} );
-    
+
diff --git a/examples/xhtml.html b/examples/xhtml.html index a6fc48f9e5..7033aa4782 100644 --- a/examples/xhtml.html +++ b/examples/xhtml.html @@ -6,18 +6,31 @@ -
+

XHTML Example

+ +
+
+

+ Shows openlayers runnig in a XHTML 1.0 Strict Doctype +

+ +
-

- Valid XHTML 1.0! -

+
This example shows openlayers using a XHTML 1.0 Strict Doctype click on the below image to validate. +

+ Valid XHTML 1.0! +

+
+ + + diff --git a/examples/xml.html b/examples/xml.html index 4260535264..a70a841d12 100644 --- a/examples/xml.html +++ b/examples/xml.html @@ -28,21 +28,21 @@ ul li { padding-left: 0; } - + -

OpenLayers XML Example

-

OpenLayers has a very simple XML format class (OpenLayers.Format.XML) - that can be used to read/write XML docs. The methods available on the - XML format (or parser if you like) allow for reading and writing of the - various XML flavors used by the library - in particular the vector data - formats. It is by no means intended to be a full-fledged XML toolset. - Additional methods will be added only as needed elsewhere in the - library.

-

This page loads an XML document and demonstrates a few of the methods - available in the parser.

-

Status: XML document loading...

-

After the XML document loads, see the result of a few of the methods - below. Assume that you start with the following code: -
- - var format = new OpenLayers.Format.XML(); - -

- Sample methods - - Output: -
 
+

XML Format Example

+ +
+
+ +

+ Shows the use of the OpenLayers XML format class +

+ +
+

OpenLayers has a very simple XML format class (OpenLayers.Format.XML) + that can be used to read/write XML docs. The methods available on the + XML format (or parser if you like) allow for reading and writing of the + various XML flavors used by the library - in particular the vector data + formats. It is by no means intended to be a full-fledged XML toolset. + Additional methods will be added only as needed elsewhere in the + library.

+

This page loads an XML document and demonstrates a few of the methods + available in the parser.

+

Status: XML document loading...

+

After the XML document loads, see the result of a few of the methods + below. Assume that you start with the following code: +
+ + var format = new OpenLayers.Format.XML(); + +

+ Sample methods + + Output: +
 
+
+ + diff --git a/examples/yahoo.html b/examples/yahoo.html index f39206b2f1..d4c6c8ebb1 100644 --- a/examples/yahoo.html +++ b/examples/yahoo.html @@ -15,22 +15,36 @@ function init(){ map = new OpenLayers.Map('map'); - yahooLayer = new OpenLayers.Layer.Yahoo( "Yahoo"); + yahooLayer = new OpenLayers.Layer.Yahoo( "Yahoo"); map.addLayer(yahooLayer); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} ); map.addLayer(layer); - map.setCenter(new OpenLayers.LonLat(-5, 40), 4); map.addControl(new OpenLayers.Control.LayerSwitcher()); } -

OpenLayers Example

-
+

Yahoo Base Layer Example

+ +
+
+ +

+ Shows how you would add a yahoo layer and add the LayerSwitcher control +

+ +
+ +
+ This is an example of how to add a yahoo layer to the OpenLayers window. In order to enable a + yahoo layer. Also shown in this example is the LayerSwitcher() control for toggling between both the yahoo layer and + the open layer WMS. +
+ diff --git a/examples/yelp-georss.xml b/examples/yelp-georss.xml index 7ecb1cf4ef..3981069809 100644 --- a/examples/yelp-georss.xml +++ b/examples/yelp-georss.xml @@ -144,4 +144,4 @@ -83.4692993164 42.3581008911 - \ No newline at end of file + diff --git a/examples/zoomLevels.html b/examples/zoomLevels.html index 0468b80e4d..527dec797a 100644 --- a/examples/zoomLevels.html +++ b/examples/zoomLevels.html @@ -2,8 +2,8 @@ @@ -15,8 +15,8 @@ var map, layer; function init(){ - - var options = { + OpenLayers.DOTS_PER_INCH = 72; + var options = { // various ways of specifying similar things // resolutions: [1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.00137329101], @@ -26,28 +26,58 @@ // maxScale: 10000000, // minScale: 50000000, // numZoomLevels: 5, +// units: "dd", minResolution: "auto", - minExtent: new OpenLayers.Bounds(-1, -1, 1, 1), + minExtent: new OpenLayers.Bounds(-1, -1, 1, 1), maxResolution: "auto", - maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90), + maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90), controls: [new OpenLayers.Control.MouseDefaults()] }; map = new OpenLayers.Map( 'map' , options); - + map.addControl(new OpenLayers.Control.PanZoomBar()); - layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", + layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'}); map.addLayer(layer); map.setCenter(new OpenLayers.LonLat(lon, lat), zoom); } - + +

Zoom Level

+ +
+
+ +

+ This example shows the use of the resolutions layer option on a number of layer types. +

+
+ +
+

+ Set the extent of the viewable map using preset levels of scale available + to the user via the zoom slider bar. You can set the minimum, maximum + scales or resolutions, the number of levels in between and the minimum + and maximum geographic extents in your map's units. +

+

+ Default units for Scale are in inches. Resolution is specified in map units + per pixel where the default map units are decimal degrees(dd).
+ scale = resolution * OpenLayers.INCHES_PER_UNIT[units] * + OpenLayers.DOTS_PER_INCH
+ You can either set the scale or the resolution, there is no need to set both. +

+

+ You can do it with a ... +

+
+ diff --git a/tools/BeautifulSoup.py b/tools/BeautifulSoup.py new file mode 100644 index 0000000000..6ef8ac026a --- /dev/null +++ b/tools/BeautifulSoup.py @@ -0,0 +1,1767 @@ +"""Beautiful Soup +Elixir and Tonic +"The Screen-Scraper's Friend" +http://www.crummy.com/software/BeautifulSoup/ + +Beautiful Soup parses a (possibly invalid) XML or HTML document into a +tree representation. It provides methods and Pythonic idioms that make +it easy to navigate, search, and modify the tree. + +A well-formed XML/HTML document yields a well-formed data +structure. An ill-formed XML/HTML document yields a correspondingly +ill-formed data structure. If your document is only locally +well-formed, you can use this library to find and process the +well-formed part of it. The BeautifulSoup class + +Beautiful Soup works with Python 2.2 and up. It has no external +dependencies, but you'll have more success at converting data to UTF-8 +if you also install these three packages: + +* chardet, for auto-detecting character encodings + http://chardet.feedparser.org/ +* cjkcodecs and iconv_codec, which add more encodings to the ones supported + by stock Python. + http://cjkpython.i18n.org/ + +Beautiful Soup defines classes for two main parsing strategies: + + * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific + language that kind of looks like XML. + + * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid + or invalid. This class has web browser-like heuristics for + obtaining a sensible parse tree in the face of common HTML errors. + +Beautiful Soup also defines a class (UnicodeDammit) for autodetecting +the encoding of an HTML or XML document, and converting it to +Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. + +For more than you ever wanted to know about Beautiful Soup, see the +documentation: +http://www.crummy.com/software/BeautifulSoup/documentation.html + +""" +from __future__ import generators + +__author__ = "Leonard Richardson (leonardr@segfault.org)" +__version__ = "3.0.4" +__copyright__ = "Copyright (c) 2004-2007 Leonard Richardson" +__license__ = "PSF" + +from sgmllib import SGMLParser, SGMLParseError +import codecs +import types +import re +import sgmllib +try: + from htmlentitydefs import name2codepoint +except ImportError: + name2codepoint = {} + +#This hack makes Beautiful Soup able to parse XML with namespaces +sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') + +DEFAULT_OUTPUT_ENCODING = "utf-8" + +# First, the classes that represent markup elements. + +class PageElement: + """Contains the navigational information for some part of the page + (either a tag or a piece of text)""" + + def setup(self, parent=None, previous=None): + """Sets up the initial relations between this element and + other elements.""" + self.parent = parent + self.previous = previous + self.next = None + self.previousSibling = None + self.nextSibling = None + if self.parent and self.parent.contents: + self.previousSibling = self.parent.contents[-1] + self.previousSibling.nextSibling = self + + def replaceWith(self, replaceWith): + oldParent = self.parent + myIndex = self.parent.contents.index(self) + if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent: + # We're replacing this element with one of its siblings. + index = self.parent.contents.index(replaceWith) + if index and index < myIndex: + # Furthermore, it comes before this element. That + # means that when we extract it, the index of this + # element will change. + myIndex = myIndex - 1 + self.extract() + oldParent.insert(myIndex, replaceWith) + + def extract(self): + """Destructively rips this element out of the tree.""" + if self.parent: + try: + self.parent.contents.remove(self) + except ValueError: + pass + + #Find the two elements that would be next to each other if + #this element (and any children) hadn't been parsed. Connect + #the two. + lastChild = self._lastRecursiveChild() + nextElement = lastChild.next + + if self.previous: + self.previous.next = nextElement + if nextElement: + nextElement.previous = self.previous + self.previous = None + lastChild.next = None + + self.parent = None + if self.previousSibling: + self.previousSibling.nextSibling = self.nextSibling + if self.nextSibling: + self.nextSibling.previousSibling = self.previousSibling + self.previousSibling = self.nextSibling = None + + def _lastRecursiveChild(self): + "Finds the last element beneath this object to be parsed." + lastChild = self + while hasattr(lastChild, 'contents') and lastChild.contents: + lastChild = lastChild.contents[-1] + return lastChild + + def insert(self, position, newChild): + if (isinstance(newChild, basestring) + or isinstance(newChild, unicode)) \ + and not isinstance(newChild, NavigableString): + newChild = NavigableString(newChild) + + position = min(position, len(self.contents)) + if hasattr(newChild, 'parent') and newChild.parent != None: + # We're 'inserting' an element that's already one + # of this object's children. + if newChild.parent == self: + index = self.find(newChild) + if index and index < position: + # Furthermore we're moving it further down the + # list of this object's children. That means that + # when we extract this element, our target index + # will jump down one. + position = position - 1 + newChild.extract() + + newChild.parent = self + previousChild = None + if position == 0: + newChild.previousSibling = None + newChild.previous = self + else: + previousChild = self.contents[position-1] + newChild.previousSibling = previousChild + newChild.previousSibling.nextSibling = newChild + newChild.previous = previousChild._lastRecursiveChild() + if newChild.previous: + newChild.previous.next = newChild + + newChildsLastElement = newChild._lastRecursiveChild() + + if position >= len(self.contents): + newChild.nextSibling = None + + parent = self + parentsNextSibling = None + while not parentsNextSibling: + parentsNextSibling = parent.nextSibling + parent = parent.parent + if not parent: # This is the last element in the document. + break + if parentsNextSibling: + newChildsLastElement.next = parentsNextSibling + else: + newChildsLastElement.next = None + else: + nextChild = self.contents[position] + newChild.nextSibling = nextChild + if newChild.nextSibling: + newChild.nextSibling.previousSibling = newChild + newChildsLastElement.next = nextChild + + if newChildsLastElement.next: + newChildsLastElement.next.previous = newChildsLastElement + self.contents.insert(position, newChild) + + def findNext(self, name=None, attrs={}, text=None, **kwargs): + """Returns the first item that matches the given criteria and + appears after this Tag in the document.""" + return self._findOne(self.findAllNext, name, attrs, text, **kwargs) + + def findAllNext(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns all items that match the given criteria and appear + before after Tag in the document.""" + return self._findAll(name, attrs, text, limit, self.nextGenerator) + + def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): + """Returns the closest sibling to this Tag that matches the + given criteria and appears after this Tag in the document.""" + return self._findOne(self.findNextSiblings, name, attrs, text, + **kwargs) + + def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns the siblings of this Tag that match the given + criteria and appear after this Tag in the document.""" + return self._findAll(name, attrs, text, limit, + self.nextSiblingGenerator, **kwargs) + fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x + + def findPrevious(self, name=None, attrs={}, text=None, **kwargs): + """Returns the first item that matches the given criteria and + appears before this Tag in the document.""" + return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) + + def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, + **kwargs): + """Returns all items that match the given criteria and appear + before this Tag in the document.""" + return self._findAll(name, attrs, text, limit, self.previousGenerator, + **kwargs) + fetchPrevious = findAllPrevious # Compatibility with pre-3.x + + def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): + """Returns the closest sibling to this Tag that matches the + given criteria and appears before this Tag in the document.""" + return self._findOne(self.findPreviousSiblings, name, attrs, text, + **kwargs) + + def findPreviousSiblings(self, name=None, attrs={}, text=None, + limit=None, **kwargs): + """Returns the siblings of this Tag that match the given + criteria and appear before this Tag in the document.""" + return self._findAll(name, attrs, text, limit, + self.previousSiblingGenerator, **kwargs) + fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x + + def findParent(self, name=None, attrs={}, **kwargs): + """Returns the closest parent of this Tag that matches the given + criteria.""" + # NOTE: We can't use _findOne because findParents takes a different + # set of arguments. + r = None + l = self.findParents(name, attrs, 1) + if l: + r = l[0] + return r + + def findParents(self, name=None, attrs={}, limit=None, **kwargs): + """Returns the parents of this Tag that match the given + criteria.""" + + return self._findAll(name, attrs, None, limit, self.parentGenerator, + **kwargs) + fetchParents = findParents # Compatibility with pre-3.x + + #These methods do the real heavy lifting. + + def _findOne(self, method, name, attrs, text, **kwargs): + r = None + l = method(name, attrs, text, 1, **kwargs) + if l: + r = l[0] + return r + + def _findAll(self, name, attrs, text, limit, generator, **kwargs): + "Iterates over a generator looking for things that match." + + if isinstance(name, SoupStrainer): + strainer = name + else: + # Build a SoupStrainer + strainer = SoupStrainer(name, attrs, text, **kwargs) + results = ResultSet(strainer) + g = generator() + while True: + try: + i = g.next() + except StopIteration: + break + if i: + found = strainer.search(i) + if found: + results.append(found) + if limit and len(results) >= limit: + break + return results + + #These Generators can be used to navigate starting from both + #NavigableStrings and Tags. + def nextGenerator(self): + i = self + while i: + i = i.next + yield i + + def nextSiblingGenerator(self): + i = self + while i: + i = i.nextSibling + yield i + + def previousGenerator(self): + i = self + while i: + i = i.previous + yield i + + def previousSiblingGenerator(self): + i = self + while i: + i = i.previousSibling + yield i + + def parentGenerator(self): + i = self + while i: + i = i.parent + yield i + + # Utility methods + def substituteEncoding(self, str, encoding=None): + encoding = encoding or "utf-8" + return str.replace("%SOUP-ENCODING%", encoding) + + def toEncoding(self, s, encoding=None): + """Encodes an object to a string in some encoding, or to Unicode. + .""" + if isinstance(s, unicode): + if encoding: + s = s.encode(encoding) + elif isinstance(s, str): + if encoding: + s = s.encode(encoding) + else: + s = unicode(s) + else: + if encoding: + s = self.toEncoding(str(s), encoding) + else: + s = unicode(s) + return s + +class NavigableString(unicode, PageElement): + + def __getattr__(self, attr): + """text.string gives you text. This is for backwards + compatibility for Navigable*String, but for CData* it lets you + get the string without the CData wrapper.""" + if attr == 'string': + return self + else: + raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) + + def __unicode__(self): + return self.__str__(None) + + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): + if encoding: + return self.encode(encoding) + else: + return self + +class CData(NavigableString): + + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): + return "" % NavigableString.__str__(self, encoding) + +class ProcessingInstruction(NavigableString): + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): + output = self + if "%SOUP-ENCODING%" in output: + output = self.substituteEncoding(output, encoding) + return "" % self.toEncoding(output, encoding) + +class Comment(NavigableString): + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): + return "" % NavigableString.__str__(self, encoding) + +class Declaration(NavigableString): + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): + return "" % NavigableString.__str__(self, encoding) + +class Tag(PageElement): + + """Represents a found HTML tag with its attributes and contents.""" + + XML_SPECIAL_CHARS_TO_ENTITIES = { "'" : "squot", + '"' : "quote", + "&" : "amp", + "<" : "lt", + ">" : "gt" } + + def __init__(self, parser, name, attrs=None, parent=None, + previous=None): + "Basic constructor." + + # We don't actually store the parser object: that lets extracted + # chunks be garbage-collected + self.parserClass = parser.__class__ + self.isSelfClosing = parser.isSelfClosingTag(name) + self.name = name + if attrs == None: + attrs = [] + self.attrs = attrs + self.contents = [] + self.setup(parent, previous) + self.hidden = False + self.containsSubstitutions = False + + def get(self, key, default=None): + """Returns the value of the 'key' attribute for the tag, or + the value given for 'default' if it doesn't have that + attribute.""" + return self._getAttrMap().get(key, default) + + def has_key(self, key): + return self._getAttrMap().has_key(key) + + def __getitem__(self, key): + """tag[key] returns the value of the 'key' attribute for the tag, + and throws an exception if it's not there.""" + return self._getAttrMap()[key] + + def __iter__(self): + "Iterating over a tag iterates over its contents." + return iter(self.contents) + + def __len__(self): + "The length of a tag is the length of its list of contents." + return len(self.contents) + + def __contains__(self, x): + return x in self.contents + + def __nonzero__(self): + "A tag is non-None even if it has no contents." + return True + + def __setitem__(self, key, value): + """Setting tag[key] sets the value of the 'key' attribute for the + tag.""" + self._getAttrMap() + self.attrMap[key] = value + found = False + for i in range(0, len(self.attrs)): + if self.attrs[i][0] == key: + self.attrs[i] = (key, value) + found = True + if not found: + self.attrs.append((key, value)) + self._getAttrMap()[key] = value + + def __delitem__(self, key): + "Deleting tag[key] deletes all 'key' attributes for the tag." + for item in self.attrs: + if item[0] == key: + self.attrs.remove(item) + #We don't break because bad HTML can define the same + #attribute multiple times. + self._getAttrMap() + if self.attrMap.has_key(key): + del self.attrMap[key] + + def __call__(self, *args, **kwargs): + """Calling a tag like a function is the same as calling its + findAll() method. Eg. tag('a') returns a list of all the A tags + found within this tag.""" + return apply(self.findAll, args, kwargs) + + def __getattr__(self, tag): + #print "Getattr %s.%s" % (self.__class__, tag) + if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: + return self.find(tag[:-3]) + elif tag.find('__') != 0: + return self.find(tag) + + def __eq__(self, other): + """Returns true iff this tag has the same name, the same attributes, + and the same contents (recursively) as the given tag. + + NOTE: right now this will return false if two tags have the + same attributes in a different order. Should this be fixed?""" + if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): + return False + for i in range(0, len(self.contents)): + if self.contents[i] != other.contents[i]: + return False + return True + + def __ne__(self, other): + """Returns true iff this tag is not identical to the other tag, + as defined in __eq__.""" + return not self == other + + def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): + """Renders this tag as a string.""" + return self.__str__(encoding) + + def __unicode__(self): + return self.__str__(None) + + def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, + prettyPrint=False, indentLevel=0): + """Returns a string or Unicode representation of this tag and + its contents. To get Unicode, pass None for encoding. + + NOTE: since Python's HTML parser consumes whitespace, this + method is not certain to reproduce the whitespace present in + the original string.""" + + encodedName = self.toEncoding(self.name, encoding) + + attrs = [] + if self.attrs: + for key, val in self.attrs: + fmt = '%s="%s"' + if isString(val): + if self.containsSubstitutions and '%SOUP-ENCODING%' in val: + val = self.substituteEncoding(val, encoding) + + # The attribute value either: + # + # * Contains no embedded double quotes or single quotes. + # No problem: we enclose it in double quotes. + # * Contains embedded single quotes. No problem: + # double quotes work here too. + # * Contains embedded double quotes. No problem: + # we enclose it in single quotes. + # * Embeds both single _and_ double quotes. This + # can't happen naturally, but it can happen if + # you modify an attribute value after parsing + # the document. Now we have a bit of a + # problem. We solve it by enclosing the + # attribute in single quotes, and escaping any + # embedded single quotes to XML entities. + if '"' in val: + fmt = "%s='%s'" + # This can't happen naturally, but it can happen + # if you modify an attribute value after parsing. + if "'" in val: + val = val.replace("'", "&squot;") + + # Now we're okay w/r/t quotes. But the attribute + # value might also contain angle brackets, or + # ampersands that aren't part of entities. We need + # to escape those to XML entities too. + val = re.sub("([<>]|&(?![^\s]+;))", + lambda x: "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";", + val) + + attrs.append(fmt % (self.toEncoding(key, encoding), + self.toEncoding(val, encoding))) + close = '' + closeTag = '' + if self.isSelfClosing: + close = ' /' + else: + closeTag = '' % encodedName + + indentTag, indentContents = 0, 0 + if prettyPrint: + indentTag = indentLevel + space = (' ' * (indentTag-1)) + indentContents = indentTag + 1 + contents = self.renderContents(encoding, prettyPrint, indentContents) + if self.hidden: + s = contents + else: + s = [] + attributeString = '' + if attrs: + attributeString = ' ' + ' '.join(attrs) + if prettyPrint: + s.append(space) + s.append('<%s%s%s>' % (encodedName, attributeString, close)) + if prettyPrint: + s.append("\n") + s.append(contents) + if prettyPrint and contents and contents[-1] != "\n": + s.append("\n") + if prettyPrint and closeTag: + s.append(space) + s.append(closeTag) + if prettyPrint and closeTag and self.nextSibling: + s.append("\n") + s = ''.join(s) + return s + + def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): + return self.__str__(encoding, True) + + def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, + prettyPrint=False, indentLevel=0): + """Renders the contents of this tag as a string in the given + encoding. If encoding is None, returns a Unicode string..""" + s=[] + for c in self: + text = None + if isinstance(c, NavigableString): + text = c.__str__(encoding) + elif isinstance(c, Tag): + s.append(c.__str__(encoding, prettyPrint, indentLevel)) + if text and prettyPrint: + text = text.strip() + if text: + if prettyPrint: + s.append(" " * (indentLevel-1)) + s.append(text) + if prettyPrint: + s.append("\n") + return ''.join(s) + + #Soup methods + + def find(self, name=None, attrs={}, recursive=True, text=None, + **kwargs): + """Return only the first child of this Tag matching the given + criteria.""" + r = None + l = self.findAll(name, attrs, recursive, text, 1, **kwargs) + if l: + r = l[0] + return r + findChild = find + + def findAll(self, name=None, attrs={}, recursive=True, text=None, + limit=None, **kwargs): + """Extracts a list of Tag objects that match the given + criteria. You can specify the name of the Tag and any + attributes you want the Tag to have. + + The value of a key-value pair in the 'attrs' map can be a + string, a list of strings, a regular expression object, or a + callable that takes a string and returns whether or not the + string matches for some custom definition of 'matches'. The + same is true of the tag name.""" + generator = self.recursiveChildGenerator + if not recursive: + generator = self.childGenerator + return self._findAll(name, attrs, text, limit, generator, **kwargs) + findChildren = findAll + + # Pre-3.x compatibility methods + first = find + fetch = findAll + + def fetchText(self, text=None, recursive=True, limit=None): + return self.findAll(text=text, recursive=recursive, limit=limit) + + def firstText(self, text=None, recursive=True): + return self.find(text=text, recursive=recursive) + + #Utility methods + + def append(self, tag): + """Appends the given tag to the contents of this tag.""" + self.contents.append(tag) + + #Private methods + + def _getAttrMap(self): + """Initializes a map representation of this tag's attributes, + if not already initialized.""" + if not getattr(self, 'attrMap'): + self.attrMap = {} + for (key, value) in self.attrs: + self.attrMap[key] = value + return self.attrMap + + #Generator methods + def childGenerator(self): + for i in range(0, len(self.contents)): + yield self.contents[i] + raise StopIteration + + def recursiveChildGenerator(self): + stack = [(self, 0)] + while stack: + tag, start = stack.pop() + if isinstance(tag, Tag): + for i in range(start, len(tag.contents)): + a = tag.contents[i] + yield a + if isinstance(a, Tag) and tag.contents: + if i < len(tag.contents) - 1: + stack.append((tag, i+1)) + stack.append((a, 0)) + break + raise StopIteration + +# Next, a couple classes to represent queries and their results. +class SoupStrainer: + """Encapsulates a number of ways of matching a markup element (tag or + text).""" + + def __init__(self, name=None, attrs={}, text=None, **kwargs): + self.name = name + if isString(attrs): + kwargs['class'] = attrs + attrs = None + if kwargs: + if attrs: + attrs = attrs.copy() + attrs.update(kwargs) + else: + attrs = kwargs + self.attrs = attrs + self.text = text + + def __str__(self): + if self.text: + return self.text + else: + return "%s|%s" % (self.name, self.attrs) + + def searchTag(self, markupName=None, markupAttrs={}): + found = None + markup = None + if isinstance(markupName, Tag): + markup = markupName + markupAttrs = markup + callFunctionWithTagData = callable(self.name) \ + and not isinstance(markupName, Tag) + + if (not self.name) \ + or callFunctionWithTagData \ + or (markup and self._matches(markup, self.name)) \ + or (not markup and self._matches(markupName, self.name)): + if callFunctionWithTagData: + match = self.name(markupName, markupAttrs) + else: + match = True + markupAttrMap = None + for attr, matchAgainst in self.attrs.items(): + if not markupAttrMap: + if hasattr(markupAttrs, 'get'): + markupAttrMap = markupAttrs + else: + markupAttrMap = {} + for k,v in markupAttrs: + markupAttrMap[k] = v + attrValue = markupAttrMap.get(attr) + if not self._matches(attrValue, matchAgainst): + match = False + break + if match: + if markup: + found = markup + else: + found = markupName + return found + + def search(self, markup): + #print 'looking for %s in %s' % (self, markup) + found = None + # If given a list of items, scan it for a text element that + # matches. + if isList(markup) and not isinstance(markup, Tag): + for element in markup: + if isinstance(element, NavigableString) \ + and self.search(element): + found = element + break + # If it's a Tag, make sure its name or attributes match. + # Don't bother with Tags if we're searching for text. + elif isinstance(markup, Tag): + if not self.text: + found = self.searchTag(markup) + # If it's text, make sure the text matches. + elif isinstance(markup, NavigableString) or \ + isString(markup): + if self._matches(markup, self.text): + found = markup + else: + raise Exception, "I don't know how to match against a %s" \ + % markup.__class__ + return found + + def _matches(self, markup, matchAgainst): + #print "Matching %s against %s" % (markup, matchAgainst) + result = False + if matchAgainst == True and type(matchAgainst) == types.BooleanType: + result = markup != None + elif callable(matchAgainst): + result = matchAgainst(markup) + else: + #Custom match methods take the tag as an argument, but all + #other ways of matching match the tag name as a string. + if isinstance(markup, Tag): + markup = markup.name + if markup and not isString(markup): + markup = unicode(markup) + #Now we know that chunk is either a string, or None. + if hasattr(matchAgainst, 'match'): + # It's a regexp object. + result = markup and matchAgainst.search(markup) + elif isList(matchAgainst): + result = markup in matchAgainst + elif hasattr(matchAgainst, 'items'): + result = markup.has_key(matchAgainst) + elif matchAgainst and isString(markup): + if isinstance(markup, unicode): + matchAgainst = unicode(matchAgainst) + else: + matchAgainst = str(matchAgainst) + + if not result: + result = matchAgainst == markup + return result + +class ResultSet(list): + """A ResultSet is just a list that keeps track of the SoupStrainer + that created it.""" + def __init__(self, source): + list.__init__([]) + self.source = source + +# Now, some helper functions. + +def isList(l): + """Convenience method that works with all 2.x versions of Python + to determine whether or not something is listlike.""" + return hasattr(l, '__iter__') \ + or (type(l) in (types.ListType, types.TupleType)) + +def isString(s): + """Convenience method that works with all 2.x versions of Python + to determine whether or not something is stringlike.""" + try: + return isinstance(s, unicode) or isintance(s, basestring) + except NameError: + return isinstance(s, str) + +def buildTagMap(default, *args): + """Turns a list of maps, lists, or scalars into a single map. + Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and + NESTING_RESET_TAGS maps out of lists and partial maps.""" + built = {} + for portion in args: + if hasattr(portion, 'items'): + #It's a map. Merge it. + for k,v in portion.items(): + built[k] = v + elif isList(portion): + #It's a list. Map each item to the default. + for k in portion: + built[k] = default + else: + #It's a scalar. Map it to the default. + built[portion] = default + return built + +# Now, the parser classes. + +class BeautifulStoneSoup(Tag, SGMLParser): + + """This class contains the basic parser and search code. It defines + a parser that knows nothing about tag behavior except for the + following: + + You can't close a tag without closing all the tags it encloses. + That is, "" actually means + "". + + [Another possible explanation is "", but since + this class defines no SELF_CLOSING_TAGS, it will never use that + explanation.] + + This class is useful for parsing XML or made-up markup languages, + or when BeautifulSoup makes an assumption counter to what you were + expecting.""" + + XML_ENTITY_LIST = {} + for i in Tag.XML_SPECIAL_CHARS_TO_ENTITIES.values(): + XML_ENTITY_LIST[i] = True + + SELF_CLOSING_TAGS = {} + NESTABLE_TAGS = {} + RESET_NESTING_TAGS = {} + QUOTE_TAGS = {} + + MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), + lambda x: x.group(1) + ' />'), + (re.compile(']*)>'), + lambda x: '') + ] + + ROOT_TAG_NAME = u'[document]' + + HTML_ENTITIES = "html" + XML_ENTITIES = "xml" + + def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, + markupMassage=True, smartQuotesTo=XML_ENTITIES, + convertEntities=None, selfClosingTags=None): + """The Soup object is initialized as the 'root tag', and the + provided markup (which can be a string or a file-like object) + is fed into the underlying parser. + + sgmllib will process most bad HTML, and the BeautifulSoup + class has some tricks for dealing with some HTML that kills + sgmllib, but Beautiful Soup can nonetheless choke or lose data + if your data uses self-closing tags or declarations + incorrectly. + + By default, Beautiful Soup uses regexes to sanitize input, + avoiding the vast majority of these problems. If the problems + don't apply to you, pass in False for markupMassage, and + you'll get better performance. + + The default parser massage techniques fix the two most common + instances of invalid HTML that choke sgmllib: + +
(No space between name of closing tag and tag close) + (Extraneous whitespace in declaration) + + You can pass in a custom list of (RE object, replace method) + tuples to get Beautiful Soup to scrub your input the way you + want.""" + + self.parseOnlyThese = parseOnlyThese + self.fromEncoding = fromEncoding + self.smartQuotesTo = smartQuotesTo + self.convertEntities = convertEntities + if self.convertEntities: + # It doesn't make sense to convert encoded characters to + # entities even while you're converting entities to Unicode. + # Just convert it all to Unicode. + self.smartQuotesTo = None + self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) + SGMLParser.__init__(self) + + if hasattr(markup, 'read'): # It's a file-type object. + markup = markup.read() + self.markup = markup + self.markupMassage = markupMassage + try: + self._feed() + except StopParsing: + pass + self.markup = None # The markup can now be GCed + + def _feed(self, inDocumentEncoding=None): + # Convert the document to Unicode. + markup = self.markup + if isinstance(markup, unicode): + if not hasattr(self, 'originalEncoding'): + self.originalEncoding = None + else: + dammit = UnicodeDammit\ + (markup, [self.fromEncoding, inDocumentEncoding], + smartQuotesTo=self.smartQuotesTo) + markup = dammit.unicode + self.originalEncoding = dammit.originalEncoding + if markup: + if self.markupMassage: + if not isList(self.markupMassage): + self.markupMassage = self.MARKUP_MASSAGE + for fix, m in self.markupMassage: + markup = fix.sub(m, markup) + self.reset() + + SGMLParser.feed(self, markup) + # Close out any unfinished strings and close all the open tags. + self.endData() + while self.currentTag.name != self.ROOT_TAG_NAME: + self.popTag() + + def __getattr__(self, methodName): + """This method routes method call requests to either the SGMLParser + superclass or the Tag superclass, depending on the method name.""" + #print "__getattr__ called on %s.%s" % (self.__class__, methodName) + + if methodName.find('start_') == 0 or methodName.find('end_') == 0 \ + or methodName.find('do_') == 0: + return SGMLParser.__getattr__(self, methodName) + elif methodName.find('__') != 0: + return Tag.__getattr__(self, methodName) + else: + raise AttributeError + + def isSelfClosingTag(self, name): + """Returns true iff the given string is the name of a + self-closing tag according to this parser.""" + return self.SELF_CLOSING_TAGS.has_key(name) \ + or self.instanceSelfClosingTags.has_key(name) + + def reset(self): + Tag.__init__(self, self, self.ROOT_TAG_NAME) + self.hidden = 1 + SGMLParser.reset(self) + self.currentData = [] + self.currentTag = None + self.tagStack = [] + self.quoteStack = [] + self.pushTag(self) + + def popTag(self): + tag = self.tagStack.pop() + # Tags with just one string-owning child get the child as a + # 'string' property, so that soup.tag.string is shorthand for + # soup.tag.contents[0] + if len(self.currentTag.contents) == 1 and \ + isinstance(self.currentTag.contents[0], NavigableString): + self.currentTag.string = self.currentTag.contents[0] + + #print "Pop", tag.name + if self.tagStack: + self.currentTag = self.tagStack[-1] + return self.currentTag + + def pushTag(self, tag): + #print "Push", tag.name + if self.currentTag: + self.currentTag.append(tag) + self.tagStack.append(tag) + self.currentTag = self.tagStack[-1] + + def endData(self, containerClass=NavigableString): + if self.currentData: + currentData = ''.join(self.currentData) + if not currentData.strip(): + if '\n' in currentData: + currentData = '\n' + else: + currentData = ' ' + self.currentData = [] + if self.parseOnlyThese and len(self.tagStack) <= 1 and \ + (not self.parseOnlyThese.text or \ + not self.parseOnlyThese.search(currentData)): + return + o = containerClass(currentData) + o.setup(self.currentTag, self.previous) + if self.previous: + self.previous.next = o + self.previous = o + self.currentTag.contents.append(o) + + + def _popToTag(self, name, inclusivePop=True): + """Pops the tag stack up to and including the most recent + instance of the given tag. If inclusivePop is false, pops the tag + stack up to but *not* including the most recent instqance of + the given tag.""" + #print "Popping to %s" % name + if name == self.ROOT_TAG_NAME: + return + + numPops = 0 + mostRecentTag = None + for i in range(len(self.tagStack)-1, 0, -1): + if name == self.tagStack[i].name: + numPops = len(self.tagStack)-i + break + if not inclusivePop: + numPops = numPops - 1 + + for i in range(0, numPops): + mostRecentTag = self.popTag() + return mostRecentTag + + def _smartPop(self, name): + + """We need to pop up to the previous tag of this type, unless + one of this tag's nesting reset triggers comes between this + tag and the previous tag of this type, OR unless this tag is a + generic nesting trigger and another generic nesting trigger + comes between this tag and the previous tag of this type. + + Examples: +

FooBar

should pop to 'p', not 'b'. +

FooBar

should pop to 'table', not 'p'. +

Foo

Bar

should pop to 'tr', not 'p'. +

FooBar

should pop to 'p', not 'b'. + +

    • *
    • * should pop to 'ul', not the first 'li'. +
  • ** should pop to 'table', not the first 'tr' + tag should + implicitly close the previous tag within the same
    ** should pop to 'tr', not the first 'td' + """ + + nestingResetTriggers = self.NESTABLE_TAGS.get(name) + isNestable = nestingResetTriggers != None + isResetNesting = self.RESET_NESTING_TAGS.has_key(name) + popTo = None + inclusive = True + for i in range(len(self.tagStack)-1, 0, -1): + p = self.tagStack[i] + if (not p or p.name == name) and not isNestable: + #Non-nestable tags get popped to the top or to their + #last occurance. + popTo = name + break + if (nestingResetTriggers != None + and p.name in nestingResetTriggers) \ + or (nestingResetTriggers == None and isResetNesting + and self.RESET_NESTING_TAGS.has_key(p.name)): + + #If we encounter one of the nesting reset triggers + #peculiar to this tag, or we encounter another tag + #that causes nesting to reset, pop up to but not + #including that tag. + popTo = p.name + inclusive = False + break + p = p.parent + if popTo: + self._popToTag(popTo, inclusive) + + def unknown_starttag(self, name, attrs, selfClosing=0): + #print "Start tag %s: %s" % (name, attrs) + if self.quoteStack: + #This is not a real tag. + #print "<%s> is not real!" % name + attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) + self.handle_data('<%s%s>' % (name, attrs)) + return + self.endData() + + if not self.isSelfClosingTag(name) and not selfClosing: + self._smartPop(name) + + if self.parseOnlyThese and len(self.tagStack) <= 1 \ + and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): + return + + tag = Tag(self, name, attrs, self.currentTag, self.previous) + if self.previous: + self.previous.next = tag + self.previous = tag + self.pushTag(tag) + if selfClosing or self.isSelfClosingTag(name): + self.popTag() + if name in self.QUOTE_TAGS: + #print "Beginning quote (%s)" % name + self.quoteStack.append(name) + self.literal = 1 + return tag + + def unknown_endtag(self, name): + #print "End tag %s" % name + if self.quoteStack and self.quoteStack[-1] != name: + #This is not a real end tag. + #print " is not real!" % name + self.handle_data('' % name) + return + self.endData() + self._popToTag(name) + if self.quoteStack and self.quoteStack[-1] == name: + self.quoteStack.pop() + self.literal = (len(self.quoteStack) > 0) + + def handle_data(self, data): + self.currentData.append(data) + + def _toStringSubclass(self, text, subclass): + """Adds a certain piece of text to the tree as a NavigableString + subclass.""" + self.endData() + self.handle_data(text) + self.endData(subclass) + + def handle_pi(self, text): + """Handle a processing instruction as a ProcessingInstruction + object, possibly one with a %SOUP-ENCODING% slot into which an + encoding will be plugged later.""" + if text[:3] == "xml": + text = "xml version='1.0' encoding='%SOUP-ENCODING%'" + self._toStringSubclass(text, ProcessingInstruction) + + def handle_comment(self, text): + "Handle comments as Comment objects." + self._toStringSubclass(text, Comment) + + def handle_charref(self, ref): + "Handle character references as data." + if self.convertEntities in [self.HTML_ENTITIES, + self.XML_ENTITIES]: + data = unichr(int(ref)) + else: + data = '&#%s;' % ref + self.handle_data(data) + + def handle_entityref(self, ref): + """Handle entity references as data, possibly converting known + HTML entity references to the corresponding Unicode + characters.""" + data = None + if self.convertEntities == self.HTML_ENTITIES or \ + (self.convertEntities == self.XML_ENTITIES and \ + self.XML_ENTITY_LIST.get(ref)): + try: + data = unichr(name2codepoint[ref]) + except KeyError: + pass + if not data: + data = '&%s;' % ref + self.handle_data(data) + + def handle_decl(self, data): + "Handle DOCTYPEs and the like as Declaration objects." + self._toStringSubclass(data, Declaration) + + def parse_declaration(self, i): + """Treat a bogus SGML declaration as raw data. Treat a CDATA + declaration as a CData object.""" + j = None + if self.rawdata[i:i+9] == '', i) + if k == -1: + k = len(self.rawdata) + data = self.rawdata[i+9:k] + j = k+3 + self._toStringSubclass(data, CData) + else: + try: + j = SGMLParser.parse_declaration(self, i) + except SGMLParseError: + toHandle = self.rawdata[i:] + self.handle_data(toHandle) + j = i + len(toHandle) + return j + +class BeautifulSoup(BeautifulStoneSoup): + + """This parser knows the following facts about HTML: + + * Some tags have no closing tag and should be interpreted as being + closed as soon as they are encountered. + + * The text inside some tags (ie. 'script') may contain tags which + are not really part of the document and which should be parsed + as text, not tags. If you want to parse the text as tags, you can + always fetch it and parse it explicitly. + + * Tag nesting rules: + + Most tags can't be nested at all. For instance, the occurance of + a

    tag should implicitly close the previous

    tag. + +

    Para1

    Para2 + should be transformed into: +

    Para1

    Para2 + + Some tags can be nested arbitrarily. For instance, the occurance + of a

    tag should _not_ implicitly close the previous +
    tag. + + Alice said:
    Bob said:
    Blah + should NOT be transformed into: + Alice said:
    Bob said:
    Blah + + Some tags can be nested, but the nesting is reset by the + interposition of other tags. For instance, a
    , + but not close a tag in another table. + +
    BlahBlah + should be transformed into: +
    BlahBlah + but, + Blah
    Blah + should NOT be transformed into + Blah
    Blah + + Differing assumptions about tag nesting rules are a major source + of problems with the BeautifulSoup class. If BeautifulSoup is not + treating as nestable a tag your page author treats as nestable, + try ICantBelieveItsBeautifulSoup, MinimalSoup, or + BeautifulStoneSoup before writing your own subclass.""" + + def __init__(self, *args, **kwargs): + if not kwargs.has_key('smartQuotesTo'): + kwargs['smartQuotesTo'] = self.HTML_ENTITIES + BeautifulStoneSoup.__init__(self, *args, **kwargs) + + SELF_CLOSING_TAGS = buildTagMap(None, + ['br' , 'hr', 'input', 'img', 'meta', + 'spacer', 'link', 'frame', 'base']) + + QUOTE_TAGS = {'script': None} + + #According to the HTML standard, each of these inline tags can + #contain another tag of the same type. Furthermore, it's common + #to actually use these tags this way. + NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', + 'center'] + + #According to the HTML standard, these block tags can contain + #another tag of the same type. Furthermore, it's common + #to actually use these tags this way. + NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del'] + + #Lists can contain other lists, but there are restrictions. + NESTABLE_LIST_TAGS = { 'ol' : [], + 'ul' : [], + 'li' : ['ul', 'ol'], + 'dl' : [], + 'dd' : ['dl'], + 'dt' : ['dl'] } + + #Tables can contain other tables, but there are restrictions. + NESTABLE_TABLE_TAGS = {'table' : [], + 'tr' : ['table', 'tbody', 'tfoot', 'thead'], + 'td' : ['tr'], + 'th' : ['tr'], + 'thead' : ['table'], + 'tbody' : ['table'], + 'tfoot' : ['table'], + } + + NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre'] + + #If one of these tags is encountered, all tags up to the next tag of + #this type are popped. + RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', + NON_NESTABLE_BLOCK_TAGS, + NESTABLE_LIST_TAGS, + NESTABLE_TABLE_TAGS) + + NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, + NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) + + # Used to detect the charset in a META tag; see start_meta + CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)") + + def start_meta(self, attrs): + """Beautiful Soup can detect a charset included in a META tag, + try to convert the document to that charset, and re-parse the + document from the beginning.""" + httpEquiv = None + contentType = None + contentTypeIndex = None + tagNeedsEncodingSubstitution = False + + for i in range(0, len(attrs)): + key, value = attrs[i] + key = key.lower() + if key == 'http-equiv': + httpEquiv = value + elif key == 'content': + contentType = value + contentTypeIndex = i + + if httpEquiv and contentType: # It's an interesting meta tag. + match = self.CHARSET_RE.search(contentType) + if match: + if getattr(self, 'declaredHTMLEncoding') or \ + (self.originalEncoding == self.fromEncoding): + # This is our second pass through the document, or + # else an encoding was specified explicitly and it + # worked. Rewrite the meta tag. + newAttr = self.CHARSET_RE.sub\ + (lambda(match):match.group(1) + + "%SOUP-ENCODING%", value) + attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], + newAttr) + tagNeedsEncodingSubstitution = True + else: + # This is our first pass through the document. + # Go through it again with the new information. + newCharset = match.group(3) + if newCharset and newCharset != self.originalEncoding: + self.declaredHTMLEncoding = newCharset + self._feed(self.declaredHTMLEncoding) + raise StopParsing + tag = self.unknown_starttag("meta", attrs) + if tag and tagNeedsEncodingSubstitution: + tag.containsSubstitutions = True + +class StopParsing(Exception): + pass + +class ICantBelieveItsBeautifulSoup(BeautifulSoup): + + """The BeautifulSoup class is oriented towards skipping over + common HTML errors like unclosed tags. However, sometimes it makes + errors of its own. For instance, consider this fragment: + + FooBar + + This is perfectly valid (if bizarre) HTML. However, the + BeautifulSoup class will implicitly close the first b tag when it + encounters the second 'b'. It will think the author wrote + "FooBar", and didn't close the first 'b' tag, because + there's no real-world reason to bold something that's already + bold. When it encounters '' it will close two more 'b' + tags, for a grand total of three tags closed instead of two. This + can throw off the rest of your document structure. The same is + true of a number of other tags, listed below. + + It's much more common for someone to forget to close a 'b' tag + than to actually use nested 'b' tags, and the BeautifulSoup class + handles the common case. This class handles the not-co-common + case: where you can't believe someone wrote what they did, but + it's valid HTML and BeautifulSoup screwed up by assuming it + wouldn't be.""" + + I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ + ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', + 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', + 'big'] + + I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript'] + + NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, + I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, + I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) + +class MinimalSoup(BeautifulSoup): + """The MinimalSoup class is for parsing HTML that contains + pathologically bad markup. It makes no assumptions about tag + nesting, but it does know which tags are self-closing, that +