leaflet maps with websocket/mqtt integration

Leaflet (http://leafletjs.com) is a javascript library for maps. It have lot of options for maps. Let we setup & try this.

You can download and configure directly as given examples, I choose option with yarn.

$ mkdir client

$ cd client

$ yarn add leaflet

Above command create node_modules folder in current directory & download leaflet and add into this.

Then write code html/javascript map code for leaflet map

<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css">
 < script src="node_modules/leaflet/dist/leaflet.js" type="text/javascript"></ script>

< script type="text/javascript">

var map = L.map('map').setView([28.7041, 77.1025 ], 12);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y} png', {
 attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'

L.marker([ 28.7041, 77.1025 ]).addTo(map)
 .bindPopup('Marker Here')

</ script>

Above code successfully show the map centered at new delhi, india. It also have a marker set with info popup.

This is simple case of map with marker and info popup, But some time we need to show some real time data. Like add marker on fly when new location updated. We may have lot of solutions for achieving this. One good solution to use Web Socket Protocol get/update data.

Let first set our Data Sender. I use MQTT Mosquitto broker & php script for achieving this. MQTT protocol work on pubsub model. So our server php script work as publisher while js application would work as subscriber.

But first we would need MQTT Broker. Mosquitto is recommended broker. on ubuntu ( or other deb based systems ) we need following commands to install mosquitto.

$ sudo apt-get install mosquitto mosquitto-clients

Also create a custom mosquitto config file at /etc/mosquitto/conf.d/mosquitto.conf & put following setting into it.

port 1883
protocol mqtt

listener 9001
protocol websockets

autosave_interval 10
autosave_on_changes false

Above setting setup the mqtt ( for publish ) port to 1883, & 9001 port for subscribe. Restart mosuitto service.

$ service mosquitto restart

We may test subscribe/publish with inbuilt commands

# Test Subscriber
$ mosquitto_sub -h localhost -t test

Here we are subscribing on localhost on topic “test”

# Test Publisher
$ mosquitto_pub -h localhost -t test -m "hello world"

Here we are publishing message “hello world” on broker on localhost on topic “test”

Now we setup php script. We use dependancy solver composer for install script dependencies. You can download composer.phar from https://getcomposer.org.

$ mkdir server

$ cd server

$ php composer.phar init

$ php composer.phar require bluerhinos/phpmqtt dev-master

Above command create vendor folder and install package phpmqtt into it. This is php package for mqtt.

Then create php script for publish mqtt data let called it publish.php & put following code into it.

 use Bluerhinos\phpMQTT;
 $server = "localhost"; // change if necessary
 $port = 1883; // change if necessary
 $username = ""; // set your username
 $password = ""; // set your password
 $client_id = "mqtt-publisher"; // make sure this is unique for connecting to sever - you could use uniqid()

$coords = [
 [ 28.6442033, 77.1118256, 'Location 1' ],
 [ 28.5501396, 77.1882317, 'Location 2' ],
 [ 28.6359866, 77.2608032, 'Location 3' ],
 [ 28.6805603, 77.1991786, 'Location 4' ]
 $mqtt = new phpMQTT($server, $port, $client_id);
 if ($mqtt->connect(true, NULL, $username, $password)) {
    for($i=0;$i<count($coords);$i++) {
       $mqtt->publish("map/coordinates", json_encode($coords[$i]), 0);
 } else {
    echo "Time out!\n";

Above script connect to mqtt broker and then some latitude/longtitude after every 5 seconds. Real applications can build their logic for publish data on actual moment.

Now we make changes in our client script to subscribe mqtt, but first install mqtt packge for javascript.

$ cd client

$ yarn add paho-mqtt

Now time to change client script.

<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css">http://node_modules/leaflet/dist/leaflet.js
< script src="node_modules/paho-mqtt/paho-mqtt-min.js" type="text/javascript">< /script>

< script type="text/javascript">

var map = L.map('map').setView([28.7041, 77.1025 ], 12);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
 attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'

document.addEventListener('DOMContentLoaded', function() {
}, false);

function mqtt_init() {
    // Create a client instance
    client = new Paho.MQTT.Client('localhost', 9001, "mqtt-spublisher");

   // set callback handlers
   client.onConnectionLost = onConnectionLost;
   client.onMessageArrived = onMessageArrived;

   // connect the client

   // called when the client connects
   function onConnect() {
    // Once a connection has been made, make a subscription and send a message.

   // called when the client loses its connection
   function onConnectionLost(responseObject) {
       if (responseObject.errorCode !== 0) {

    // called when a message arrives
    function onMessageArrived(message) {
       console.log("onMessageArrived:" + message.payloadString);
       msg = JSON.parse(message.payloadString);
       L.marker([msg[0], msg[1] ]).addTo(map)


< /script>


When we publish our serve script, We see marker coming after duration (5 seconds ), which can become effective real time solution for maps.

Full code can be found at https://github.com/kuldeep-k/leaflet-mqtt