2

I am trying to do this example: I have an openlayers3 map, and one point of interest.

In this map, I can draw a bounding box and after, clicking on check button, the script has to tell me if the bounding box contains or not my point of interest.

This is my map:

        var init = function () {
        var raster = new ol.layer.Tile({
            source: new ol.source.MapQuest({
                layer: 'osm'
            })
        });
        source = new ol.source.Vector({
            wrapX: false
        });
        var vector = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: '#ffcc33',
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 7,
                    fill: new ol.style.Fill({
                        color: '#ffcc33'
                    })
                })
            })
        });
        map = new ol.Map({
            target: 'map',
            layers: [raster,vector],
            view: new ol.View({
              center: ol.proj.fromLonLat([11.249367, 43.774298]),
              zoom: 15
            })
        });

        // SMN marker
        var pos = ol.proj.fromLonLat([11.2490443, 43.774704]);
        var marker = new ol.Overlay({
          position: pos,
          positioning: 'center-center',
          element: document.getElementById('marker'),
          stopEvent: false
        });
        map.addOverlay(marker);

        // Vienna label
        var smn = new ol.Overlay({
          position: pos,
          element: document.getElementById('smn')
        });

        map.addOverlay(smn);

        // Popup showing the position the user clicked
        var popup = new ol.Overlay({
          element: document.getElementById('popup')
        });
        map.addOverlay(popup);      
    };

This is the function that help me to draw a poligon. When I draw a poligon, if exist another poligon it is deletd.

function addInteraction() {

        var ct = 0;
        draw = new ol.interaction.Draw({
            source: source,
            type: 'Polygon',
            geometryFunction: function (c, g) {
                if (goog.isDef(g)) {
                    g.setCoordinates(c);
                } else {
                    g = new ol.geom.Polygon(c);
                }
                if (c[0].length > ct) {
                    console.log('click coord : ' + c[0][c[0].length - 1]);
                    var coord = c[0][c[0].length - 1];
                    coordinates.push(coord);
                    $('div#coordinate').html( $('div#coordinate').html() + "<p>" + ( Number(coord[0]).toFixed(2) ) + " - " + ( Number(coord[1]).toFixed(2) ) + "</p>" );
                    ct = c[0].length;
                } else {
                    console.log('move coord : ' + c[0][c[0].length - 1]);

                }

                return g;
            }
        });
        draw.on('drawend',  function(e) {
            lastFeature = e.feature;
        })

        draw.on('drawstart', function (e) {
            source.clear();
        });
        map.addInteraction(draw);

    }

And this the body init function:

    function config(){
        init();
        $('button#check').on('click', function () {
         // something
        });
        $('button#draw').on('click', function () {
            coordinates=[];
            map.removeInteraction(draw);
            addInteraction();
        });
        $('button#nodraw').on('click', function () {
            map.removeInteraction(draw);
        });
    };

I have set one point of interest with static coordinate. Clicking on Draw button I can draw a box on the map specifying the the vertices of the polygon. After the poligon is done I can click on the Stop Drawing button.

The last step is clicking on check button...I ask you if you can help me to write the function that check if the point of interest is in the poligon bounding box.

The array coordinates contains the coordinates of the poligon.

My JsFiddle http://jsfiddle.net/michelejs/3zawt33b/6/

Thanks

Jose Gómez
  • 3,110
  • 2
  • 32
  • 54
michele
  • 26,348
  • 30
  • 111
  • 168

1 Answers1

4

You can get the drawn polygon extent and check if some coordinate is inside of it:

draw.on('drawend', function(evt){
  var coord = ol.proj.fromLonLat([11.2490443, 43.774704]);
  var polygon_extent = evt.feature.getGeometry().getExtent();
  var contains = ol.extent.containsCoordinate(polygon_extent, coord);
  console.info(contains);
});
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
  • It seems work! The last question...how can I convert the poligon coord to lat lon??? Thank you so much! – michele Jan 22 '16 at 18:26
  • Check [`ol.geom.Polygon#getCoordinates`](http://openlayers.org/en/master/apidoc/ol.geom.Polygon.html#getCoordinates). Each vertex has a coordinate. In my answer the polygon is `evt.feature.getGeometry()`. – Jonatas Walker Jan 22 '16 at 18:30
  • hmm it don't help me...here my question: http://stackoverflow.com/questions/34954901/openlayers3-get-lat-long-coordinate-from-polygon – michele Jan 22 '16 at 19:57
  • What's going on @michele? I answered your (deleted) question. Now this one remains open? – Jonatas Walker Jan 22 '16 at 21:25
  • Sorry Jonatas, I had bad exposed the deleted question. I wuold simply convert the coordinate to EPSG:4326. I solved it. The problem is that I can't add the containsCoordinate( ) function at check button click event. sorry for the misunderstanding – michele Jan 22 '16 at 21:29
  • In your answer the solution is connected with draw.on('drawend') trigger but I have to connect at $("button#check").on("click",...) event – michele Jan 22 '16 at 21:31
  • All right @michele . You can **store a global reference (variable)** to the drawn feature inside `draw.on('drawend')` then use `containsCoordinate( )` function at check button. – Jonatas Walker Jan 22 '16 at 21:37
  • hmm sorry I don' understand @jonatas-walker how I can set evt variable as a global reference. can you give me an example? – michele Jan 22 '16 at 21:45
  • ooooooooook solved!!! thanks @jonatas-walker. I stored evt at draw end trigger in a global variable. – michele Jan 22 '16 at 21:55