Mapbox-gl-js: Keeping a marker centered even during map move

Created on 26 Jan 2019  ·  4Comments  ·  Source: mapbox/mapbox-gl-js

I need to keep the marker centered all the time, even during drag and pan of the map and update its LngLat according to the map movement.

While most of it works, but I just can't figure out how to keep the marker cenrtered during the map drag/pan.

Here's what I have so far:
https://jsfiddle.net/iaezzy/yLf4wgzd/1/

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [0, 0],
    zoom: 2
});
var marker = new mapboxgl.Marker()
    .setLngLat([0, 0])
    .addTo(map);

map.on('movestart', function (e) {
    console.log(`Current Map Center: ${map.getCenter()}`);
    marker.setLngLat(map.getCenter());
});
map.on('moveend', function (e) {
    console.log(`Current Map Center: ${map.getCenter()}`);
    marker.setLngLat(map.getCenter());
});

One way I can think of is to poll map.isMoving every few milliseconds and update the markers location but that doesn't seem an optimal solution.

Most helpful comment

You can use move event

map.on('move', function (e) {
    console.log(`Current Map Center: ${map.getCenter()}`);
    marker.setLngLat(map.getCenter());
});

All 4 comments

Isn’t there an event for “move”?

Ah darn, not sure how I missed that. Thanks!

I have found better trick, I hope it will help :
mapbox-gl : [v1.6.0]

```
map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [0, 0],
minZoom: 8,
zoom: 13
});

    marker = new mapboxgl.Marker({
        draggable: true
    })
        .setLngLat([0, 0])
        .addTo(map);

    marker.on('dragend', onDragEnd);

function onDragEnd() {
    var lngLat = marker.getLngLat();
    console.log('Longitude: ' + lngLat.lng + ' Latitude: ' + lngLat.lat);

    // move map to where the marker is dragged 
    map.flyTo({
        center: [
            lngLat.lng,
            lngLat.lat
        ],
        essential: false // this animation is considered essential with respect to prefers-reduced-motion
    });
}

You can use move event

map.on('move', function (e) {
    console.log(`Current Map Center: ${map.getCenter()}`);
    marker.setLngLat(map.getCenter());
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

BernhardRode picture BernhardRode  ·  3Comments

shotor picture shotor  ·  3Comments

iamdenny picture iamdenny  ·  3Comments

yoursweater picture yoursweater  ·  3Comments

mollymerp picture mollymerp  ·  3Comments