jfgodoy / knex-postgis

postgis extension for knex
MIT License
183 stars 25 forks source link

QUESTION: Polygons #15

Closed vinceprofeta closed 8 years ago

vinceprofeta commented 8 years ago

I am trying to store a polygon to use as a geo fence and then query if a point is within the geo fence. Can you provide an example of how to store this data.

I have the following table.specificType('polygon', 'geometry(Polygon, 4326)')

What would be the appropriate way to insert the data?

Thanks, sorry for the novice question.

jfgodoy commented 8 years ago

Hi @vinceprofeta, If you have only one polygon you don't need to save it in a table, instead you can use the library turf-inside to check if a point is inside the polygon. However, if you have many polygons and you want to query if a point is inside some of them you can do the following:

to insert a record in the table you can use:

    var polygon = st.geomFromGeoJSON({
      "type": "Polygon",
      "coordinates": [
        [
          [
            -70.85357666015625,
            -33.536816067733
          ],
          [
            -70.85357666015625,
            -33.355767498334146
          ],
          [
            -70.521240234375,
            -33.355767498334146
          ],
          [
            -70.521240234375,
            -33.536816067733
          ],
          [
            -70.85357666015625,
            -33.536816067733
          ]
        ]
      ],
      "crs":{"type":"name","properties":{"name":"EPSG:4326"}}
    });

    return knex.insert({'polygon': polygon}).into('mytable')

and to query if a point is inside some polygons in the table:

    var point = st.geomFromGeoJSON({
      "type": "Point",
      "coordinates": [
        -70.62080383300781,
        -33.45206821659519
      ],
      "crs":{"type":"name","properties":{"name":"EPSG:4326"}}
    });

    return knex
      .select('*')
      .from('mytable')
      .where(st.intersects('polygon', point))
      .then(function(results) {
        console.log(results)
      });

There are other ways to insert polygons and to create points, this is only one of them. I hope this works for you and if you have any problems, let me know.

vinceprofeta commented 8 years ago

@jfgodoy Thanks for the quick response! It appears to be working correctly. I will dive deeper and let you know if I have any more questions