Hi @aleperix. The easiest way I can think of to do something like this would be to install a plugin like Advanced Custom Fields.
First, set up a ‘Owners’ field with ‘Type = User’ and ‘Select multiple values? = Yes’. Show this when ‘Post type = post’.
Then, set up a ‘Location’ field with Type = Google Map. Show this when ‘User form’ = ‘Add / Edit’.
Now write some custom code in the post template that loops through all of the post’s owners and selects the one that is nearest to a given address.
$origin = array( 'lat' => -33.865143, 'lng' => 151.209900 );
$owners = get_field( 'owners' );
foreach ( $owners as $owner ) {
$location = get_field( 'location', 'user_' . $owner->ID );
$distance = haversineGreatCircleDistance( $origin['lat'], $origin['lng'], $location['lat'], $location['lng'] );
if ( ! isset( $nearest_distance ) || $distance < $nearest_distance ) {
$nearest_distance = $distance;
$nearest_owner = $owner;
}
}
// From https://stackoverflow.com/a/10054282
function haversineGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
printf( 'The nearest owner is: %s', $nearest_owner->display_name );