In this code, I'm loading a bunch of random points that are roughly in the contiguous USA. I've created a OpenLayers.Bounds object roughly corresponding to that extent.
When I select a point, I want to determine whether that point falls within those Bounds. If you load up this code, you'll see that clicking on a point in the USA should cause Bounds#containsLonLat to return true. But alas, no.
Why?
var map, osm;
var fromProj = new OpenLayers.Projection("EPSG:4326");
var toProj = new OpenLayers.Projection("EPSG:900913");
var center, pointsLayer, usaBounds;
$(function() {
var vector = new OpenLayers.Layer.Vector('vector');
var boxes = new OpenLayers.Layer.Vector( "Boxes", { style: {fillColor: '#000', fillOpacity: 0.1, strokeWidth: 0}} );
map = new OpenLayers.Map("map", {});
osm = new OpenLayers.Layer.OSM();
center = new OpenLayers.LonLat(-98.5795, 39.8282).transform(fromProj, toProj);
pointsLayer = new OpenLayers.Layer.Vector("Clients", {});
var px, py;
var pointFeatures = [];
for(var i=0; i< 50; i++) {
// 50 random points roughly in continental USA
var latMin = 30; var latMax = 50; var longMin = -120; var longMax = -50;
py = Math.floor(Math.random() * (latMax - latMin + 1) + latMin);
px = Math.floor(Math.random() * (longMax - longMin + 1) + longMin);
var pointGeometry = new OpenLayers.Geometry.Point(px, py).transform(fromProj, toProj);
var pointFeature = new OpenLayers.Feature.Vector(pointGeometry);
pointFeatures.push(pointFeature);
}
pointsLayer.addFeatures(pointFeatures);
usaBounds = new OpenLayers.Bounds(-125, 50, -60, 20);
usaBounds.transform(fromProj, toProj);
var box = new OpenLayers.Feature.Vector(usaBounds.toGeometry());
boxes.addFeatures(box);
map.addLayers([osm,pointsLayer,boxes]);
var selectControl = new OpenLayers.Control.SelectFeature(pointsLayer, {
hover: false, clickout: true,
onSelect: function(feature) {
thisFeature = feature;
ll = feature.geometry.getBounds().getCenterLonLat();
px = map.getPixelFromLonLat(ll);
// ll.transform(fromProj, toProj);
console.log(usaBounds.toBBOX());
var containsLL = usaBounds.containsLonLat(ll);
// >>>>>>>> THIS IS ALWAYS FALSE, BUT SHOULD BE TRUE
console.log("Contains LonLat: " + containsLL);
var containsPixel = usaBounds.containsPixel(px);
// >>>>>>>> LIKEWISE, THIS IS ALWAYS FALSE, BUT SHOULD BE TRUE
console.log("Contains Pixel: " + containsPixel);
}
});
map.addControl(selectControl);
selectControl.activate();
map.setCenter(center,3);
}); // end JQR
</script>