Cosmos db Multipolygon - Which inner Polygon it belongs to ?

Mathew James 421 Reputation points
2024-07-06T04:08:36.93+00:00

Hi everyone -

I do have a Multipolygon defined with several fences.
When I run a query using st_within, I get only a boolean which indicates my Location is within ANY of the polygon.

The question in addition to this boolean, is it possible to know which exact polygon (in the multipolygon) my location belongs to ?

Thanks!
-Mathew

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,672 questions
0 comments No comments
{count} votes

Accepted answer
  1. Amira Bedhiafi 26,186 Reputation points
    2024-07-06T15:17:55.49+00:00

    You may need to break down the multipolygon into its constituent polygons and store them separately in your database then you can use a query to check which polygon contains the point.

    I am not expert but this is my idea :

    Example of a polygon :

    {
        "id": "polygon1",
        "type": "Polygon",
        "coordinates": [
            [
                [longitude1, latitude1],
                [longitude2, latitude2],
                [longitude3, latitude3],
                [longitude1, latitude1]
            ]
        ]
    }
    

    You will need to write a query to check which polygon contains the point.

    SELECT c.id
    FROM c
    WHERE ST_WITHIN({ "type": "Point", "coordinates": [longitude, latitude] }, c)
    

    This how you might perform this query using the Azure Cosmos DB SDK for JavaScript (Try and tell us ! ) :

    const { CosmosClient } = require("@azure/cosmos");
    const client = new CosmosClient({ endpoint, key });
    const database = client.database(databaseId);
    const container = database.container(containerId);
    const point = {
        type: "Point",
        coordinates: [longitude, latitude]
    };
    const query = {
        query: "SELECT c.id FROM c WHERE ST_WITHIN(@point, c)",
        parameters: [
            { name: "@point", value: point }
        ]
    };
    const { resources: results } = await container.items.query(query).fetchAll();
    if (results.length > 0) {
        console.log("Point is within polygon with id:", results[0].id);
    } else {
        console.log("Point is not within any polygon");
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.