簡體   English   中英

使用帶有多個參數的 C# 路由調用 POSTGIS 以確定一個點是否在半徑內

[英]using C# route with multiple parameters to call POSTGIS to determine if a point is in a radius

當我嘗試運行此 controller 時,在 postman 中不斷出現錯誤“Npgsql.PostgresException (0x80004005): XX000: parse error - invalid geometry”

我嘗試直接將數字硬編碼到查詢中並且效果很好所以我認為我無法從路線中獲取經度和緯度

[HttpGet("VerifyRegion/{lat}/{longitude}")]
public async Task<Object> VerifyRegion(double lat, double longitude)
{
    string connectionString = "Host=localhost;Username=alex;Password=;Database=PostGISTest";
    await using var conn = new NpgsqlConnection(connectionString);
    await conn.OpenAsync();
    
    await using (var cmd = new NpgsqlCommand("select ST_DWithin(st_geomfromtext('POINT((@latty) (@longy))', 4326),st_geomfromtext('POINT(54.21 22.54)', 4326), 100);", conn))
    {

        cmd.Parameters.AddWithValue("latty", lat);
        cmd.Parameters.AddWithValue("longy", longitude);

        await cmd.ExecuteNonQueryAsync();

        await using var reader = await cmd.ExecuteReaderAsync();
        while (await reader.ReadAsync())
        {
            return Ok(reader.GetBoolean(0));
        }
    };

   

    return Ok();
}

SQL:

select
    ST_DWithin(
        st_geomfromtext(
            'POINT((@latty) (@longy))', 
            4326
        ),
        st_geomfromtext(
            'POINT(54.21 22.54)',
            4326
        ),
        100
    );

每個坐標周圍都有一個額外的括號。 嘗試刪除它。

st_geomfromtext('POINT(@longy @latty)',4326)

話雖如此,使用另一種方法來創建點會更強,例如st_makePoint 無需將坐標轉換為文本。

另外,請注意坐標順序:首先是經度,然后是緯度。

st_dwithin使用幾何坐標系,因此您在這里尋找彼此相距 100 度(而不是米)內的點。

您不能使用ExecuteNonQueryAsync ,因為它是一個返回 boolean 的查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM