GeoJSONで属性を表示するメモ。
script.js
// MapTiler読み込み
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/jp-mierune-streets/style.json?key=[APIキー]',
center: [139.767, 35.681],
zoom: 11,
});
map.on('load', function () {
// サークル設定
map.addSource('point_sample', {
type: 'geojson',
data: './vector/sample.geojson'
});
// スタイル設定
map.addLayer({
'id': 'point_sample',
'type': 'circle',
'source': 'point_sample',
'layout': {},
'paint': {
'circle-color': '#FF0000',
'circle-radius': 10
}
});
// ポイントクリックイベント
map.on('click', 'point_sample', function (e) {
const coordinates = e.lngLat;
// 属性設定
const description =
'field01: ' + e.features[0].properties.field01 + '<br>' +
'field02: ' + e.features[0].properties.field02 + '<br>' +
'field03: ' + e.features[0].properties.field03 ;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new maplibregl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
// カーソルON,OFF
map.on('mouseenter', 'point_sample', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'point_sample', function () {
map.getCanvas().style.cursor = '';
});
});
// コントロール関係表示
map.addControl(new maplibregl.NavigationControl());
sample.geojson
{
"type": "FeatureCollection",
"name": "sample",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "field01": "一", "field02": "abcd", "field03": 5 }, "geometry": { "type": "Point", "coordinates": [ 139.766778945922852, 35.68198003744061 ] } },
{ "type": "Feature", "properties": { "field01": "二", "field02": null, "field03": 7 }, "geometry": { "type": "Point", "coordinates": [ 139.762916564941406, 35.674310750817348 ] } },
{ "type": "Feature", "properties": { "field01": "三", "field02": "kojsha", "field03": 9 }, "geometry": { "type": "Point", "coordinates": [ 139.763603210449219, 35.691391336319306 ] } }
]
}
MapLibre GL JSを手軽に始めるビルド環境公開しています。
maplibregljs-starter
- 参考文献
MapLibre GL JS