Skip to content

Instantly share code, notes, and snippets.

@stevage stevage/README.md
Created Jun 26, 2018

Embed
What would you like to do?
Round labels demo

This is a somewhat hacky way of producing rounded labels in Mapbox-GL-JS. They are drawn as Markers, using queryRenderedFeatures to synchronise with the source data.

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Display a map</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.46.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.46.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
.rounded-label {
background: white;
padding: 0.25em 0.5em;
font-size: 16pt;
border-radius: 1em;
border:1px solid lightgrey;
}
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
function loadMarkers() {
// places = map.querySourceFeatures('composite', { sourceLayer: 'place_label', filter: ['<=', 'localrank', 3]});
places = map.queryRenderedFeatures({ layers: labelLayers});
console.log(places[0]);
var newies = 0;
places.forEach(place => {
if (!markers[place.id]) {
var el = document.createElement('div');
el.innerHTML = place.properties.name;
el.className = 'rounded-label';
markers[place.id] = new mapboxgl.Marker(el)
.setLngLat(place.geometry.coordinates)
.addTo(map);
newies ++;
}
});
// newies &&
console.log(newies, ' markers added.');
}
mapboxgl.accessToken = 'pk.eyJ1Ijoic3RldmFnZSIsImEiOiJGcW03aExzIn0.QUkUmTGIO3gGt83HiRIjQw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-74.50, 40],
zoom: 9
});
var places;
var markers = {};
var labelLayers = ['place-city-lg-n', 'place-city-lg-s', 'place-city-md-n', 'place-city-md-s', 'place-city-sm'];
// map.on('load', () => labelLayers.forEach(l => map.setPaintProperty(l, 'text-opacity', 0.1)));
map.on('sourcedata', loadMarkers);
// there seems to be an unmanageable race condition here.
map.once('render', () => window.setTimeout(loadMarkers, 2000));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.