Maxime4000
Maxime4000

Reputation: 87

Openlayer popup position is the bottom-center

Hi I was working with the OpenLayers 3 popup and I'm trying to center the popup position in the bottom-middle of where I click whatever is width and height and I can't find how I would do that...

I want something dynamic, not base on a predefined height and width.

I create a JSfiddle base on the example of openlayers 3

DEMO

It's would be simple if the left:50%; work but because it's position:absolute it's has no effect.

.ol-popup {
  position: absolute;

  ...

  //left:-50%; Doesn't work so I don't know what to do
  left: -50px;
  min-width: 250px;
}

Thanks for any anwser

Upvotes: 0

Views: 3580

Answers (3)

MichaelG
MichaelG

Reputation: 737

This should do it:

overlay.on('change:position', function(evt) {
  var width=document.getElementsByClassName('ol-popup')[0].offsetWidth;
  var centerX=-width/2;
  var position=[centerX,0];
  this.setOffset(position);
});

Upvotes: 2

pavlos
pavlos

Reputation: 3081

change your single click listener to this

map.on('singleclick', function(evt) {
  var coordinate = evt.coordinate;
  var pixel = evt.pixel;
  var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
      coordinate, 'EPSG:3857', 'EPSG:4326'));
  var pixelPos = [pixel[0]-(container.offsetWidth/2),pixel[1]-container.offsetHeight];
  var coord = this.getCoordinateFromPixel(pixelPos);
  console.log("coords",coord)
  content.innerHTML = '<p>The arrow is in the middle<br/>And it\'s should pointing where I click (it\'s not the case...)</p><code>' + hdms +
      '</code>';
  overlay.setPosition(coord);
});

Also remove the position:absolutefrom your .ol-popupcss class

Just make sure the function is fired once the container is ready. If you just change your listener function to what I suggest. It wont work on the first click but it should work on every click after the first. Have a look in the code, to get the idea, and adjust it to your case.

check your fiddle here (as said click twice to see it in action). Or better here without removing position absolute

Upvotes: 1

VeloFX
VeloFX

Reputation: 768

If you want to center something just use this:

.ol-popup {
  position: absolute;
  left: 50%;     //this will center the div
  top:50%;   

  width: 250px;  //width and height
  height:100px;  


  margin-left:-125px;  //to center the div at the absolute position (half the width)
  margin-top:-50px;  //to center the div at the absolute position (half the height)

  background-color:#000000;  //and a color for the div
}

Upvotes: 0

Related Questions