Search code examples
openlayersopenlayers-3

OL3 - Find any point within each Polygon


I want to find all the points in the countries, I create a hundred points and search within Polygons. But no results found!

var count = 100;
var features = new Array(count);
var e = 4500000;
for (var i = 0; i < count; ++i) {
  var coordinates = [(2 * e * Math.random() - e)+20, (2 * e * Math.random() - e)+20];
  features[i] = new ol.Feature(new ol.geom.Point(coordinates));
}

var polyFeatures;
$.get(
  'https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json',
  function(res) {
    var format = new ol.format.GeoJSON();
    polyFeatures = format.readFeatures(res);
    polyFeatures.forEach(function(poly) {
      features.forEach(function(point) {
        //console.log(poly.getGeometry().getExtent())
        if(poly.getGeometry().intersectsExtent(point.getGeometry().getExtent())){
          console.log('Fount!');
        }else
        {console.log('Not Fount!')}
      });
    });
  }
);

the code on Plunker is here


Solution

  • Your random points are in map coordinates, the geojson is in lonlat, you need to transform one of them in the search

    if(poly.getGeometry().clone().transform('EPSG:4326','EPSG:3857').intersectsExtent(point.getGeometry().getExtent())){
    

    or

    if(poly.getGeometry().intersectsExtent(point.getGeometry().clone().transform('EPSG:3857','EPSG:4326',).getExtent())){