2023年2月13日月曜日

OpenLayersを使って図形を書く

 折角なので以前の記事に続き、OpenLayersの部分も試してみました。

Drawing objects on maps in Oracle APEX - MapLibre vs OpenLayers
https://pretius.com/blog/maplibre-vs-openlayers/


空のアプリケーションを作成したところから始めます。

静的コンテンツのリージョンを作成します。識別タイトルMapとします。

ソースのHTMLコードは以下です。

<div id="map"></div>


ページ・プロパティJavaScriptCSSを設定します。

JavaScriptファイルURLは以下になります。OpenLayersのサイトより、最新のバージョンを確認しましょう。

https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js

ファンクションおよびグローバル変数の宣言に以下を記述します。

/*
* This code is based on the article wrtten by Lech Cieślik, Pretius.
* Drawing objects on maps in Oracle APEX - MapLibre vs OpenLayers
* https://pretius.com/blog/maplibre-vs-openlayers/
*/
//Create Raster Source
const sourceRaster = new ol.source.OSM();
//Create new layer - Open Street Maps
const raster = new ol.layer.Tile({
source: sourceRaster
});
//Create Vector Source
const source = new ol.source.Vector({wrapX: false});
//Create new layer - Vector Source
const vector = new ol.layer.Vector ({
source: source,
});
/*
* マップに書き込まれた図形のジオメトリを取得する。
*/
const GET_FEATURES = {
name: "get-features",
action: (event, element, args) => {
let geojson = new ol.format.GeoJSON().writeFeatures(vector.getSource().getFeatures(), {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
apex.items.P1_COORDINATE.setValue(geojson);
}
};
/*
* ページの準備ができてから実行する。
*/
apex.jQuery(window).on('theme42ready', () => {
// apex.actionsにアクションを登録する。
apex.actions.add([GET_FEATURES]);
//Create map
const map = new ol.Map({
//set layer(s)
layers: [raster, vector],
//set container
target: "map",
//set view
view: new ol.View({
center: ol.proj.fromLonLat([12.48, 41.85]),
zoom: 8
})
});
//Add Interaction (Draw object functionality)
var draw = new ol.interaction.Draw({
source: source,
type: "Polygon", //you can use 'Point' or 'LineString'
});
map.addInteraction(draw);
});

CSSファイルURLに以下を記述します。

https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css

CSSインラインに以下を記述します。

#map {height: 500px; width: 100%;}


マップに記述した図形のジオメトリを取得するボタンを作成します。

ボタン名GET_FEATURESラベルGet Features動作アクションとして動的アクションで定義を選択し、詳細カスタム属性として以下を記述します。

data-action="#action$get-features"


ジオメトリを保持するページ・アイテムを作成します。

識別名前P1_COORDINATEタイプとしてテキスト領域を選択します。


以上で完成です。アプリケーションを実行すると、記事の先頭のGIF動画のように動作します。

今回作成したAPEXアプリケーションのエクスポートを以下に置きました。
https://github.com/ujnak/apexapps/blob/master/exports/openlayers-sample.zip

Oracle APEXのアプリケーション作成の参考になれば幸いです。