簡體   English   中英

如何使用mysql查找多邊形線內的位置

[英]How to find locations which are within polygon cords using mysql

我想搜索多邊形坐標內的地方。

我的多邊形線 json 數組是這樣的:

[{"lat":23.044131034993626,"lng":72.52770534192086},{"lat":23.045493462614736,"lng":72.53060212765695},{"lat":23.04381510777979,"lng":72.53163209591867},{"lat":23.042472408854092,"lng":72.52843490277291}]

我的數據庫表名是地方,它的值如下:

id  lat         lng         
1   23.0449391  72.5301363 
2   23.044816   72.529531  
3   23.0439868  72.5291617 
4   23.0440151  72.5291033 
5   23.0441163  72.529624  
6   23.044531   72.52946   
7   23.0449581  72.5301291 
8   23.044081   72.529584  
9   23.0440654  72.5295851 
10  23.0443758  72.529803  
11  23.047929   72.527231    
11  23.0464945  72.5288149 

所以我想要多邊形線內的地方

在上表中,前 10 個點在多邊形線中,其余兩個在多邊形線之外

我試過這個查詢,但它不起作用

select id, lat, lng from places 
where st_within(point(lng, lat),  ST_GeomFromText('Polygon((72.52770534192086 23.044131034993626, 72.53060212765695 23.045493462614736, 72.53163209591867 23.04381510777979,72.52843490277291 23.042472408854092))'));

所以請建議我為此使用 mysql 選擇查詢。

我不知道在 MySql 中是否有辦法做到這一點,但在 PHP 中你可以做到。

如果您可以從您的數據庫中以如下數組結構檢索數據

$pol = array(
    array('lat' => 23.034002369168842,'lng' => 72.56034198842099),
    array('lat' => 23.033439580995058,'lng' => 72.56498757443478),
    array('lat' => 23.03146486705749, 'lng' => 72.56323877415707),
    array('lat' => 23.029875201316813,'lng' => 72.55889359555295),
    array('lat' => 23.031682087006978,'lng' => 72.55772415242245),
    array('lat' => 23.032955778756484,'lng' => 72.55875412068417),
    array('lat' => 23.033972748797236,'lng' => 72.56003085217526)
);

以及您點的坐標,例如

$point = array('lat' =>, 23.0337224, 'lng' => 72.5668896);

告訴您點是否在多邊形內的函數可能類似於

function is_inside($point, $polygon) {
    if ($polygon[0] != $polygon[count($polygon) - 1])
        $polygon[count($polygon)] = $polygon[0];
    $j = 0;
    $inside = false;
    $x = $point['lat'];
    $y = $poin['lng'];
    $n = count($polygon);
    for ($i = 0; $i < $n; $i++) :
        $j++;
        if ($j == $n)
            $j = 0;
        if ((($polygon[$i]['lng'] < $y) && ($polygon[$j]['lng'] >= $y)) || (($polygon[$j]['lng'] < $y) && ($polygon[$i]['lng'] >= $y))) :
            if ($polygon[$i]['lat'] + ($y - $polygon[$i]['lng']) / ($polygon[$j]['lng'] - $polygon[$i]['lng']) * ($polygon[$j]['lat'] - $polygon[$i]['lat']) < $x)
                $inside = !$inside;
        endif;
    endfor;

    return $inside;
}

所以你可以檢查點是否在里面只是調用函數

if(is_inside($point, $polygon)){
     /* do something */
}

暫無
暫無

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

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