Edited at

Mapbox GL JS で矢印マーカー(mapboxgl.Marker 利用)

More than 1 year has passed since last update.

こんにちは。

Mapbox GL JS で mapboxgl.Marker を使い矢印(矢尻形)マーカーを描いてみました。svg で形を定義し、色、サイズ、方向を変化させました。

apboxgl.Marker.jpg


mapboxgl.marker_arrowhead.html

<!DOCTYPE html>

<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.30.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.30.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.marker {
display: block;
border: none;
cursor: pointer;
padding: 0;
}
</style>
<div id='map'></div>
<script>
//mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
container:
'map',
style:
'mapbox://styles/mapbox/light-v9',
center: [-65.017, -16.457],
zoom: 5
});
map.addControl(new mapboxgl.NavigationControl());

var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"marker-rotation": 0,
"marker-color": "red",
"marker-size": 10
},
"geometry": {
"type": "Point",
"coordinates": [
-66.324462890625,
-16.024695711685304
]
}
},
{
"type": "Feature",
"properties": {
"marker-rotation": 45,
"marker-color": "orange",
"marker-size": 14
},
"geometry": {
"type": "Point",
"coordinates": [
-61.2158203125,
-15.97189158092897
]
}
},
{
"type": "Feature",
"properties": {
"marker-rotation": 135,
"marker-color": "green",
"marker-size": 20
},
"geometry": {
"type": "Point",
"coordinates": [
-63.29223632812499,
-18.28151823530889
]
}
}
]
};

geojson.features.forEach(function(marker) {
var markerSize = marker.properties["marker-size"], markerRotation = marker.properties["marker-rotation"], markerFill = marker.properties["marker-color"];
var markerData = "<svg width='" + markerSize + "' height='" + markerSize + "' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg' version='1.1'><polygon fill='" + markerFill + "' stroke='black' stroke-width='1' points='20,90 50,10 80,90 50,70' transform='rotate(" + markerRotation + " 50 50)'/></svg>"; // arrowhead

var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = "url(data:image/svg+xml;base64," + btoa(markerData) + ')';
el.style.width = markerSize + 'px';
el.style.height = markerSize + 'px';

new mapboxgl.Marker(el, {offset: [-markerSize / 2, -markerSize / 2]})
.setLngLat(marker.geometry.coordinates)
.addTo(map);

});
</script>

</body>
</html>