地図からではなく、属性データから位置図を作成しようと思い、「OpenLayers」を利用して実装してみました。
処理の概要は以下の通りです。
- 属性のプライマリーキーより、図形データ(GeoJson形式)のデータを取得
- 取得した図形データ(GeoJson形式)から、中心点を取得して、表示領域に設定
各処理とファイルは以下の通りです。
- 図形取得用APIコントローラー…ReportController.cs
- クライアント…map.js
以下、実装例です。必要な個所のみに抜粋しています。
ReportController.cs
前回は、GetFeatures()という全図形を返却するメソッドを作成しましたが、
今回は1件しか表示させないので、引数付きのGetFeature()メソッドを作成しました。
今回も、GeoJson形式で作成するため、空間演算ライブラリのNetTopologySuiteにある、GeoJsonWriterを利用しています。
また、前回は複数件の返却であったため、FeatureCollectionクラスでGeoJsonを作成していましたが、今回は1件なので、FeatureクラスでGeoJsonを作成しています。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class ReportController : ApiController { public HttpResponseMessage GetFeature(string id) { var response = new HttpResponseMessage(); try { var geoJsonWriter = new GeoJsonWriter(); var wktReader = new WKTReader(); var report = this.ReportService.GetReport(id); var wkt = report.Geometry.AsText(); var geometry = wktReader.Read(wkt); var attributes = new AttributesTable(); attributes.AddAttribute("ReportId", report.ReportId.ToString()); attributes.AddAttribute("ReportStatus", report.ReportStatus); var feature = new Feature(geometry, attributes); var jsonString = geoJsonWriter.Write(feature); response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); } catch (Exception ex) { throw ex; } return response; } } |
map.js
図形レイヤから、引数付きの図形取得用APIコントローラーを呼びます。図形取得した後、中心点を取得して、表示領域に設定しています。
表示領域に設定は、以前は、ol.View.centerOn()メソッドを使っていましたが、今回は、ol.View.fit()メソッドを使いました。fit()の方が、引数の設定が分かりやすいため、使い易いです。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
var map = new ol.Map({ target: 'MapPanel', view: new ol.View({ center: [14897735, 4070125], zoom: 15, minZoom: 10, maxZoom: 18 }) }); var layer1 = new ol.layer.Tile({ name: '電子国土基本図(標準地図)', type: 'base', source: new ol.source.XYZ({ attributions: [ new ol.control.Attribution({ html: "<a href="https://maps.gsi.go.jp/development/ichiran.html" target="_blank" rel="noopener">標準地図</a>" }) ], url: "http://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png", projection: "EPSG:3857" }) }); map.addLayer(layer1); var reportId = TextReportId.GetValue(); var vectorSource = new ol.source.Vector( { projection: 'EPSG:3857', format: new ol.format.GeoJSON(), loader: function (extent, resolution, projection) { var json = LoadJson('../../Controllers/Report/GetFeature/' + reportId); var feature = new ol.format.GeoJSON().readFeature(json); this.addFeature(feature); var point = feature.getGeometry(); map.getView().fit(point, { padding: [100, 100, 100, 100] }); }, strategy: ol.loadingstrategy.all }); var layer2 = new ol.layer.Vector({ name: 'Vecteur', source: vectorSource, style: function (feature) { var style = getStyle(feature); return style; } }); map.addLayer(layer2); map.updateSize(); |
以下、表示イメージです。ピンが地図の中心に表示されています。
