Firebase की मदद से, साथ मिलकर काम करने की रीयल टाइम मैपिंग

खास जानकारी

इस ट्यूटोरियल में, Firebase ऐप्लिकेशन प्लैटफ़ॉर्म का इस्तेमाल करके इंटरैक्टिव मैप बनाने का तरीका बताया गया है. हीटमैप बनाने के लिए, नीचे दिए गए मैप में अलग-अलग जगहों पर क्लिक करके देखें.

नीचे दिया गया सेक्शन वह पूरा कोड दिखाता है जिसकी ज़रूरत आपको इस ट्यूटोरियल में मैप बनाने के लिए होती है.

/**
 * Firebase config block.
 */
var config = {
  apiKey: 'AIzaSyDX-tgWqPmTme8lqlFn2hIsqwxGL6FYPBY',
  authDomain: 'maps-docs-team.firebaseapp.com',
  databaseURL: 'https://maps-docs-team.firebaseio.com',
  projectId: 'maps-docs-team',
  storageBucket: 'maps-docs-team.appspot.com',
  messagingSenderId: '285779793579'
};

firebase.initializeApp(config);

/**
 * Data object to be written to Firebase.
 */
var data = {sender: null, timestamp: null, lat: null, lng: null};

function makeInfoBox(controlDiv, map) {
  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '2px';
  controlUI.style.marginBottom = '22px';
  controlUI.style.marginTop = '10px';
  controlUI.style.textAlign = 'center';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '100%';
  controlText.style.padding = '6px';
  controlText.textContent =
      'The map shows all clicks made in the last 10 minutes.';
  controlUI.appendChild(controlText);
}

      /**
      * Starting point for running the program. Authenticates the user.
      * @param {function()} onAuthSuccess - Called when authentication succeeds.
      */
      function initAuthentication(onAuthSuccess) {
        firebase.auth().signInAnonymously().catch(function(error) {
          console.log(error.code + ', ' + error.message);
        }, {remember: 'sessionOnly'});

        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            data.sender = user.uid;
            onAuthSuccess();
          } else {
            // User is signed out.
          }
        });
      }

      /**
       * Creates a map object with a click listener and a heatmap.
       */
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 0, lng: 0},
          zoom: 3,
          styles: [{
            featureType: 'poi',
            stylers: [{ visibility: 'off' }]  // Turn off POI.
          },
          {
            featureType: 'transit.station',
            stylers: [{ visibility: 'off' }]  // Turn off bus, train stations etc.
          }],
          disableDoubleClickZoom: true,
          streetViewControl: false,
        });

        // Create the DIV to hold the control and call the makeInfoBox() constructor
        // passing in this DIV.
        var infoBoxDiv = document.createElement('div');
        makeInfoBox(infoBoxDiv, map);
        map.controls[google.maps.ControlPosition.TOP_CENTER].push(infoBoxDiv);

        // Listen for clicks and add the location of the click to firebase.
        map.addListener('click', function(e) {
          data.lat = e.latLng.lat();
          data.lng = e.latLng.lng();
          addToFirebase(data);
        });

        // Create a heatmap.
        var heatmap = new google.maps.visualization.HeatmapLayer({
          data: [],
          map: map,
          radius: 16
        });

        initAuthentication(initFirebase.bind(undefined, heatmap));
      }

      /**
       * Set up a Firebase with deletion on clicks older than expiryMs
       * @param {!google.maps.visualization.HeatmapLayer} heatmap The heatmap to
       */
      function initFirebase(heatmap) {

        // 10 minutes before current time.
        var startTime = new Date().getTime() - (60 * 10 * 1000);

        // Reference to the clicks in Firebase.
        var clicks = firebase.database().ref('clicks');

        // Listen for clicks and add them to the heatmap.
        clicks.orderByChild('timestamp').startAt(startTime).on('child_added',
          function(snapshot) {
            // Get that click from firebase.
            var newPosition = snapshot.val();
            var point = new google.maps.LatLng(newPosition.lat, newPosition.lng);
            var elapsedMs = Date.now() - newPosition.timestamp;

            // Add the point to the heatmap.
            heatmap.getData().push(point);

            // Request entries older than expiry time (10 minutes).
            var expiryMs = Math.max(60 * 10 * 1000 - elapsedMs, 0);

            // Set client timeout to remove the point after a certain time.
            window.setTimeout(function() {
              // Delete the old point from the database.
              snapshot.ref.remove();
            }, expiryMs);
          }
        );

        // Remove old data from the heatmap when a point is removed from firebase.
        clicks.on('child_removed', function(snapshot, prevChildKey) {
          var heatmapData = heatmap.getData();
          var i = 0;
          while (snapshot.val().lat != heatmapData.getAt(i).lat()
            || snapshot.val().lng != heatmapData.getAt(i).lng()) {
            i++;
          }
          heatmapData.removeAt(i);
        });
      }

      /**
       * Updates the last_message/ path with the current timestamp.
       * @param {function(Date)} addClick After the last message timestamp has been updated,
       *     this function is called with the current timestamp to add the
       *     click to the firebase.
       */
      function getTimestamp(addClick) {
        // Reference to location for saving the last click time.
        var ref = firebase.database().ref('last_message/' + data.sender);

        ref.onDisconnect().remove();  // Delete reference from firebase on disconnect.

        // Set value to timestamp.
        ref.set(firebase.database.ServerValue.TIMESTAMP, function(err) {
          if (err) {  // Write to last message was unsuccessful.
            console.log(err);
          } else {  // Write to last message was successful.
            ref.once('value', function(snap) {
              addClick(snap.val());  // Add click with same timestamp.
            }, function(err) {
              console.warn(err);
            });
          }
        });
      }

      /**
       * Adds a click to firebase.
       * @param {Object} data The data to be added to firebase.
       *     It contains the lat, lng, sender and timestamp.
       */
      function addToFirebase(data) {
        getTimestamp(function(timestamp) {
          // Add the new timestamp to the record data.
          data.timestamp = timestamp;
          var ref = firebase.database().ref('clicks').push(data, function(err) {
            if (err) {  // Data was not written to firebase.
              console.warn(err);
            }
          });
        });
      }
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=visualization&callback=initMap" defer></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>

खुद आज़माकर देखें

कोड विंडो के ऊपरी दाएं कोने में मौजूद, <> आइकॉन पर क्लिक करके, JSFiddle में इस कोड को इस्तेमाल किया जा सकता है.

<!DOCTYPE html>
<html>
  <head>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-database.js"></script>
    <script>
/**
 * Firebase config block.
 */
var config = {
  apiKey: 'AIzaSyDX-tgWqPmTme8lqlFn2hIsqwxGL6FYPBY',
  authDomain: 'maps-docs-team.firebaseapp.com',
  databaseURL: 'https://maps-docs-team.firebaseio.com',
  projectId: 'maps-docs-team',
  storageBucket: 'maps-docs-team.appspot.com',
  messagingSenderId: '285779793579'
};

firebase.initializeApp(config);

/**
 * Data object to be written to Firebase.
 */
var data = {sender: null, timestamp: null, lat: null, lng: null};

function makeInfoBox(controlDiv, map) {
  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '2px';
  controlUI.style.marginBottom = '22px';
  controlUI.style.marginTop = '10px';
  controlUI.style.textAlign = 'center';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '100%';
  controlText.style.padding = '6px';
  controlText.textContent =
      'The map shows all clicks made in the last 10 minutes.';
  controlUI.appendChild(controlText);
}

      /**
      * Starting point for running the program. Authenticates the user.
      * @param {function()} onAuthSuccess - Called when authentication succeeds.
      */
      function initAuthentication(onAuthSuccess) {
        firebase.auth().signInAnonymously().catch(function(error) {
          console.log(error.code + ', ' + error.message);
        }, {remember: 'sessionOnly'});

        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            data.sender = user.uid;
            onAuthSuccess();
          } else {
            // User is signed out.
          }
        });
      }

      /**
       * Creates a map object with a click listener and a heatmap.
       */
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 0, lng: 0},
          zoom: 3,
          styles: [{
            featureType: 'poi',
            stylers: [{ visibility: 'off' }]  // Turn off POI.
          },
          {
            featureType: 'transit.station',
            stylers: [{ visibility: 'off' }]  // Turn off bus, train stations etc.
          }],
          disableDoubleClickZoom: true,
          streetViewControl: false,
        });

        // Create the DIV to hold the control and call the makeInfoBox() constructor
        // passing in this DIV.
        var infoBoxDiv = document.createElement('div');
        makeInfoBox(infoBoxDiv, map);
        map.controls[google.maps.ControlPosition.TOP_CENTER].push(infoBoxDiv);

        // Listen for clicks and add the location of the click to firebase.
        map.addListener('click', function(e) {
          data.lat = e.latLng.lat();
          data.lng = e.latLng.lng();
          addToFirebase(data);
        });

        // Create a heatmap.
        var heatmap = new google.maps.visualization.HeatmapLayer({
          data: [],
          map: map,
          radius: 16
        });

        initAuthentication(initFirebase.bind(undefined, heatmap));
      }

      /**
       * Set up a Firebase with deletion on clicks older than expiryMs
       * @param {!google.maps.visualization.HeatmapLayer} heatmap The heatmap to
       */
      function initFirebase(heatmap) {

        // 10 minutes before current time.
        var startTime = new Date().getTime() - (60 * 10 * 1000);

        // Reference to the clicks in Firebase.
        var clicks = firebase.database().ref('clicks');

        // Listen for clicks and add them to the heatmap.
        clicks.orderByChild('timestamp').startAt(startTime).on('child_added',
          function(snapshot) {
            // Get that click from firebase.
            var newPosition = snapshot.val();
            var point = new google.maps.LatLng(newPosition.lat, newPosition.lng);
            var elapsedMs = Date.now() - newPosition.timestamp;

            // Add the point to the heatmap.
            heatmap.getData().push(point);

            // Request entries older than expiry time (10 minutes).
            var expiryMs = Math.max(60 * 10 * 1000 - elapsedMs, 0);

            // Set client timeout to remove the point after a certain time.
            window.setTimeout(function() {
              // Delete the old point from the database.
              snapshot.ref.remove();
            }, expiryMs);
          }
        );

        // Remove old data from the heatmap when a point is removed from firebase.
        clicks.on('child_removed', function(snapshot, prevChildKey) {
          var heatmapData = heatmap.getData();
          var i = 0;
          while (snapshot.val().lat != heatmapData.getAt(i).lat()
            || snapshot.val().lng != heatmapData.getAt(i).lng()) {
            i++;
          }
          heatmapData.removeAt(i);
        });
      }

      /**
       * Updates the last_message/ path with the current timestamp.
       * @param {function(Date)} addClick After the last message timestamp has been updated,
       *     this function is called with the current timestamp to add the
       *     click to the firebase.
       */
      function getTimestamp(addClick) {
        // Reference to location for saving the last click time.
        var ref = firebase.database().ref('last_message/' + data.sender);

        ref.onDisconnect().remove();  // Delete reference from firebase on disconnect.

        // Set value to timestamp.
        ref.set(firebase.database.ServerValue.TIMESTAMP, function(err) {
          if (err) {  // Write to last message was unsuccessful.
            console.log(err);
          } else {  // Write to last message was successful.
            ref.once('value', function(snap) {
              addClick(snap.val());  // Add click with same timestamp.
            }, function(err) {
              console.warn(err);
            });
          }
        });
      }

      /**
       * Adds a click to firebase.
       * @param {Object} data The data to be added to firebase.
       *     It contains the lat, lng, sender and timestamp.
       */
      function addToFirebase(data) {
        getTimestamp(function(timestamp) {
          // Add the new timestamp to the record data.
          data.timestamp = timestamp;
          var ref = firebase.database().ref('clicks').push(data, function(err) {
            if (err) {  // Data was not written to firebase.
              console.warn(err);
            }
          });
        });
      }
    </script>
    <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization&callback=initMap">
    </script>
  </body>
</html>

रिपोर्ट का इस्तेमाल करना

इस ट्यूटोरियल में दिए गए कोड का इस्तेमाल करके, Firebase मैप का अपना वर्शन बनाया जा सकता है. ऐसा करने के लिए, टेक्स्ट एडिटर में एक नई फ़ाइल बनाएं और उसे index.html के तौर पर सेव करें.

इस फ़ाइल में जोड़े जा सकने वाले कोड को समझने के लिए, आगे दिए गए सेक्शन पढ़ें.

बुनियादी मैप बनाना

यह सेक्शन उस कोड के बारे में बताता है जिससे बुनियादी मैप सेट अप किया जाता है. यह आपके मैप बनाने के तरीके जैसा ही हो सकता है, जैसे ही Maps JavaScript API का इस्तेमाल शुरू करना.

नीचे दिए गए कोड को अपनी index.html फ़ाइल में कॉपी करें. यह कोड, Maps JavaScript API को लोड करता है और मैप को फ़ुलस्क्रीन बना देता है. यह विज़ुअलाइज़ेशन लाइब्रेरी भी लोड करता है, जिसकी ज़रूरत आपको बाद में ट्यूटोरियल में हीटमैप बनाने के लिए पड़ेगी.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY
        &libraries=visualization&callback=initMap">
    </script>

    <script>
      // The JavaScript code that creates the Firebase map goes here.
    </script>

  </body>
</html>

कोड सैंपल में YOUR_API_KEY पर क्लिक करें या निर्देशों का पालन करके एपीआई पासकोड पाएं. YOUR_API_KEY को अपने ऐप्लिकेशन की एपीआई पासकोड से बदलें.

बाद के सेक्शन, Firebase मैप बनाने वाले JavaScript कोड के बारे में जानकारी देते हैं. कोड को कॉपी करके, firebasemap.js फ़ाइल में सेव किया जा सकता है. साथ ही, इसे नीचे बताए गए स्क्रिप्ट टैग के बीच रेफ़रंस के तौर पर रखा जा सकता है.

<script>firebasemap.js</script>

इसके अलावा, आपके पास सीधे स्क्रिप्ट टैग में कोड डालने का विकल्प भी होता है, जैसा कि इस ट्यूटोरियल की शुरुआत में पूरा सैंपल कोड दिखाया गया है.

नीचे दिए गए कोड को firebasemap.js फ़ाइल में या अपनी index.html फ़ाइल के खाली स्क्रिप्ट टैग के बीच में जोड़ें. मैप ऑब्जेक्ट को शुरू करने वाला फ़ंक्शन बनाकर, प्रोग्राम को इसी जगह से चलाया जाता है.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 0, lng: 0},
    zoom: 3,
    styles: [{
      featureType: 'poi',
      stylers: [{ visibility: 'off' }]  // Turn off points of interest.
    }, {
      featureType: 'transit.station',
      stylers: [{ visibility: 'off' }]  // Turn off bus stations, train stations, etc.
    }],
    disableDoubleClickZoom: true,
    streetViewControl: false
  });
}

क्लिक किए जा सकने वाले हीटमैप को इस्तेमाल में आसान बनाने के लिए, ऊपर दिया गया कोड मैप स्टाइल का इस्तेमाल करता है. इससे लोकप्रिय जगहों और बस, मेट्रो वगैरह के स्टेशन बंद किए जाते हैं. इन स्टेशन पर क्लिक करने पर जानकारी विंडो दिखती है. इससे गलती से ज़ूम करने की सुविधा को रोकने के लिए, डबल क्लिक पर ज़ूम करने की सुविधा भी बंद हो जाती है. अपने मैप को स्टाइल देने के बारे में ज़्यादा पढ़ें.

एपीआई के पूरी तरह लोड होने के बाद, नीचे दिए गए स्क्रिप्ट टैग में मौजूद कॉलबैक पैरामीटर, एचटीएमएल फ़ाइल में initMap() फ़ंक्शन को एक्ज़ीक्यूट करता है.

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

मैप पर सबसे ऊपर टेक्स्ट कंट्रोल बनाने के लिए, नीचे दिया गया कोड जोड़ें.

function makeInfoBox(controlDiv, map) {
  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '2px';
  controlUI.style.marginBottom = '22px';
  controlUI.style.marginTop = '10px';
  controlUI.style.textAlign = 'center';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('div');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '100%';
  controlText.style.padding = '6px';
  controlText.innerText = 'The map shows all clicks made in the last 10 minutes.';
  controlUI.appendChild(controlText);
}

टेक्स्ट कंट्रोल बॉक्स को लोड करने के लिए, var map के बाद initMap फ़ंक्शन में नीचे दिया गया कोड जोड़ें.

// Create the DIV to hold the control and call the makeInfoBox() constructor
// passing in this DIV.
var infoBoxDiv = document.createElement('div');
var infoBox = new makeInfoBox(infoBoxDiv, map);
infoBoxDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(infoBoxDiv);
इसे अभी आज़माएं

कोड के बनाए गए Google मैप को देखने के लिए, index.html फ़ाइल को वेब ब्राउज़र में खोलें.

Firebase सेट अप करना

इस ऐप्लिकेशन को साथ मिलकर काम करने लायक बनाने के लिए, आपको क्लिक को किसी बाहरी डेटाबेस में सेव करना होगा, ताकि सभी उपयोगकर्ता ऐक्सेस कर सकें. Firebase रीयल टाइम डेटाबेस का इस्तेमाल इसी मकसद से किया जा सकता है. इसके लिए, एसक्यूएल की जानकारी की ज़रूरत नहीं होती.

सबसे पहले, बिना किसी शुल्क के Firebase खाते के लिए साइन अप करें. अगर Firebase आपके लिए नया है, तो आपको "मेरा पहला ऐप्लिकेशन" नाम से एक नया ऐप्लिकेशन दिखेगा. अगर कोई नया ऐप्लिकेशन बनाया जाता है, तो उसे एक नया नाम दिया जा सकता है. साथ ही, पसंद के मुताबिक Firebase यूआरएल भी दिया जा सकता है, जिसके आखिरी अंक firebaseIO.com होते हैं. उदाहरण के लिए, अपने ऐप्लिकेशन का नाम "जेन का फ़ायरबेस मैप" रखा जा सकता है. साथ ही, https://janes-firebase-map.firebaseIO.com यूआरएल भी दिया जा सकता है. इस यूआरएल का इस्तेमाल, डेटाबेस को अपने JavaScript ऐप्लिकेशन से लिंक करने के लिए किया जा सकता है.

Firebase लाइब्रेरी को इंपोर्ट करने के लिए, अपनी एचटीएमएल फ़ाइल के <head> टैग के बाद, नीचे दी गई लाइन जोड़ें.

<script src="www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>

अपनी JavaScript फ़ाइल में नीचे दी गई लाइन जोड़ें:

var firebase = new Firebase("<Your Firebase URL here>");

Firebase में क्लिक डेटा को स्टोर करना

इस सेक्शन में उस कोड के बारे में बताया गया है जो Firebase में डेटा स्टोर करता है. यह डेटा, मैप पर होने वाले माउस से होने वाले क्लिक से जुड़ा होता है.

मैप पर किए गए हर माउस-क्लिक के लिए, नीचे दिया गया कोड एक ग्लोबल डेटा ऑब्जेक्ट बनाता है और उसकी जानकारी को Firebase में सेव करता है. यह ऑब्जेक्ट, अपने latLng और क्लिक का टाइम-स्टैंप जैसा डेटा रिकॉर्ड करता है. साथ ही, क्लिक बनाने वाले ब्राउज़र का यूनीक आईडी भी रिकॉर्ड करता है.

/**
 * Data object to be written to Firebase.
 */
var data = {
  sender: null,
  timestamp: null,
  lat: null,
  lng: null
};

नीचे दिया गया कोड, हर क्लिक के लिए एक यूनीक सेशन आईडी रिकॉर्ड करता है. इससे, Firebase के सुरक्षा नियमों के तहत, मैप पर ट्रैफ़िक की दर को कंट्रोल करने में मदद मिलती है.

/**
* Starting point for running the program. Authenticates the user.
* @param {function()} onAuthSuccess - Called when authentication succeeds.
*/
function initAuthentication(onAuthSuccess) {
  firebase.auth().signInAnonymously().catch(function(error) {
      console.log(error.code + ", " + error.message);
  }, {remember: 'sessionOnly'});

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      data.sender = user.uid;
      onAuthSuccess();
    } else {
      // User is signed out.
    }
  });
}

नीचे दिए गए कोड का अगला सेक्शन, मैप पर होने वाले क्लिक का ध्यान रखता है. इससे आपके Firebase डेटाबेस में 'चाइल्ड' जानकारी जुड़ जाती है. ऐसा होने पर, snapshot.val() फ़ंक्शन को एंट्री की डेटा वैल्यू मिलती हैं और वह एक नया LatLng ऑब्जेक्ट बनाता है.

// Listen for clicks and add them to the heatmap.
clicks.orderByChild('timestamp').startAt(startTime).on('child_added',
  function(snapshot) {
    var newPosition = snapshot.val();
    var point = new google.maps.LatLng(newPosition.lat, newPosition.lng);
    heatmap.getData().push(point);
  }
);

नीचे दिया गया कोड, Firebase को इसके लिए सेट अप करता है:

  • मैप पर क्लिक के लिए सुनें. जब कोई क्लिक होता है, तो ऐप्लिकेशन एक टाइमस्टैंप रिकॉर्ड करता है. इसके बाद, आपके Firebase डेटाबेस में 'चाइल्ड' जोड़ देता है.
  • रीयल टाइम में, मैप पर मौजूद 10 मिनट से ज़्यादा पुराने क्लिक मिटाएं.
/**
 * Set up a Firebase with deletion on clicks older than expirySeconds
 * @param {!google.maps.visualization.HeatmapLayer} heatmap The heatmap to
 * which points are added from Firebase.
 */
function initFirebase(heatmap) {

  // 10 minutes before current time.
  var startTime = new Date().getTime() - (60 * 10 * 1000);

  // Reference to the clicks in Firebase.
  var clicks = firebase.database().ref('clicks');

  // Listen for clicks and add them to the heatmap.
  clicks.orderByChild('timestamp').startAt(startTime).on('child_added',
    function(snapshot) {
      // Get that click from firebase.
      var newPosition = snapshot.val();
      var point = new google.maps.LatLng(newPosition.lat, newPosition.lng);
      var elapsedMs = Date.now() - newPosition.timestamp;

      // Add the point to the heatmap.
      heatmap.getData().push(point);

      // Request entries older than expiry time (10 minutes).
      var expiryMs = Math.max(60 * 10 * 1000 - elapsed, 0);
      // Set client timeout to remove the point after a certain time.
      window.setTimeout(function() {
        // Delete the old point from the database.
        snapshot.ref.remove();
      }, expiryMs);
    }
  );

  // Remove old data from the heatmap when a point is removed from firebase.
  clicks.on('child_removed', function(snapshot, prevChildKey) {
    var heatmapData = heatmap.getData();
    var i = 0;
    while (snapshot.val().lat != heatmapData.getAt(i).lat()
      || snapshot.val().lng != heatmapData.getAt(i).lng()) {
      i++;
    }
    heatmapData.removeAt(i);
  });
}

इस सेक्शन के सभी JavaScript कोड को अपनी firebasemap.js फ़ाइल में कॉपी करें.

हीटमैप बनाना

अगला कदम, हीटमैप दिखाना है. इससे दर्शकों को मैप में अलग-अलग जगहों पर मिले क्लिक की संख्या के बारे में ग्राफ़िकल इंप्रेशन मिलेगा. ज़्यादा जानने के लिए, हीटमैप की गाइड पढ़ें.

हीटमैप बनाने के लिए, initMap() फ़ंक्शन में नीचे दिया गया कोड जोड़ें.

// Create a heatmap.
var heatmap = new google.maps.visualization.HeatmapLayer({
  data: [],
  map: map,
  radius: 16
});

नीचे दिया गया कोड, initFirebase, addToFirebase, और getTimestamp फ़ंक्शन को ट्रिगर करता है.

initAuthentication(initFirebase.bind(undefined, heatmap));

ध्यान दें कि अगर हीटमैप पर क्लिक किया जाता है, तो वह अभी पॉइंट नहीं बनाता. मैप पर पॉइंट बनाने के लिए, आपको मैप लिसनर सेट अप करना होगा.

हीटमैप पर पॉइंट बनाना

नीचे दिया गया कोड, मैप बनाने वाले कोड के बाद, initMap() में एक लिसनर जोड़ता है. यह कोड हर क्लिक का डेटा सुनता है, Firebase के डेटाबेस में आपके क्लिक की जगह की जानकारी सेव करता है, और आपके हीटमैप पर पॉइंट दिखाता है.

// Listen for clicks and add the location of the click to firebase.
map.addListener('click', function(e) {
  data.lat = e.latLng.lat();
  data.lng = e.latLng.lng();
  addToFirebase(data);
});
इसे अभी आज़माएं

अपने हीटमैप पर पॉइंट बनाने के लिए, मैप पर जगहों पर क्लिक करें.

अब आपके पास Firebase और Maps JavaScript API का इस्तेमाल करने वाला, पूरी तरह से काम करने वाला रीयल-टाइम ऐप्लिकेशन है.

हीटमैप पर क्लिक करने पर, क्लिक के अक्षांश और देशांतर अब आपके Firebase डेटाबेस में दिखने चाहिए. अपने Firebase खाते में लॉग इन करके और अपने ऐप्लिकेशन के डेटा टैब पर जाकर, इसे देखा जा सकता है. इस समय, अगर कोई और आपके मैप पर क्लिक करता है, तो आप और वह व्यक्ति, मैप पर पॉइंट देख सकता है. क्लिक की जगह, उपयोगकर्ता के पेज बंद करने के बाद भी बनी रहती है. रीयल टाइम में, साथ मिलकर काम करने की सुविधा की जांच करने के लिए, पेज को दो अलग-अलग विंडो में खोलें. मार्कर, रीयल टाइम में दोनों पर दिखने चाहिए.

ज़्यादा जानें

Firebase एक ऐप्लिकेशन प्लैटफ़ॉर्म है, जो डेटा को JSON के तौर पर सेव करता है और कनेक्ट किए गए सभी क्लाइंट से रीयल टाइम में सिंक करता है. यह आपके ऐप्लिकेशन के ऑफ़लाइन होने पर भी उपलब्ध होती है. यह ट्यूटोरियल, अपने रीयल टाइम डेटाबेस का इस्तेमाल करता है.