Hi,
I'm not a php expert. Can experts here give me a php code to put in my CCK calculated field ?

I just need to calculate the distance between User location(user who view the node) and node location(author specifies).

Thank you for any help.

Comments

nevets’s picture

This answer uses "Node Locations", "User Locations" and Dynamic Field for the calculated field (there is a dynamic field and a computed field, not sure which are using).

Place the following code in the PHP code box for the dynamic field

global $user;
$account = user_load(array('uid' => $user->uid));
$node_at = location_latlon_exact($node->locations[0]);
$user_at = location_latlon_exact($account->locations[0]);
$answer = "unknown";
if ( !empty($node_at) && !empty($user_at) ) {
  $dist = location_distance_between($node_at, $user_at, 'mile');
  $answer = format_plural($dist['scalar'], $dist['scalar'] . ' ' . $dist['distance_unit'], $dist['scalar'] . ' ' . $dist['distance_unit'] . 's');
}
return $answer;

Note the code returns 'unknown' if either the node or user location is not set or the coordinated can not be determined.

Also note you can change 'mile' to 'km'.

Ayesh’s picture

Thank you VERY much Nevets.
Yes, Dynamic field is what I need to use rather than Computed field.
I'm going to install dyna field, and put your great code. I'll come with results.

hsiyao’s picture

Hi,

thanks for this great code!
Maybe you'd like to help me with a question regarding how to use the distance in a calculation:

I'd like to have something like

distance(without miles or km)*0.02 = result

and have that result printed underneath the distance

thanks in advance!