Skip to content

Instantly share code, notes, and snippets.

@shrimp2t
Last active July 30, 2018 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shrimp2t/e72988f93f4e6f54e223d27eb08047ba to your computer and use it in GitHub Desktop.
Save shrimp2t/e72988f93f4e6f54e223d27eb08047ba to your computer and use it in GitHub Desktop.
Get distance from lat and long
<?php
/**
* Get the SQL query for getting listings within a given proximity.
*
* @link https://wordpress.stackexchange.com/a/206560/123815
* @since 1.0.0
*/
public function get_proximity_sql() {
global $wpdb;
return "
SELECT $wpdb->posts.ID,
( %s * acos(
cos( radians(%s) ) *
cos( radians( latitude.meta_value ) ) *
cos( radians( longitude.meta_value ) - radians(%s) ) +
sin( radians(%s) ) *
sin( radians( latitude.meta_value ) )
) )
AS distance, latitude.meta_value AS latitude, longitude.meta_value AS longitude
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta
AS latitude
ON $wpdb->posts.ID = latitude.post_id
INNER JOIN $wpdb->postmeta
AS longitude
ON $wpdb->posts.ID = longitude.post_id
WHERE 1=1
AND ($wpdb->posts.post_status = 'publish' )
AND latitude.meta_key='geolocation_lat'
AND longitude.meta_key='geolocation_long'
HAVING distance < %s
ORDER BY distance ASC";
}
$proximity = absint( $form_data['proximity'] );
$location = isset($form_data['search_location']) ? sanitize_text_field( stripslashes( $form_data['search_location'] ) ) : false;
$lat = (float) $form_data['search_location_lat'];
$lng = (float) $form_data['search_location_lng'];
$units = isset($form_data['proximity_units']) && $form_data['proximity_units'] == 'mi' ? 'mi' : 'km';
if ( $lat && $lng && $proximity && $location ) {
// dump($lat, $lng, $proximity);
$earth_radius = $units == 'mi' ? 3959 : 6371;
$sql = $wpdb->prepare( $this->get_proximity_sql(), $earth_radius, $lat, $lng, $lat, $proximity );
// dump($sql);
$post_ids = (array) $wpdb->get_results( $sql, OBJECT_K );
if (empty($post_ids)) $post_ids = ['none'];
$args['post__in'] = array_keys( (array) $post_ids );
// Remove search_location filter when using proximity filter.
$args['search_location'] = '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment