Skip to content

Instantly share code, notes, and snippets.

@dianashk
Last active December 4, 2018 20:55
Show Gist options
  • Save dianashk/420a7116fbfff3e0dc3263283e06a780 to your computer and use it in GitHub Desktop.
Save dianashk/420a7116fbfff3e0dc3263283e06a780 to your computer and use it in GitHub Desktop.
example of a mapbox map with custom vector tile data source
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.css' rel='stylesheet' />
</head>
<body>
<div class="row">
<div id='map' style="height: 500px; width:800px"></div>
<script>
mapboxgl.accessToken = '<insert_mapbox_key>';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/streetcredlabs/cjkkcj0k816qn2rmoscle2bef',
center: [-74.0060, 40.7128],
zoom: 15 // starting zoom
});
map.on('load', () => {
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/9/98/Dot10.png', function(error, image) {
if (error) throw error;
map.addImage('place', image);
map.addLayer({
"id": "places",
"type": "symbol",
"source": {
"type": "vector",
"tiles": ["http://localhost:8000/tiles/{z}/{x}/{y}.mvt"],
"minzoom": 6,
"maxzoom": 20
},
"source-layer": "places",
layout: {
'icon-image': 'place',
'icon-size': 1,
'icon-allow-overlap': true
}
});
});
// When a click event occurs on a feature in the places layer, open a popup at the
// location of the feature, with description HTML from its properties.
map.on('click', 'places', function (e) {
console.log(e.features);
const coordinates = e.features[0].geometry.coordinates.slice();
const description =
`<p><a target="_blank" href="/admin/places/${e.features[0].properties.id}">
<b>${e.features[0].properties.name}</b>
</a></p>
<p>${JSON.parse(e.features[0].properties.address).label}</p>
<p><i>${e.features[0].properties.categories}</i></p>
<p><i>${e.features[0].properties.id}</i></p>
<p>location: ${e.features[0].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;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'places', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'places', function () {
map.getCanvas().style.cursor = '';
});
});
</script>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment