OpenLayersのFeature classについて[Chapter 43]

====== OpenLayersを使ってみる。[Chapter 43] ======

[[http://blog.godo-tys.jp/2013/08/12/3696/|OpenLayersのGeometry subclassについて[Chapter 42] ]]に引き続き、OpenLayersのFeature classについて基本を学んでいきます。

この章以降は、
* どのようにvector layerを描いているか?
* Vector Classとは?
* GeometryとFeature classについて -> **今回もここ**
* Strategy,Protocol,Format classの使い方
について順番に学んでいきます。

[[http://www.packtpub.com/openlayers-2-1-javascript-web-mapping-library-beginners-guide/book|OpenLayers 2.10 Beginner’s Guide]]なる書籍の章立てにあわせて、OpenLayersの使い方を学んでいきます。

===== Feature class =====
**Feature class**は、実際に地図上のgeometry objectを表示ために、vector classが使用するものです。
Vector Layer classにはfeatureと呼ばれる特性があります。それはFeture Objectの配列です。
**Feature class**の基本は、Geometry objectsとattributes(属性)の2つから成り立っています。
Attributesは、featureに関連したデータを含んでいます。

==== Feature subclasses ====
Feature subclassesはただ一つのFeature.Vactor classを持っています。その親 Feature classスのように、それはGeometry objectからできていて、attributes(属性)を含んでいます。
さらに、featureがどのように見えるかcontrolするstyle propertyがあります。
Style classについては、Chapter 10で詳しく学びます。

==== Feature functions ====
Featureのfunctionについていくつかをみてみます。それほど難しい英語ではないので、原文のまま載せます。

==== destroy() ====
**destroy()**: Destroys the feature object.

==== clone() ====
**clone()**: Creates a copy of the feature object and returns it, as an {OpenLayers.Feature.Vector} object.

==== getVisibility() ====
**getVisibility()**: Returns a {Boolean} which specifies whether the feature is displayed or not.

==== move(location) ====
**move(location)**: Moves the feature to a passed in location. The location can be either an {OpenLayers.LonLat} object, which will move the feature to a passed in map coordinate, or an {OpenLayers.Pixel} object which will move it to a pixel location on the screen.

==== onScreen(boundsOnly) ====
**onScreen(boundsOnly)**: Returns a {Boolean} indicating if the feature is within the map viewport (if it is visible on the screen). A boundsOnly parameter can be passed in, which is a {Boolean} set to false by default. If set to true, a quicker but less precise bounding box intersection method will be used.

===== feature objectをインスタンスする。 =====
Feature objectを作る場合、
**var my_feature = new OpenLayers.Feature.Vector( geometry_object, attributes, style);**
のように作成します。
ここで、**geometry_object**はgeometry objectです。Attributes objectは、feature’s
attributes propertyで地図を作るoptional object literalです。
たとえば、featureは{‘building_area’: 18000, ‘building_floors’: 2}のようなattributes propertyです。

===== Control.SelectFeatureを使用して、featureと対話する。 =====
Featureをclickしてに何かを起こらせるために、SelectFeature control class(OpenLayers.Control.SelectFeatureクラス)を使用する必要があります。このcontrolは、featureと対話することを可能にします、
SelectFeature control classを使ったexample codeを見ましょう。

==== SelectFeature control example code ====

SelectFeature controlを使った簡単なexample codeを作成してみましょう。以下のcodeを入力します。
保存先は、c:¥ms4w¥apache¥htdocs¥openlayer¥chapter9¥にしておきます。
ファイル名は、chapter9_ex5_selectFeature.htmlで保存します。

 
<!DOCTYPE html>
<html lang='ja'>
	<head>
		<meta charset='utf-8' />
		<script type='text/javascript' src='http://localhost/openlayers/OpenLayers.js'></script>
		<script type='text/javascript'>
			var map, vector_layer;

			function init() {
				//Create a map with an empty array of controls
				map = new OpenLayers.Map('map_element');

				//Create a base layer
				var wms_layer = new OpenLayers.Layer.WMS(
					'OpenLayers WMS', 
					'http://vmap0.tiles.osgeo.org/wms/vmap0', {
					layers : 'basic'
				}, {});
				map.addLayer(wms_layer);

				//Create and add vector layer
				vector_layer = new OpenLayers.Layer.Vector('Basic Vector Layer');
				map.addLayer(vector_layer);

				//Create and add a couple features
				var feature_point_1 = new OpenLayers.Feature.Vector(
					new OpenLayers.Geometry.Point(6.055, 46.234), {
					'location' : 'Cern',
					'description' : "Stand back, I'm going to try science!"
				});
				var feature_point_2 = new OpenLayers.Feature.Vector(
					new OpenLayers.Geometry.Point(-129, 3), {
					'location' : 'The Sea',
					'description' : 'Here be dragons'
				});
				var feature_polygon = new OpenLayers.Feature.Vector(
				//We'll make a polgon from a linear ring object, which consists of points
				new OpenLayers.Geometry.Polygon(
					new OpenLayers.Geometry.LinearRing([
						new OpenLayers.Geometry.Point(-124.2, 41.9), 
						new OpenLayers.Geometry.Point(-120.1, 41.9), 
						new OpenLayers.Geometry.Point(-120, 39), 
						new OpenLayers.Geometry.Point(-114.5, 34.9), 
						new OpenLayers.Geometry.Point(-114.7, 32.7), 
						new OpenLayers.Geometry.Point(-117.1, 32.5), 
						new OpenLayers.Geometry.Point(-120, 34), 
						new OpenLayers.Geometry.Point(-123.7, 38.4)
				//We won't pass in the first point, the polygon will close automatically
				])), {
					'location' : 'Fanghorn Forest',
					'description' : 'Land of the Ents'
				});
				vector_layer.addFeatures([feature_point_1, feature_point_2, feature_polygon]);

				//Create and add selectFeature control
				var select_feature_control = new OpenLayers.Control.SelectFeature(
					vector_layer, {
					multiple : false,
					toggle : true,
					toggleKey : 'ctrlKey',
					multipleKey : 'shiftKey'
				});
				map.addControl(select_feature_control);

				//Activate the control
				select_feature_control.activate();

				//Finally, let's add some events so we can do stuff when the user
				//	interacts with the features
				function selected_feature(event) {
					//clear out the log's contents
					document.getElementById('map_feature_log').innerHTML = '';

					//Show the current selected feature (passed in from the event object)
					var display_text = 'Clicked on: ' + '<strong>' + 
						event.feature.attributes.location + '</strong>' + ': ' + 
						event.feature.attributes.description + '<hr />';
					document.getElementById('map_feature_log').innerHTML = display_text;

					//Show all the selected features
					document.getElementById('map_feature_log').innerHTML += 'All selected features: ';

					//Now, loop through the selected feature array
					for (var i = 0; i < vector_layer.selectedFeatures.length; i++) {
						document.getElementById('map_feature_log').innerHTML += vector_layer.selectedFeatures[i].attributes.location + ' | ';
					}
				}

				function unselected_feature(event) {
					var display_text = event.feature.attributes.location + ' unselected!' + '<hr />';
					document.getElementById('map_feature_log').innerHTML = display_text;

					//Show all the selected features
					document.getElementById('map_feature_log').innerHTML += 'All selected features: ';

					//Now, loop through the selected feature array
					for (var i = 0; i < vector_layer.selectedFeatures.length; i++) {
						document.getElementById('map_feature_log').innerHTML += vector_layer.selectedFeatures[i].attributes.location + ' | ';
					}
				}

				//Register the event
				vector_layer.events.register('featureselected', this, selected_feature);
				vector_layer.events.register('featureunselected', this, unselected_feature);

				if (!map.getCenter()) {
					map.zoomToMaxExtent();
				}

			}

		</script>
	</head>

	<body onload='init();'>
		<div id='map_element' style='width: 600px; height: 600px;'></div>
		<div id='map_feature_log'></div>
	</body>
</html>

codeでまずは、map objectを作成して、

//Create a map with an empty array of controls
map = new OpenLayers.Map('map_element');

//Create a base layer
var wms_layer = new OpenLayers.Layer.WMS(
'OpenLayers WMS',
'http://vmap0.tiles.osgeo.org/wms/vmap0', {
layers : 'basic'
}, {});
map.addLayer(wms_layer);

//Create and add vector layer
vector_layer = new OpenLayers.Layer.Vector('Basic Vector Layer');
map.addLayer(vector_layer);

のようにwms_layerとvector_layerを定義します。

次に、feature objectを3つ追加します。

//Create and add a couple features
var feature_point_1 = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(6.055, 46.234), {
'location' : 'Cern',
'description' : "Stand back, I'm going to try science!"
});
var feature_point_2 = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-129, 3), {
'location' : 'The Sea',
'description' : 'Here be dragons'
});
var feature_polygon = new OpenLayers.Feature.Vector(
//We'll make a polgon from a linear ring object, which consists of points
new OpenLayers.Geometry.Polygon(
new OpenLayers.Geometry.LinearRing([
new OpenLayers.Geometry.Point(-124.2, 41.9),
new OpenLayers.Geometry.Point(-120.1, 41.9),
new OpenLayers.Geometry.Point(-120, 39),
new OpenLayers.Geometry.Point(-114.5, 34.9),
new OpenLayers.Geometry.Point(-114.7, 32.7),
new OpenLayers.Geometry.Point(-117.1, 32.5),
new OpenLayers.Geometry.Point(-120, 34),
new OpenLayers.Geometry.Point(-123.7, 38.4)
//We won't pass in the first point, the polygon will close automatically
])), {
'location' : 'Fanghorn Forest',
'description' : 'Land of the Ents'
});
vector_layer.addFeatures([feature_point_1, feature_point_2, feature_polygon]);

OpenLayers.Feature.Vectorでfeatureを作って、Geometry.Pointでpointを作成します。
Attributeとして、locationとdescriptionを追加します。最後にvector_layer.addFeaturesで作成したfeatureを追加します。

そして、Control.SelectFeatureでcontrolを

//Create and add selectFeature control
var select_feature_control = new OpenLayers.Control.SelectFeature(
vector_layer, {
multiple : false,
toggle : true,
toggleKey : 'ctrlKey',
multipleKey : 'shiftKey'
});
map.addControl(select_feature_control);

//Activate the control
select_feature_control.activate();

のように追加して、controlをactiveにします。

最後に、featureを選択した場合と選択を解除する場合のfunctionを作成します。

function selected_feature(event) {
//clear out the log's contents
document.getElementById('map_feature_log').innerHTML = '';

//Show the current selected feature (passed in from the event object)
var display_text = 'Clicked on: ' + '' +
event.feature.attributes.location + '
' + ': ' +
event.feature.attributes.description + '


';
document.getElementById('map_feature_log').innerHTML = display_text;

//Show all the selected features
document.getElementById('map_feature_log').innerHTML += 'All selected features: ';

//Now, loop through the selected feature array
for (var i = 0; i < vector_layer.selectedFeatures.length; i++) { document.getElementById('map_feature_log').innerHTML +=vector_layer.selectedFeatures[i].attributes.location + ' | '; } } function unselected_feature(event) { var display_text = event.feature.attributes.location + ' unselected!' + '


';
document.getElementById('map_feature_log').innerHTML = display_text;

//Show all the selected features
document.getElementById('map_feature_log').innerHTML += 'All selected features: ';

//Now, loop through the selected feature array
for (var i = 0; i < vector_layer.selectedFeatures.length; i++) { document.getElementById('map_feature_log').innerHTML +=vector_layer.selectedFeatures[i].attributes.location + ' | '; } } //Register the event vector_layer.events.register('featureselected', this, selected_feature); vector_layer.events.register('featureunselected', this, unselected_feature);

functionを定義して、eventを登録します。
Attributeについては、map_feature_logの

に表示されるようにします。

保存後、FireFoxを立ち上げて、http://localhost/openlayers/chapter9/chapter9_ex5_selectFeature.htmlと入力すると、
{{http://blog.godo-tys.jp/wp-content/gallery/openlayers_43/image01.jpg}}

ようにvactor layerが追加されて、3つのfeatureがmapに表示されます。

そして、featureをmouse clickで選択すると、
{{http://blog.godo-tys.jp/wp-content/gallery/openlayers_43/image02.jpg}}

で選択状態となり、map下部に選択されたfeatureのattributeが表示されます。

また、shift keyを押しながらfeatureをmouse clickで選択すると、
{{http://blog.godo-tys.jp/wp-content/gallery/openlayers_43/image03.jpg}}

のように複数のfeatureが選択できて、map下部に選択されたfeatureのattributeが表示されます。

===== 今回のまとめ =====

OpenLayersの簡単なGeometryとFeatureについて学びました。(ちょい手抜きの部分もありますが。。。)
次回は、Control.SelectFeature classについてSelectFeatureの基本を学んでいきます。

また、本tutorialは、htmlやCSSやJavaScriptの基本的なことはある程度理解している前提で今後も話を進めていきます。また、誤字、脱字、spell間違いや勘違いも多々出てくると考えられます。
それは違うじゃん!!とかいろんな意見をいただければと思います。
そこんところ ヨロシク~~!!

**[[http://blog.godo-tys.jp/openlayer-tutorial/|OpenLayers Tutorialの目次に戻る。]]**

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

CAPTCHA