Add bearing attribute to proximity

I would like to be able to access the bearing between my personal location and a zone. The most generic and future proof way, to me, would be to add the bearing to the Proximity integration.

It could simply be the bearing from the nearest device tracker to the zone. That is, the same device as that is used for calculating the distance and direction. So, if I’m north of a zone, the bearing would be 180 or 360 degrees. And when I’m east of the zone, the bearing would be 90 or 270 degrees. Etc.

This request is a follow up to an old post of mine:

The logic might be based on this trig computation:

Background / Use Case

I travel to work by bike. My plan is to show a card with information for my daily commute. One of the entities that I want to show (sensor, binary sensor, I don’t know yet) is an average headwind, tailwind or sidewind (or no wind, if the speed is below a certain treshold).

To determine this, I need to calculate a bearing between my current location and my home zone or my work zone. Both have coordinates in my config. I will then compare the bearing with the wind direction.

FYI, this can now be done in a template. All the trig needed has been added since my original comment in that thread.

I’ve tried the earlier python example and came up with this. It calculates, but doesn’t give me the proper results.

{% set x1 = state_attr('person.king', 'latitude') %}
{% set x1 = 51.92 %}
{% set y1 = state_attr('person.king', 'longitude') %}
{% set y1 = 4.56 %}
{% set x2 = state_attr('zone.werk', 'latitude') %}
{% set x2 = 51.88 %}
{% set y2 = state_attr('zone.werk', 'longitude') %}
{% set y2 = 4.53 %}
{% set x = sin(x2-x1)*cos(y2) %}
{% set y = cos(y1)*sin(y2) - sin(y1)*cos(y2)*cos(x2-x1) %}
{% set bearing = atan2(y,x)*180/pi %}
My location: {{x1}},{{y1}}
Work location: {{x2}},{{y2}}
Bearing: {{ bearing }}
Expected approx. bearing: 200 or 20 (depending on direction)

I think I figured it out.

{% set lat1 = state_attr('person.king', 'latitude') %}
{% set lat1 = 51.92 %}
{% set long1 = state_attr('person.king', 'longitude') %}
{% set long1 = 4.56 %}
{% set lat2 = state_attr('zone.werk', 'latitude') %}
{% set lat2 = 51.88 %}
{% set long2 = state_attr('zone.werk', 'longitude') %}
{% set long2 = 4.53 %}
{% set y = sin((long2-long1)*pi/180)*cos(lat2*pi/180) %}
{% set x = cos(lat1*pi/180)*sin(lat2*pi/180)-sin(lat1*pi/180)*cos(lat2*pi/180)*cos((long2-long1)*pi/180) %}
{% set bearing = atan2(y,x)*180/pi %}
{% set bearing = (bearing + 360) % 360 %}
My location: {{lat1}},{{long1}}
Work location: {{lat2}},{{long2}}
Bearing: {{ bearing}}