I’m trying to find the shortest distance with name between phone and GPS locations. I have enabled phone location and tried below code but the result is unknown. Can someone help?
{% set locations = {
"San Francisco": (5.169231175822279, 76.50155407099898),
"Los Angeles": (5.169135339347688, 76.50266904873067),
} %}
{% set phone_lat = state_attr('device_tracker.iphone', 'latitude') %}
{% set phone_lon = state_attr('device_tracker.iphone', 'longitude') %}
{% if phone_lat is not none and phone_lon is not none %}
{% set min_dist = 9999 %}
{% set closest_location = "Unknown" %}
{% for name, coords in locations.items() %}
{% set dist = distance(phone_lat, phone_lon, coords[0], coords[1]) %}
{% if dist < min_dist %}
{% set min_dist = dist %}
{% set closest_location = name %}
{% endif %}
{% endfor %}
Closest Location: {{ closest_location }}
{% else %}
"Unknown"
{% endif %}
This is Ok in the Developer Tool template but still shows unknown when the sensor is set. Any idea? I have cleared browser cache but the issue still persists.
You need to get rid of the unit of measurement. Sensor’s with a defined unit_of_measurement must return a numeric value… your template will always return a string like “Las Vegas: 3010.1 km”.