简体   繁体   中英

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 初始] Currently After zooming in ] Expected after zooming in or out

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]]);

You are setting the coordinates of the popup to the event-coordinates which can be slightly off.

Try setting the coordinates of the popupt to the coordinates of the feature like:

let coordinate = feature.getGeometry().getCoordinates();

https://jsfiddle.net/2jf56q0g/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM