GeoJSON: Display points as markers
Draw GeoJSON.Points as markers with Mapbox GL
by Geoapify
HTML
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@1.15.2/dist/maplibre-gl.css">
<script src="https://unpkg.com/maplibre-gl@1.15.2/dist/maplibre-gl.js"></script>
<div id="my-map"></div>
CSS
body {
margin: 0;
padding: 0;
}
#my-map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.my-marker {
height: 46px;
width: 31px;
cursor: pointer;
}
JavaScript
// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
var myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";
// Store all added markers to be able remove them later
var markers = [];
var bounds = {
// Paris
lat1: 48.88002146841028,
lon1: 2.3410839716279455,
lat2: 48.86395628860821,
lon2: 2.368348737185606
}
var map = new maplibregl.Map({
center: [(bounds.lon1 + bounds.lon2) / 2, (bounds.lat1 + bounds.lat2) / 2],
zoom: 15,
container: 'my-map',
style: `https://maps.geoapify.com/v1/styles/klokantech-basic/style.json?apiKey=${myAPIKey}`,
});
map.addControl(new maplibregl.NavigationControl());
var type = "cafe"
// getting cafes for the given boundary (number of results limited by 100)
var placesUrl = `https://api.geoapify.com/v1/places?lat1=${bounds.lat1}&lon1=${bounds.lon1}&lat2=${bounds.lat2}&lon2=${bounds.lon2}&type=${type}&limit=100&apiKey=${myAPIKey}`;
fetch(placesUrl).then(response => response.json()).then(places => {
showGeoJSONPoints(places);
});
function showGeoJSONPoints(geojson) {
if (markers.length) {
markers.forEach(marker => marker.remove());
markers = [];
}
// each feature contains 1 place
geojson.features.forEach((feature, index) => {
var markerIcon = document.createElement('div');
markerIcon.classList.add("my-marker");
// Icon size for scaleFactor=1: 31 x 46px, shadow adds: 4px
// Explicitly set scaleFactor=2 in the call
// and backgroundSize=contain to get better
// Marker Icon quality with Mapbox GL
markerIcon.style.backgroundSize = "contain";
markerIcon.style.backgroundImage = `url(https://api.geoapify.com/v1/icon/?type=awesome&color=%233f99b1&text=${index + 1}&noWhiteCircle&scaleFactor=2&apiKey=${myAPIKey})`;
var popup = new maplibregl.Popup({
anchor: 'bottom',
offset: [0, -42] // height - shadow
})
.setText(feature.properties.name);
var marker = new...