Search code examples
javascriptgeolocationopenlayers-3geoserver

check if a lat long is within an extent using open layers 3


I have a UK county shape file (Multipolygon) using EPSG:4326 in my geoserver. I'm using open layers 3 to load this shape file in my application as below :

source = new ol.source.XYZ({url: '/gmaps?zoom={z}&x={x}&y={y}&Layers=UKCounties', crossOrigin: "anonymous"});
countiesLayer = new ol.layer.Tile({source: source});
map.addLayer(countiesLayer);

This works well. I have a requirement to get users current location which is done as

var coordinate = geolocation.getPosition();

I'm able to retrieve the correct lat & long here. Ex : Lat = 53.797534899999995, Lng = -1.5449. now I need to check which of the counties (polygon) these points are in using open layers 3 & Javascript. Using Geoserver WFS, I'm able to get the bounding box of each of the counties as

$.each(features, function(index, eachFeature) {
            var bbox = eachFeature.properties.bbox;
            if (bbox != null) {
              var bottomLeft = ([bbox[0], bbox[1]]);
              var topRight = ([bbox[2], bbox[3]]);
              var extent = new ol.extent.boundingExtent([bottomLeft, topRight]);

            if (ol.extent.containsXY(extent1,lat,long)) {
                alert("got the feature");
            }
        }

});

The issue is my code doesn't print the alert statement.I've also tried using

if (ol.extent.containsXY(extent,long,lat))

and

var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');

if (ol.extent.containsXY(extent,XY[0],XY[1])) if (ol.extent.containsXY(extent,XY[1],XY[0]))

But none of these print the alert. Is there anything wrong in this?


Solution

  • I had to use

    var XY = ol.extent.applyTransform(extent, ol.proj.getTransform("EPSG:3857", "EPSG:4326"));
    

    instead of

    var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
    

    and it works.