vincent wong
Created January 17, 2019

Friend of Hikers

I will build a hiker tracking device with companion app. The device can be extended to track other moving objects like trucks and cars.

36
Friend of Hikers

Things used in this project

Story

Read more

Code

ReadDeviceToCloudMessages.sonydevice01.js

JavaScript
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

'use strict';

var firebase = require("firebase");

var config = {
  apiKey: "<apiKey>",
  authDomain: "<name>.firebaseapp.com",
  databaseURL: "https://<name>.firebaseio.com",
  storageBucket: "<name>.appspot.com"
  };
firebase.initializeApp(config);

var database = firebase.database();


// Connection string for the IoT Hub service
//
// NOTE:
// For simplicity, this sample sets the connection string in code.
// In a production environment, the recommended approach is to use
// an environment variable to make it available to your application
// or use an x509 certificate.
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security
//
// Using the Azure CLI:
// az iot hub show-connection-string --hub-name {YourIoTHubName} --output table
var connectionString = 'HostName=<iot-hub>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<share-access-key>';

// Using the Node.js SDK for Azure Event hubs:
//   https://github.com/Azure/azure-event-hubs-node
// The sample connects to an IoT hub's Event Hubs-compatible endpoint
// to read messages sent from a device.
var { EventHubClient, EventPosition } = require('@azure/event-hubs');

var printError = function (err) {
  console.log(err.message);
};

function writeData(hiker, latitude, longitude) {
  database.ref(hiker).set({
    lat: latitude,
    lng : longitude
  });
}

// Display the message content - telemetry and properties.
// - Telemetry is sent in the message body
// - The device can add arbitrary application properties to the message
// - IoT Hub adds system properties, such as Device Id, to the message.
var printMessage = function (message) {
  console.log('Telemetry received: ');
  console.log(JSON.stringify(message.body));

  console.log(message.body.Latitude);
  console.log(message.body.Longitude);

  writeData('/me', message.body.Latitude, message.body.Longitude);

  console.log('Application properties (set by device): ')
  console.log(JSON.stringify(message.applicationProperties));
  console.log('System properties (set by IoT Hub): ')
  console.log(JSON.stringify(message.annotations));
  console.log('');
};

// Connect to the partitions on the IoT Hub's Event Hubs-compatible endpoint.
// This example only reads messages sent after this application started.
var ehClient;
EventHubClient.createFromIotHubConnectionString(connectionString).then(function (client) {
  console.log("Successully created the EventHub Client from iothub connection string.");
  ehClient = client;
  return ehClient.getPartitionIds();
}).then(function (ids) {
  console.log("The partition ids are: ", ids);
  return ids.map(function (id) {
    return ehClient.receive(id, printMessage, printError, { eventPosition: EventPosition.fromEnqueuedTime(Date.now()) });
  });
}).catch(printError);

realtime-moving-hikers-google-map-firebase.html

JavaScript
<!DOCTYPE html>
<html>
    <head>
		<title>Friend of Hikers</title>
		<!-- Map Icons -->
		<link rel="stylesheet" type="text/css" href="dist/css/map-icons.css">
		<script type="text/javascript" src="dist/js/map-icons.js"></script>

        <style>
            #map {
                height: 100%;
            }

            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
            }

            #over_map {
                position: absolute;
                top: 10px;
                left: 89%;
                z-index: 99;
                background-color: #ccffcc;
                padding: 10px;
            }
        </style>
    </head>

    <body>
        <div id="map"></div>

        <div id="over_map">
            <div>
                <span>Online Hikers: </span><span id="cars">0</span>
            </div>
        </div>

        <!-- jQuery CDN -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <!-- add firebase -->
		<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
		<script>
		  // Initialize Firebase
		  var config = {
			apiKey: "<apiKey>",
			authDomain: "<name>.firebaseapp.com",
			databaseURL: "https://<name>.firebaseio.com",
			projectId: "<name>",
			storageBucket: "<name>.appspot.com",
			messagingSenderId: "87190323406"
		  };
		  firebase.initializeApp(config);
		</script>


        <script>

            // counter for online cars...
            var cars_count = 0;

            // markers array to store all the markers, so that we could remove marker when any car goes offline and its data will be remove from realtime database...
            var markers = [];
            var map;
            function initMap() { // Google Map Initialization... 
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 18,  //16
                    //center: new google.maps.LatLng(31.52011, 74.368604),
                    center: new google.maps.LatLng(3.100940, 101.445170),
                    mapTypeId: 'terrain'
                });
            }

            // This Function will create a car icon with angle and add/display that marker on the map
            function AddCar(data) {

                var icon = { // car icon
                    path: 'M29.395,0H17.636c-3.117,0-5.643,3.467-5.643,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759   c3.116,0,5.644-2.527,5.644-5.644V6.584C35.037,3.467,32.511,0,29.395,0z M34.05,14.188v11.665l-2.729,0.351v-4.806L34.05,14.188z    M32.618,10.773c-1.016,3.9-2.219,8.51-2.219,8.51H16.631l-2.222-8.51C14.41,10.773,23.293,7.755,32.618,10.773z M15.741,21.713   v4.492l-2.73-0.349V14.502L15.741,21.713z M13.011,37.938V27.579l2.73,0.343v8.196L13.011,37.938z M14.568,40.882l2.218-3.336   h13.771l2.219,3.336H14.568z M31.321,35.805v-7.872l2.729-0.355v10.048L31.321,35.805',
                    scale: 0.4,
                    fillColor: "#427af4", //<-- Car Color, you can change it 
                    fillOpacity: 1,
                    strokeWeight: 1,
                    anchor: new google.maps.Point(0, 5),
                    rotation: data.val().angle //<-- Car angle
                };

                var uluru = { lat: data.val().lat, lng: data.val().lng };

				/*
                var marker = new google.maps.Marker({
                    position: uluru,
                    icon: icon,
                    map: map
                });
				*/
	
				/* map icon */
				var marker = new mapIcons.Marker({
					map: map,
					position: uluru,
					icon: {
						path: mapIcons.shapes.MAP_PIN,
						fillColor: '#00CCBB',
						fillOpacity: 1,
						strokeColor: '',
						strokeWeight: 0
					},
					map_icon_label: '<span class="map-icon map-icon-point-of-interest"></span>'
				});
				
				
                markers[data.key] = marker; // add marker in the markers array...
                document.getElementById("cars").innerHTML = cars_count;
            }

            // get firebase database reference...
            var cars_Ref = firebase.database().ref('/');

            // this event will be triggered when a new object will be added in the database...
            cars_Ref.on('child_added', function (data) {
                cars_count++;
                AddCar(data);
            });

            // this event will be triggered on location change of any car...
            cars_Ref.on('child_changed', function (data) {
                markers[data.key].setMap(null);
                AddCar(data);
            });

            // If any car goes offline then this event will get triggered and we'll remove the marker of that car...  
            cars_Ref.on('child_removed', function (data) {
                markers[data.key].setMap(null);
                cars_count--;
                document.getElementById("cars").innerHTML = cars_count;
            });

        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=<key>&callback=initMap">
        </script>

    </body>
</html>

Credits

vincent wong

vincent wong

80 projects • 203 followers
Thanks to Shehryar Khan.

Comments