Search code examples
javascriptanimationopenlayers

Animate current location in Openlayers while the view follows


With openlayers I would like to make the current location visible and follow it with the view. The problem is that the current location updates from the device come in roughly every second and the resulting experience is not nice as the view jumps. This can be smoothed a little bit with a view animation, but then still the current location marker "jumps" on the map, like in this example.

I created an example where I put the current location in an animation (I used this example as base) and update the view directly in the animation. (btw: how can I avoid adding the helperMarker?) This works but calling map.getView().setCenter while the animation seems wrong and I think this is the reason that sometimes the animation is not smooth and it slows down and stutters (reproducible in Chrome and Firefox).

I then implemented another way where I move the current location marker outside of the map into a div element and overlay the map at a fixed location and then I only need to animate the view and center it to the location of this div element. This seems to work but feels like a hack as the current location marker is no longer part of openlayers with potential problems regarding synchronization.

So, what is the proper way with Openlayers for a smooth "synchronizated" of the view and a current location marker?

(So probably something like this or this but for openlayers)


Solution

  • If you already have a view animation that follows the path you can simply draw the marker in the view center in a postrender handler.

    vectorContext.drawGeometry(new Point(getCenter(map.getView().calculateExtent()))
    
    

    I updated the example to keep the point in the view center during the animation (checkbox 'Smooth'): https://codesandbox.io/s/track-position-vfdrx?file=/main.js

    A postrender event on the vector layer only fires when at least one feature is drawn. You can add the postrender event handler to the tile layer to avoid having a helper marker. (See my updated example above)