Ad

Openlayers How To Update Overlay Position On Map Moveend Event

I have a Point feature of type ol.geom.Point on openlayers map and there is a popup which I am displaying on clicking the feature. The popup is <div> element which I have added as an overlay, I am displaying and hiding the overlay whenever I find the feature on click event on the map.

The problem is the overlay dislocates (tip and div) when you zoom in or out on the map. However if you click again on feature it displays properly but clicking each time is not ideal. Also I am trying to display the overlay in every world, the problem is same for every world, it dislocates.

The expected outcome is whenever I click on feature the overlay should be displayed on the feature, irrespective of zoom in or out.

Here is a working fiddle to reproduce the problem : Openlayers overlay JSFiddle

Screenshots: Initial Initial] Currently After zooming in ]Expected after zooming in or out

Ad

Answer

To position precisely on the feature, but in the world you clicked on:

var worldWidth = ol.extent.getWidth(view.getProjection().getExtent());
var world = Math.floor((map.getCoordinateFromPixel(evt.pixel)[0] + worldWidth/2)/worldWidth);
let coordinate = feature.getGeometry().getCoordinates();
content.innerHTML = feature.get('desc');
popup.setPosition([coordinate[0] + world*worldWidth, coordinate[1]]);
Ad
source: stackoverflow.com
Ad