MapBox Map Starter Template
Creating a web map item and was using MapBox and decided to create a basic template for working with MapBox+JavaScript+HTML and came up with this
<!DOCTYPE html>
<html>
<head>
<title>Map Test</title>
<style>
.mapboxgl-popup {
max-width: 200px;
}
.mapboxgl-popup-content {
text-align: center;
font-family: monospace, sans-serif;
}
.map {
width: -webkit-fill-available;
}
</style>
<link href="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.js"></script>
</head>
<body>
<div class="map" id="map">
</div>
<script>
let map = null;
let mapMarkers = [];
function setupMap() {
mapboxgl.accessToken = "<YOUR TOKEN>";
map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v12",
center: [0, 0],
zoom: 0,
});
}
function getRandomColor() {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function updateMap(listings) {
if (listings.length == 0) {
return;
}
property = listings.shift();
mapMarkers.forEach(z => z.remove());
mapMarkers = [];
const position = [
property.location.longitude,
property.location.latitude
];
const title = property.name;
const addressData = Object.entries(property.address).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {});
const addressLine = Object.keys(addressData).reduce((acc, key) => acc + `${addressData[key]} ` ,'');
const descriptionText = property.description || "";
const description = descriptionText.length <= 50 ? descriptionText : descriptionText.slice(0, 50);
const newMarker = new mapboxgl.Marker({ color: getRandomColor() })
.setLngLat(position)
.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML(`<h3>${title}</h3><p>${addressLine}<br/>${description}</p>`)).addTo(map);
mapMarkers.push(newMarker);
map.flyTo({ center: position, zoom: 18 });
}
window.onload = (event) => {
setupMap();
};
</script>
</body>
</html>