My purpose is to display only features that have coordinate inside my map viewport (map area currently displayed).
I get the extent of the viewport by doing:
var mapExtent = this.map.getView().calculateExtent(this.map.getSize());
mapExtent = ol.proj.transformExtent(mapExtent, 'EPSG:3857', 'EPSG:4326');
and after, in a loop where I am reading the element of one store,
var point = ol.proj.fromLonLat([
element.get('longitude'),
element.get('latitude')
]);
elementPoint = new ol.geom.Point(point);
var feature = new ol.Feature(elementPoint);
var coordsFeatures = feature.getGeometry().getCoordinates();
and after, just to quickly see if the point is inside my viewport, I use just a console log:
console.log(ol.extent.containsXY(mapExtent, coordsFeatures[0],coordsFeatures[1]));
/*if(!ol.extent.containsXY(mapExtent, coordsFeatures[0],coordsFeatures[1])){
return true;
}*/
But I don't know why, the result is only false, even if for sure there are points inside the map area currently displayed.
Whart I am doing wrong?
You are mixing projections.
For the extent, you change from 3857 to 4326.
For the point, by applying ol.proj.fromLonLat()
, you change from 4326 to 3857 (the default )
Just use 3857 or 4326 for both
So I will post the correct code in case someone else may need it. As mentioned by @GH (thank you again) my problem was the mixing projections, so I changed my code in this way:
instead of using the coordinate, I get the extent of the feature:
var extentFeature = feature.getGeometry().getExtent();
and after i applied to it the same transformExtent used for the map:
extentFeature = ol.proj.transformExtent(extentFeature, 'EPSG:3857', 'EPSG:4326');
if(!ol.extent.containsExtent(mapExtent, extentFeature)){
return true;
}
and now it works: :D
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.