Experiment with Location, geofencing, and a MQTT button
TL;DR, This Saturday I did experiment with my Node-RED server and some geo fencing APIs.
I create a location-sensitive button; when a user's mobile is inside the geo-fencing (red circle), the lamp glows up, and once the user's mobile goes out, the lamp glows down.
I used one open-source library to achieve this: node-red-contrib-world-map.
The node-red-contrib-web-worldmap 5.1.2 is a popular Node-RED node that allows you to display geographical data on an interactive world map within your Node-RED flows. and some JavaScript code snippets. Like
// Function node code
var circleData = flow.get("circleData");
var circleLat = circleData.lat;
var circleLon = circleData.lon;
var circleRadius = circleData.radius;
var currentLat = msg.payload.lat;
var currentLon = msg.payload.lon;
if (circleData && msg.payload) {
function calculateDistance(lat1, lon1, lat2, lon2) {
// Haversine formula (approximate distance)
var R = 6371e3; // Earth radius in meters
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
var distance = calculateDistance(circleLat, circleLon, currentLat, currentLon);
if (distance <= circleRadius) {
msg.payload = { inside: true, distance: distance , radius: circleRadius};
} else {
msg.payload = { inside: false, distance: distance ,radius: circleRadius };
}
}else{
node.error = "somthing went wrong"
}
return msg;
The idea is completely based on the Haversine formula , with this help, I create the above method, which returns an object containing a boolean (which tells if the mobile is inside the geofencing or outside), the distance of the mobile (GPS device) from the center (geofencing), and the radius of geofencing.
If the mobile is inside the fencing, then the lamp glows up and vice versa.
Use case:
If you are an IoT hobbyist and you have the knowledge of Node-RED, then you can use my work by downloading my workflow in the given link.
If you want to lean IOT with me, then you can message me at linkedin