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.
Created
June 26, 2018 01:28
-
-
Save stevage/23d881a66e2bcca385d8cc074691b674 to your computer and use it in GitHub Desktop.
Round labels demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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