Skip to content

Instantly share code, notes, and snippets.

@malwoodsantoro
Last active March 4, 2022 05:24
Show Gist options
  • Save malwoodsantoro/04d9e7e1d47ac76cfbc6283f38c69716 to your computer and use it in GitHub Desktop.
Save malwoodsantoro/04d9e7e1d47ac76cfbc6283f38c69716 to your computer and use it in GitHub Desktop.
Show popup over center of building
<!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://npmcdn.com/@turf/turf/turf.min.js'></script>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFsLXdvb2QiLCJhIjoiY2oyZ2t2em50MDAyMzJ3cnltMDFhb2NzdiJ9.X-D4Wvo5E5QxeP7K_I3O8w';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location
center: [-80.004, 40.441], // starting position [lng, lat]
zoom: 18 // starting zoom
});
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('click', 'building', function (e) {
var description = e.features[0].properties.height;
var centerPoint = turf.centerOfMass(e.features[0]);
var coordinates = centerPoint.geometry.coordinates;
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
popup.setLngLat(coordinates)
.setHTML('<b>Building height: </b>' + description + ' meters ')
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'building', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'building', function () {
map.getCanvas().style.cursor = '';
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment