Moving marker on click
This example demonstrates how to reposition a marker by clicking on the map. By utilizing the map’s click event, we can dynamically update the marker’s location to match the exact coordinates where the user has clicked. This interactive functionality allows for seamless marker placement and movement across the map.
Click on the map to move the marker.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
container: 'map', // container's id or the HTML element to render the map
style: MapStyle.STREETS,
center: [12.550343, 55.665957], // starting position [lng, lat]
zoom: 9, // starting zoom
});
const marker = new maptilersdk.Marker()
.setLngLat([lng, lat])
.addTo(map);
map.on('click', (evt) => {
marker.setLngLat(evt.lngLat);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Moving marker on click | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
Related examples
Filtered Marker Layout
ExamplesCreate non-colliding marker overlays to display the information from the city and town label layers.