13

What is the fastest way to get the pixel coordinates of a OpenLayers.Feature.Vector? I mean, I want to get the pixel (top,left) position relative to map container of a already drawn feature, if possible without calculations because performance improvements.

Thanks & regards, Rafael.

Rafael
  • 307
  • 1
  • 3
  • 16

1 Answers1

31

In ol3:

var geometry = feature.getGeometry();
var coordinate = geometry.getCoordinates();
var pixel = map.getPixelFromCoordinate(coordinate);

In OL2:

var geometry = feature.geometry;
var coordinate = new OpenLayers.LonLat(geometry.x, geometry.y);
var pixel = map.getPixelFromLonLat(coordinate);

A few prerequisities: the feature must be point, otherwise geometry.getCoordinates() returns an array of coordinates and you need to choose one. The other should be pretty obvious but I'll mention it anyway: variable map is an instance of ol.Map or OpenLayers.Map respectivelly

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
Kenny806
  • 595
  • 4
  • 8
  • If he wants to get the top left, you can also do, var bounds=geom.getBounds() and then get left, and top, from the bounds object. – John Powell Jun 13 '14 at 09:38
  • I don't know how to use bounds.left & bounds.top because it don't change on zoom change. I have to go throw an array of 3000-5000 features in the worst case. So I was looking for the fastest way to access (cx, cy). – Rafael Jun 15 '14 at 17:43
  • You can always store it as an attribute of the polygon when you create or modify it and then look it up, rather than recalculating it. – John Powell Jun 15 '14 at 20:00
  • @JohnBarça Not a bad idea, but you need to consider how often you would access those coordinates. Your proposal could result in the coordinates being calculated more often than if you only calculate them when you need them. Just saying it's use-case-specific. – Kenny806 Jul 20 '15 at 11:17