How can I query a radius of coordinates?

admin2025-06-06  1

This is what I am trying

// Each post have a field with coords like:
// The value is a string

usp-custom-90 = 45.46135436613811,9.175124650000043


// Here I am getting some coords from a form
// tehse values are strings

$lat = $_GET['usp-custom-19']; 
$ln = $_GET['usp-custom-20'];

// First I loop all post to get a value
// From which I will create a radius

$args = get_posts( 
    array( 
        'post_type'      => 'post', 
        'posts_per_page' => -1, 
    ) 
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();

        // Get the coords from its custom field

        $customCoords = usp_get_meta(false, 'usp-custom-90');
        $arrayCoords = explode( ",", $customCoords );

        // Here I create a radius by adding 10 to the coords

        $radiusLn = +$arrayCoords[0] + 10;
        $radiusLat = +$arrayCoords[1] + 10;

        // Here I start the second loop and I compare the values            

        $args = array(
            'post_type' => 'post',
            'meta_query' => array(
                array(
                    'relation' => 'AND',
                    array(
                        'key' => 'get_usp-custom-19',
                        'value' => array($ln, $radiusLn),
                        'compare' => '>='
                    ),
                    array(
                        'key' => 'get_usp-custom-20',
                        'value' => array($lat, $radiusLat),
                        'compare' => '<='
                    ),
                ),
            ),
        );
        $query = new WP_Query( $args );
        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                the_title();
            }
        }
    }
}

But I get zero results and the whole logic is wrong. But I can't get my head around it.

One suggestion I had is:

$post_ids = $wpdb->get_col( <<<EOD
SELECT m.post_id FROM $wpdb->postmeta m, $wpdb->postmeta n
    WHERE m.post_id=n.post_id AND m.meta_key='get_usp-custom-19' AND n.meta_key='get_usp-custom-20'
        AND (POW( CAST(m.meta_value AS DECIMAL) - $lat, 2 ) + POW( CAST(n.meta_value AS DECIMAL) - $ln, 2 )) < 100.0
EOD
);

But I don't know how to use it to be honest

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749149824a316789.html

最新回复(0)