Skip to main content

Dynamic icon

Build dynamic point icons using Canvas API

show
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dynamic icon</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<script src='https://delivery.mapmost.com/cdn/sdk/webgl/v9.16.0/mapmost-webgl-min.js'></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>

<script>
const map = new mapmost.Map({
container: 'map',
style: '<your style url>',
center: [120.72862794279075, 31.326409968777853],
zoom: 10,
userId: '***', // Authorization code
});

const size = 200;

//Define color variables
const color = '#297F87'
const rgba1 = `rgba(61, 243, 245,`
const pulsingDot = {
width: size,
height: size,
data: new Uint8Array(size * size * 4),

// Get the canvas for drawing the map
onAdd: function () {
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
this.context = canvas.getContext('2d');
},

// Refresh the icon every frame of rendering
render: function () {
const duration = 1000;
const t = (performance.now() % duration) / duration;

const radius = (size / 2) * 0.2;
const outerRadius = (size / 2) * 0.5 * t + radius;
const context = this.context;

// Draw the outer diffusion ripple of the dot
context.clearRect(0, 0, this.width, this.height);
context.beginPath();
context.arc(
this.width / 2,
this.height / 2,
outerRadius,
0,
Math.PI * 2
);
context.fillStyle = rgba1 + `${(0.7- t)<0?0:(0.7- t)})`;
context.fill();

//Draw the center point
context.beginPath();
context.arc(
this.width / 2,
this.height / 2,
radius,
0,
Math.PI * 2
);
context.fillStyle = color;
context.fill();

//Update dynamic picture data
this.data = context.getImageData(
0,
0,
this.width,
this.height
).data;

// Continuously redraw the map so that the points have smooth animation
map.triggerRepaint();

//Notify that the map image has been updated
return true;
}
};

//Add layer
map.on('load', () => {
map.addImage('pulsing-dot', pulsingDot, { pixelRatio: 2 });

map.addSource('dot-point', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [120.60077271290618, 31.31545402626199]
}
}
]
}
});
map.addLayer({
'id': 'symbol-layer',
'type': 'symbol',
'source': 'dot-point',
'layout': {
'icon-image': 'pulsing-dot'
}
});
});
</script>

</body>
</html>