MapLibre GL: Display GeoJSON points as layer with custom markers
Draw GeoJSON.Points as layer with MapLibre GL
by Geoapify
HTML
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css">
<div id="my-map"></div>
CSS
body {
margin: 0;
padding: 0;
}
#my-map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
JavaScript
// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
var myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";
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());
map.on('load', () => {
// getting an icon from Geoapify Icons API
// Explicitly set scaleFactor=2 in the call
// and {pixelRatio: scale} to get better
// Marker Icon quality with MapLibre GL
var scale=2;
map.loadImage(`https://api.geoapify.com/v2/icon/?icon=coffee&scaleFactor=${scale}&color=%23ff9999&size=45&type=awesome&apiKey=${myAPIKey}`, function(error, image) {
if (error) throw error;
map.addImage('rosa-pin', image, {pixelRatio: scale}); //38x55px, shadow adds 5px
});
var type = "catering.cafe"
// getting cafes for the given boundary (number of results limited by 100)
var placesUrl = `https://api.geoapify.com/v2/places?categories=catering.cafe&filter=rect:${bounds.lon1},${bounds.lat1},${bounds.lon2},${bounds.lat2}&limit=100&apiKey=${myAPIKey}`
fetch(placesUrl).then(response => response.json()).then(places => {
showGeoJSONPoints(places, type);
});
});
function showGeoJSONPoints(geojson, id) {
var layerId = `${id}-layer`;
if (map.getSource(id)) {
// romove first the old one
map.removeLayer(layerId);
map.removeSource(id);
}
map.addSource(id, {
'type': 'geojson',
'data': geojson
});
map.addLayer({
'id': layerId,
'type': 'symbol',
'source': id,
'layout': {
'icon-image': 'rosa-pin',
'icon-anchor':...