Skip to content

Instantly share code, notes, and snippets.

@malwoodsantoro
Last active March 4, 2022 05:27
Show Gist options
  • Save malwoodsantoro/6696fedafc3e150315dd1d97adc65003 to your computer and use it in GitHub Desktop.
Save malwoodsantoro/6696fedafc3e150315dd1d97adc65003 to your computer and use it in GitHub Desktop.
Add a popup to a drawn polygon
<!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.38.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.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>
#fill-button {
min-height: 20px;
background-color: #ff69b4 ;
color: #fff;
font-family: 'Arial';
font-size: 20px;
border-radius: 5px;
padding: 10px;
cursor: pointer;
margin: 10px 0;
position: absolute;
top: 210px;
left: 10px;
}
</style>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js'></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.0.0/mapbox-gl-draw.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.0.0/mapbox-gl-draw.css' type='text/css'/>
<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', //hosted style id
center: [-91.874, 42.760], // starting position
zoom: 12 // starting zoom
});
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
},
styles: [
//linestring style
{
"id": "gl-draw-line",
"type": "line",
"filter": ["all", ["==", "$type", "LineString"], ["!=", "mode", "static"]],
"layout": {
"line-cap": "round",
"line-join": "round"
},
"paint": {
"line-color": "#0254A2",
"line-dasharray": [0.2, 2],
"line-width": 5
}
},
//polygon stroke style
{
"id": "gl-draw-polygon-stroke-active",
"type": "line",
"filter": ["all", ["==", "$type", "Polygon"], ["!=", "mode", "static"]],
"layout": {
"line-cap": "round",
"line-join": "round"
},
"paint": {
"line-color": "#0254A2",
"line-dasharray": [0.2, 2],
"line-width": 5
}
},
// polygon fill style
{
"id": "gl-draw-polygon-fill",
"type": "fill",
"filter": ["all", ["==", "$type", "Polygon"], ["!=", "mode", "static"]],
"paint": {
"fill-color": "#0254A2",
"fill-outline-color": "#0254A2",
"fill-opacity": 0
}
}
]
});
map.addControl(draw);
// add popup to drawn polygon
map.on('click', 'gl-draw-polygon-fill.cold', function (e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML('<b>Hi popup!</b>')
.addTo(map);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment