Raymond Seger
Raymond Seger

Reputation: 1130

Wordpress ACF Google Map How to get the objects that are 10 km from some latitude longitude?

I am using Wordpress ACF plugin, and there's a field type of Google Map. It stored the Lat,Long and Address.

Now, i have some user's latitude and longitude. I need a way to get only the objects that are no more than 10km in distance.

This is a server Wordpress question. For now, i am simply getting ALL the gyms i wanted instead of only the nearest (10 km maximum) gym around the user current position. There is a field called "gym_location" which is a Google Map type. The problem is, i don't know the math formula.

// get all objects
$query_for_ojektaxi_user = new WP_Query( array(
    'post_type'  => 'gyms',
    'meta_query' => array(
        array(
            'key'       => 'open_or_closed',
            'value'     => 1,
            'compare'   => '=',
        )
    )
));

Upvotes: 0

Views: 1031

Answers (2)

Gruffy
Gruffy

Reputation: 1531

As @drzdraf says, the location data is serialized, so it is not useful for a WP query. What you can do is hook into the acf/save_post action and duplicate the lat and lng properties to some post meta, which can then be searched:

add_action('acf/save_post', function (int $id): void {
    // Check we are saving the relevant post type
    if (get_post_type($id) !== 'my_post_type') {
        return;
    }

    // Get the location data that was just saved
    $location = get_field('my_location_field', $id);

    // Save the data to `lat` and `lng` meta properties.
    if ($location) {
        update_post_meta($id, 'lat', $location['lat']);
        update_post_meta($id, 'lng', $location['lng']);
    }
});

Then when querying:

// Bounding box
$topLeft = [
    'lat' => 44.319304
    'lng' => -79.989017
];

$bottomRight = [
    'lat' => 43.200546
    'lng' => -76.020305
];


$query = new WP_Query([
    'post_type' => my_post_type,
    'posts_per_page' => -1,
    'meta_query' => [
        'relation' => 'AND',
        [
            'key' => 'lat',
            'value' => (float) $topLeft['lat'],
            'compare' => '>=',
            'type' => 'DECIMAL(10,3)'
        ],
        [
            'key' => 'lat',
            'value' => (float) $bottomRight['lat'],
            'compare' => '<=',
            'type' => 'DECIMAL(10,3)'
        ],
        [
            'key' => 'lng',
            'value' => (float) $topLeft['lng'],
            'compare' => '>=',
            'type' => 'DECIMAL(10,3)'
        ],
        [
            'key' => 'lng',
            'value' => (float) $bottomRight['lng'],
            'compare' => '<=',
            'type' => 'DECIMAL(10,3)'
        ]
    ]
]);

Upvotes: 0

drzraf
drzraf

Reputation: 511

You won't be able to make direct (and useful) use of lng or lat "subfields" of the googlemap advanced custom field inside the SQL query. The values are serialized in the mysql "meta_value" (text) column of the post_meta table.

Upvotes: 1

Related Questions