Openlayers3实战(三)

来源:互联网 发布:js调用div 编辑:程序博客网 时间:2024/05/29 11:06

3控制与交互

3.1显示一个线状比例尺

还有一个典型的比例尺小部件。Openlayers3为比例尺提供了ol.control.ScaleLine。

3.1.1创建一个现状比例尺

任务:

1、 打开map.html文件

2、  在地图配置的地方添加如下代码

 

controls:ol.control.defaults().extend([

  new ol.control.ScaleLine()

]),

 

3、  保存并访问网页

 

 

3.1.2移动比例尺位置

你会发现标尺来阅读这些意象有点难。有几种方法,来提高比例尺的可见度。如果你想在地图试图内控制,那么你可以通过css样式来实现。

.ol-scale-line,.ol-scale-line:not([ie8andbelow]) {

 background: black;

 padding: 5px;

}

但是,把比例尺放在地图上可能不大好看,你可以通过创建一个html元素用来盛放你的比例尺控件。

任务:

1、  打开你的map.html文档,在body中添加一个div元素。

 

<divid="scale-line"class="scale-line"></div>

 

2、  修改你的比例尺控件。

 

controls: ol.control.defaults().extend([

  new ol.control.ScaleLine({className:'ol-scale-line', target:document.getElementById('scale-line')})

]),

添加如下样式

.scale-line {

 position: absolute;

 top: 350px;

}

.ol-scale-line {

 position: relative;

 bottom: 0px;

 left: 0px;

}

 

3、  访问你的map页面。

(时间可贵,我就不翻译了,把时间用在翻译API)

 

3.2. Selecting Features

As we’ve seen in the layers module, we canpull features as vectors and draw them on top of a base map. One of theadvantages of serving vector data is that users can interact with the data. Inthis example, we create a vector layer where users can select and view featureinformation.

The previous example demonstrated the useof an ol.control.Control on the map. Controls have a visualrepresentation on the map or add DOM elements to the document. An ol.interaction.Interaction is responsible for handling userinteraction, but typically has no visual representation. This exampledemonstrates the use of the ol.interaction.Select for interacting with features fromvector layers.

3.2.1. Createa Vector Layer and a Select Interaction

Tasks

  1. Let’s start with the vector layer example from a previous section. Open map.html in your text editor and make sure it looks something like the following:

2.  <!doctype html>

3.  <htmllang="en">

4.    <head>

5.      <linkrel="stylesheet"href="ol3/ol.css"type="text/css">

6.      <style>

7.      #map {

8.        height:256px;

9.        width:512px;

10.    }

11.    </style>

12.    <scriptsrc="ol3/ol.js"type="text/javascript"></script>

13.    <title>OpenLayers 3 example</title>

14.  </head>

15.  <body>

16.    <h1>My Map</h1>

17.    <divid="map"></div>

18.    <scripttype="text/javascript">

19.     var map=new ol.Map({

20.       interactions: ol.interaction.defaults().extend([

21.         new ol.interaction.Select({

22.           style:new ol.style.Style({

23.             image:new ol.style.Circle({

24.                radius:5,

25.                fill:new ol.style.Fill({

26.                  color:'#FF0000'

27.                }),

28.                stroke:new ol.style.Stroke({

29.                  color:'#000000'

30.                })

31.              })

32.           })

33.         })

34.       ]),

35.       target:'map',

36.       layers: [

37.         new ol.layer.Tile({

38.           title:"Global Imagery",

39.           source:new ol.source.TileWMS({

40.              url:'http://maps.opengeo.org/geowebcache/service/wms',

41.              params: {LAYERS:'bluemarble', VERSION:'1.1.1'}

42.           })

43.         }),

44.         new ol.layer.Vector({

45.           title:'Earthquakes',

46.           source:new ol.source.GeoJSON({

47.              url:'data/layers/7day-M2.5.json'

48.           }),

49.           style:new ol.style.Style({

50.              image:new ol.style.Circle({

51.                radius:5,

52.                fill:new ol.style.Fill({

53.                  color:'#0000FF'

54.               }),

55.                stroke:new ol.style.Stroke({

56.                  color:'#000000'

57.                })

58.              })

59.           })

60.         })

61.       ],

62.       view:new ol.View({

63.         projection:'EPSG:4326',

64.         center: [0,0],

65.         zoom:1

66.       })

67.     });

68.    </script>

69.  </body>

70.</html>

  1. Save your changes to map.html and open the page in your browser: http://localhost:8000/ol_workshop/map.html. To see feature selection in action, use the mouse-click to select an earthquake:

Using aninteraction to select features from a vector layer.

3.3. Drawing Features

New features can be drawn by using an ol.interaction.Draw. A draw interaction is constructed with avector source and a geometry type.

3.3.1. Createa Vector Layer and a Draw Interaction

Tasks

  1. Let’s start with the example below. Open map.html in your text editor and make sure it looks something like the following:

2.  <!doctype html>

3.  <htmllang="en">

4.    <head>

5.      <linkrel="stylesheet"href="ol3/ol.css"type="text/css">

6.      <style>

7.      #map {

8.        height:256px;

9.        width:512px;

10.    }

11.    </style>

12.    <scriptsrc="ol3/ol.js"type="text/javascript"></script>

13.    <title>OpenLayers 3 example</title>

14.  </head>

15.  <body>

16.    <h1>My Map</h1>

17.    <divid="map"></div>

18.    <scripttype="text/javascript">

19.     var source=new ol.source.GeoJSON({

20.       url:'data/layers/7day-M2.5.json'

21.     });

22.     var draw=new ol.interaction.Draw({

23.       source: source,

24.       type:'Point'

25.     });

26.     var map=new ol.Map({

27.       interactions: ol.interaction.defaults().extend([draw]),

28.       target:'map',

29.       layers: [

30.         new ol.layer.Tile({

31.           title:"Global Imagery",

32.           source:new ol.source.TileWMS({

33.              url:'http://maps.opengeo.org/geowebcache/service/wms',

34.              params: {LAYERS:'bluemarble', VERSION:'1.1.1'}

35.           })

36.         }),

37.         new ol.layer.Vector({

38.           title:'Earthquakes',

39.           source: source,

40.           style:new ol.style.Style({

41.              image:new ol.style.Circle({

42.                radius:5,

43.                fill:new ol.style.Fill({

44.                  color:'#0000FF'

45.                }),

46.                stroke:new ol.style.Stroke({

47.                  color:'#000000'

48.                })

49.              })

50.           })

51.         })

52.       ],

53.       view:new ol.View({

54.         projection:'EPSG:4326',

55.         center: [0,0],

56.         zoom:1

57.       })

58.     });

59.    </script>

60.  </body>

61.</html>

  1. Save your changes to map.html and open the page in your browser: http://localhost:8000/ol_workshop/map.html. To see drawing of point geometries in action, click in the map to add a new feature:

Using a drawinteraction to add features to a vector source.

Bonus Tasks

  1. Create a listener which gets the new feature’s X and Y after it is drawn.

3.4.Modifying Features

Modifying features works by using an ol.interaction.Select in combination with an ol.interaction.Modify. They share acommon collection (ol.Collection) of features.Features selected with the ol.interaction.Select become candidates for modifications with theol.interaction.Modify.

3.4.1. Create a Vector Layer and aModify Interaction

Tasks

1.   Let’s start with the working example. Open map.html in your text editor and make sure it looks something like thefollowing:

2.  <!doctype html>
3.  <htmllang="en">
4.    <head>
5.      <linkrel="stylesheet"href="ol3/ol.css"type="text/css">
6.      <style>
7.      #map {
8.        height:256px;
9.        width:512px;
10.    }
11.    </style>
12.    <script src="ol3/ol.js"type="text/javascript"></script>
13.    <title>OpenLayers 3 example</title>
14.  </head>
15.  <body>
16.    <h1>My Map</h1>
17.    <divid="map"></div>
18.    <script type="text/javascript">
19.      var source =new ol.source.GeoJSON({
20.        url:'data/layers/7day-M2.5.json'
21.      });
22.      var style =new ol.style.Style({
23.        image:new ol.style.Circle({
24.          radius:7,
25.            fill:new ol.style.Fill({
26.            color: [0,153,255,1]
27.          }),
28.          stroke:new ol.style.Stroke({
29.            color: [255,255,255,0.75],
30.            width:1.5
31.          })
32.        }),
33.        zIndex:100000
34.      });
35.      var select =new ol.interaction.Select({style: style});
36.      var modify =new ol.interaction.Modify({
37.        features: select.getFeatures()
38.      });
39.      var map =new ol.Map({
40.        interactions: ol.interaction.defaults().extend([select, modify]),
41.        target:'map',
42.        layers: [
43.          new ol.layer.Tile({
44.            title:"Global Imagery",
45.            source:new ol.source.TileWMS({
46.              url:'http://maps.opengeo.org/geowebcache/service/wms',
47.              params: {LAYERS:'bluemarble', VERSION:'1.1.1'}
48.            })
49.          }),
50.          new ol.layer.Vector({
51.            title:'Earthquakes',
52.            source: source,
53.            style:new ol.style.Style({
54.              image:new ol.style.Circle({
55.                radius:5,
56.                fill:new ol.style.Fill({
57.                  color:'#0000FF'
58.                }),
59.                stroke:new ol.style.Stroke({
60.                  color:'#000000'
61.                })
62.              })
63.            })
64.          })
65.        ],
66.        view:new ol.View({
67.          projection:'EPSG:4326',
68.          center: [0,0],
69.          zoom:1
70.        })
71.      });
72.    </script>
73.  </body>
74.</html>

75. Save yourchanges to map.html and open the page in your browser: http://localhost:8000/ol_workshop/map.html.To see feature modification in action, use the mouse-click to select an earthquake and then drag to move the point.

3.4.2. A Closer Look

Let’s examine how modifying features works.

var style =new ol.style.Style({
  image:new ol.style.Circle({
    radius:7,
      fill:new ol.style.Fill({
      color: [0,153,255,1]
    }),
    stroke:new ol.style.Stroke({
      color: [255,255,255,0.75],
      width:1.5
    })
  }),
  zIndex:100000
});
var select =new ol.interaction.Select({style: style});
var modify =new ol.interaction.Modify({
  features: select.getFeatures()
});

We create 2 interactions, an ol.interaction.Select to select the features before modifying them, and an ol.interaction.Modify to actually modify the geometries. They share the same ol.Collection of features. Features selected using ol.interaction.Modify become candidates for modification with the ol.interaction.Modify. Aspreviously, the ol.interaction.Select is configured with a style object, which effectively defines thestyle used for drawing selected features. When the user clicks in the mapagain, the feature will be drawn using the layer’s style.

4.1.Working with Vector Layers

The base ol.layer.Vector constructor provides a fairly flexible layer type. By default,when you create a new vector layer, no assumptions are made about where thefeatures for the layer will come from, since this is the domain of ol.source.Vector. Customizingthe rendering style is addressed in an upcoming section. This section introducesthe basics of vector data formats.

4.1.1. ol.format

The ol.format classes in OpenLayers 3 are responsible for parsing data from theserver representing vector features. Most of the times you won’t be using themdirectly, but you’ll be using their corresponding source (e.g. ol.source.KML). The formatturns raw feature data into ol.Feature objects.

Consider the two blocks of data below. Both represent the same ol.Feature object (a point in Barcelona, Spain). The first is serialized as GeoJSON (usingthe ol.format.GeoJSON parser). The second is serialized as KML (using the ol.format.KML parser).

4.1.1.1. GeoJSONExample

{
    "type":"Feature",
    "id":"OpenLayers.Feature.Vector_107",
    "properties": {},
    "geometry": {
        "type":"Point",
        "coordinates": [-104.98,39.76]
    }
}

4.1.1.2. KMLExample

<?xml version="1.0" encoding="utf-8"?>
<kmlxmlns="http://earth.google.com/kml/2.2">
  <Placemark>
    <Point>
      <coordinates>-104.98,39.76</coordinates>
    </Point>
  </Placemark>
</kml>

4.2.Understanding Style

When styling HTML elements, you might use CSS like the following:

.someClass {
    background-color: blue;
    border-width: 1px;
    border-color: olive;
}

The .someClass text is a selector (in this case it selects all elements thatinclude the class name "someClass") and the blockthat follows is a group of named properties and values, otherwise known asstyle declarations.

4.2.1. Layer style

A vector layer can have styles. More specifically, a vector layercan be configured with an ol.style.Style object, an array ofol.style.Style objects, or a function that takes an ol.Feature instance and a resolution and returns an array of ol.style.Style objects.

Here’s an example of a vector layer configured with a staticstyle:

var layer =new ol.layer.Vector({
  source:new ol.source.Vector(),
  style:new ol.style.Style({
    // ...
  })
});

And here’s an example of a vector layer configured with a stylefunction that applies a style to all features that have an attribute named class with a value of 'someClass':

var layer =new ol.layer.Vector({
  source:new ol.source.Vector(),
  style:function(feature, resolution) {
    if (feature.get('class')==='someClass') {
      // create styles...
      return styles;
    }
  },
});

4.2.2. Symbolizers

The equivalent of a declaration block in CSS is a symbolizer in OpenLayers 3 (these are typicallyinstances of ol.style.*). To paint polygon features with a blue background anda 1 pixel wide olive stroke, you would use two symbolizers like the following:

new ol.style.Style({
  fill:new ol.style.Fill({
    color:'blue'
  }),
  stroke:new ol.style.Stroke({
    color:'olive',
    width:1
  })
});

Depending on the geometry type, different symbolizers can beapplied. Lines work like polygons, but they cannot have a fill. Points can bestyled with ol.style.Circle or ol.style.Icon. The former isused to render circle shapes, and the latter uses graphics from file (e.g. pngimages). Here is an example for a style with a circle:

new ol.style.Circle({
  radius:20,
  fill:new ol.style.Fill({
    color:'#ff9900',
    opacity:0.6
  }),
  stroke:new ol.style.Stroke({
    color:'#ffcc00',
    opacity:0.4
  })
});

4.2.3. ol.style.Style

An ol.style.Style object has 4 keys: fill, image, stroke and text. It also hasan optional zIndex property. The style function will return an array of ol.style.Style objects.

If you want all features to be colored red except for those thathave a class attribute with the value of "someClass" (and you want those features colored blue with an 1px wide olivestroke), you would create a style function that looked like the following (bythe way, it is important to create objects outside of the style function sothey can be reused, but for simplicity reasons the objects are created inlinein the example below):

style: (function() {
  var someStyle = [new ol.style.Style({
    fill:new ol.style.Fill({
      color:'blue'
    }),
    stroke:new ol.style.Stroke({
      color:'olive',
      width:1
    })
  })];
  var otherStyle = [new ol.style.Style({
    fill:new ol.style.Fill({
      color:'red'
    })
  })];
  returnfunction(feature, resolution) {
    if (feature.get('class')==="someClass") {
      return someStyle;
    } else {
      return otherStyle;
    }
  };
}())

Note

 

It is important to create the style arraysoutside of the actual function. This can be done with a JavaScript closure asdone in the example above.

Note

 

A feature also has a style config option thatcan take a function having only resolution as argument. This makes it possibleto style individual features (based on resolution).

4.2.4. Pseudo-classes

CSS allows for pseudo-classes on selectors. These basically limitthe application of style declarations based on contexts that are not easilyrepresented in the selector, such as mouse position, neighboring elements, orbrowser history. In OpenLayers 3, a somewhat similar concept is having a styleconfig option on an ol.interaction.Select.

An example is:

var select =new ol.interaction.Select({
  style:new ol.style.Style({
    fill:new ol.style.Fill({
      color:'rgba(255,255,255,0.5)'
    })
  })
});

With the basics of styling under your belt, it’s time to move onto styling vector layers.

4.3. Styling Vector Layers

  1. We’ll start with a working example that displays building footprints in a vector layer. Open your text editor and save the following as map.html in the root of your workshop directory:

2.  <!doctype html>

3.  <htmllang="en">

4.    <head>

5.      <linkrel="stylesheet"href="ol3/ol.css"type="text/css">

6.      <style>

7.      #map {

8.        background-color:gray;

9.        height:256px;

10.     width:512px;

11.    }

12.    </style>

13.    <title>OpenLayers 3 example</title>

14.    <scriptsrc="ol3/ol.js"type="text/javascript"></script>

15.  </head>

16.  <body>

17.    <h1>My Map</h1>

18.    <divid="map"></div>

19.    <scripttype="text/javascript">

20.     var map=new ol.Map({

21.       target:'map',

22.        layers: [

23.         new ol.layer.Vector({

24.           title:'Buildings',

25.           source:new ol.source.KML({

26.              url:'data/layers/buildings.kml',

27.              extractStyles:false

28.           }),

29.           style:new ol.style.Style({

30.              stroke:new ol.style.Stroke({color:'red', width:2})

31.           })

32.         })

33.       ],

34.       view:new ol.View({

35.         projection:'EPSG:4326',

36.         center: [-122.791859392,42.3099154789],

37.         zoom:16

38.       })

39.      });

40.    </script>

41.  </body>

42.</html>

  1. Open this map.html file in your browser to see buildings with a red outline: http://localhost:8000/ol_workshop/map.html
  2. With a basic understanding of styling in OpenLayers, we can create a style function that displays buildings in different colors based on the size of their footprint. In your map initialization code, replace the style config option for theBuildings layer with the following:

45.style: (function() {

46.  var defaultStyle= [new ol.style.Style({

47.    fill:new ol.style.Fill({color:'navy'}),

48.    stroke:new ol.style.Stroke({color:'black', width:1})

49.  })];

50.  var ruleStyle= [new ol.style.Style({

51.    fill:new ol.style.Fill({color:'olive'}),

52.    stroke:new ol.style.Stroke({color:'black', width:1})

53.  })];

54.  returnfunction(feature, resolution) {

55.    if (feature.get('shape_area')<3000) {

56.     return ruleStyle;

57.    }else {

58.     return defaultStyle;

59.    }

60.  };

61.})()

  1. Save your changes and open map.html in your browser: http://localhost:8000/ol_workshop/map.html

Buildings coloredby footprint area.

  1. Now as a final step, let’s add a label to the buildings. For simplicity we’re only using a label and a black outline as the style.

64.style: (function() {

65.  var stroke=new ol.style.Stroke({

66.    color:'black'

67.  });

68.  var textStroke=new ol.style.Stroke({

69.    color:'#fff',

70.    width:3

71.  });

72.  var textFill=new ol.style.Fill({

73.    color:'#000'

74.  });

75.  returnfunction(feature, resolution) {

76.    return [new ol.style.Style({

77.     stroke: stroke,

78.     text:new ol.style.Text({

79.       font:'12px Calibri,sans-serif',

80.       text: feature.get('key'),

81.       fill: textFill,

82.       stroke: textStroke

83.     })

84.    })];

85.  };

86.})()

  1. Save your changes and open map.html in your browser: http://localhost:8000/ol_workshop/map.html

Buildings labeledby the key field.

 

0 0
原创粉丝点击