Firebase ile Ortak Çalışmaya Dayalı Gerçek Zamanlı Haritalama

Genel bakış

Bu eğitim, Firebase uygulama platformunu kullanarak nasıl etkileşimli harita oluşturacağınızı göstermektedir. Isı haritası oluşturmak için aşağıdaki haritada farklı konumları tıklamayı deneyin.

Aşağıdaki bölümde, bu eğiticide harita oluşturmak için ihtiyaç duyduğunuz kodun tamamı görüntülenmektedir.

/**
 * 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>

Kendiniz deneyin

Kod penceresinin sağ üst köşesindeki <> simgesini tıklayarak JSFiddle'da bu kodla deneme yapabilirsiniz.

<!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>

Kullanmaya başlama

Bu eğitimdeki kodu kullanarak kendi Firebase haritası sürümünüzü geliştirebilirsiniz. Bunu yapmaya başlamak için metin düzenleyicide yeni bir dosya oluşturun ve index.html adıyla kaydedin.

Bu dosyaya ekleyebileceğiniz kodu anlamak için aşağıdaki bölümleri okuyun.

Temel harita oluşturma

Bu bölümde, temel bir harita oluşturan kod açıklanmaktadır. Bu, Haritalar JavaScript API'yi kullanmaya başlarken oluşturduğunuz haritalara benzer olabilir.

Aşağıdaki kodu index.html dosyanıza kopyalayın. Bu kod, Maps JavaScript API'yi yükler ve haritayı tam ekran hale getirir. Ayrıca, eğiticinin ilerleyen bölümlerinde bir ısı haritası oluşturmak için ihtiyaç duyacağınız görselleştirme kitaplığını da yükler.

<!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>

Kod örneğinde YOUR_API_KEY öğesini tıklayın veya API anahtarı alma talimatlarını uygulayın. YOUR_API_KEY yerine uygulamanızın API anahtarını yazın.

Aşağıdaki bölümlerde Firebase haritasını oluşturan JavaScript kodu açıklanmaktadır. Kodu kopyalayıp bir firebasemap.js dosyasına kaydedebilir ve komut dosyası etiketleri arasında aşağıdaki gibi referans verebilirsiniz.

<script>firebasemap.js</script>

Alternatif olarak, kodu bu eğiticinin başındaki tam örnek kodda olduğu gibi doğrudan komut dosyası etiketlerinin içine ekleyebilirsiniz.

Aşağıdaki kodu firebasemap.js dosyasına veya index.html dosyanızın boş komut dosyası etiketlerinin arasına ekleyin. Bu, harita nesnesini başlatan bir işlev oluşturarak programı çalıştıran başlangıç noktasıdır.

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
  });
}

Bu tıklanabilir ısı haritasının kullanımını kolaylaştırmak için yukarıdaki kod, önemli yerleri ve toplu taşıma istasyonlarını (tıklandığında bir bilgi penceresi görüntüler) devre dışı bırakmak için harita stilini kullanır. Ayrıca, yanlışlıkla yakınlaştırma yapılmasını önlemek için çift tıkladığınızda yakınlaştırma devre dışı bırakılır. Haritanızın stilini belirleme hakkında daha fazla bilgi edinin.

API tamamen yüklendikten sonra, aşağıdaki komut dosyası etiketinde bulunan geri çağırma parametresi, HTML dosyasındaki initMap() işlevini yürütür.

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

Haritanın üst kısmında metin denetimini oluşturmak için aşağıdaki kodu ekleyin.

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);
}

Metin kontrol kutusunu yüklemek için aşağıdaki kodu initMap işlevinin içine, var map ifadesinden sonra ekleyin.

// 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);
Hemen deneyin

Kodun oluşturduğu Google haritasını görüntülemek için index.html dosyasını bir web tarayıcısında açın.

Firebase'i ayarlama

Bu uygulamayı ortak çalışmaya uygun hale getirmek için tıklamaları tüm kullanıcıların erişebileceği harici bir veritabanında depolamanız gerekir. Firebase Realtime Database bu amaca uygundur ve SQL hakkında bilgi sahibi olmayı gerektirmez.

Öncelikle, ücretsiz olarak Firebase hesabı almak için kaydolun. Firebase'i kullanmaya yeni başladıysanız "İlk Uygulamam" adlı yeni bir uygulama görürsünüz. Yeni bir uygulama oluşturursanız bu uygulamaya yeni bir ad ve firebaseIO.com ile biten özel bir Firebase URL'si verebilirsiniz. Örneğin, uygulamanıza https://janes-firebase-map.firebaseIO.com URL'sini "Jale's Firebase Map" olarak adlandırabilirsiniz. Veritabanını JavaScript uygulamanıza bağlamak için bu URL'yi kullanabilirsiniz.

Firebase kitaplığını içe aktarmak için aşağıdaki satırı HTML dosyanızın <head> etiketlerinden sonra ekleyin.

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

JavaScript dosyanıza aşağıdaki satırı ekleyin:

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

Firebase'de tıklama verilerini depolama

Bu bölümde, verileri Firebase'de depolayan kod, harita üzerindeki fare tıklamaları ile ilgili olarak açıklanmaktadır.

Aşağıdaki kod, haritadaki her fare tıklandığında global bir veri nesnesi oluşturur ve bu nesnenin bilgilerini Firebase'de depolar. Bu nesne, enlLng ve tıklamanın zaman damgası gibi verilerin yanı sıra tıklamayı oluşturan tarayıcının benzersiz kimliğini kaydeder.

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

Aşağıdaki kod, her tıklamaya göre benzersiz bir oturum kimliği kaydeder. Bu kimlik, Firebase güvenlik kurallarına uygun şekilde haritadaki trafik hızını kontrol etmeye yardımcı olur.

/**
* 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.
    }
  });
}

Aşağıdaki kodun bir sonraki bölümü, harita tıklamalarını dinleyerek Firebase veritabanınıza bir "alt" öğe ekler. Bu durumda snapshot.val() işlevi, girişin veri değerlerini alır ve yeni bir LatLng nesnesi oluşturur.

// 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);
  }
);

Aşağıdaki kod Firebase'i şu şekilde ayarlar:

  • Haritadaki tıklamaları takip edin. Bir tıklama gerçekleştiğinde, uygulama bir zaman damgası kaydeder, ardından Firebase veritabanınıza bir "alt" öğe ekler.
  • Harita üzerindeki 10 dakikadan eski tıklamaları gerçek zamanlı olarak silin.
/**
 * 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);
  });
}

Bu bölümdeki tüm JavaScript kodunu firebasemap.js dosyanıza kopyalayın.

Isı haritası oluşturma

Sonraki adım, görüntüleyenlere haritada çeşitli yerlerde yapılan tıklamaların göreceli sayısını grafik olarak sunan bir ısı haritası görüntülemektir. Daha fazla bilgi edinmek için ısı haritaları kılavuzunu okuyun.

Isı haritası oluşturmak için aşağıdaki kodu initMap() işlevinin içine ekleyin.

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

Aşağıdaki kod initFirebase, addToFirebase ve getTimestamp işlevlerini tetikler.

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

Isı haritasını tıkladığınızda henüz nokta oluşturulmadığını görürsünüz. Haritada noktalar oluşturmak için harita işleyici oluşturmanız gerekir.

Isı haritasında nokta oluşturma

Aşağıdaki kod, haritayı oluşturan koddan sonra initMap() içine bir işleyici ekler. Bu kod her tıklamadan elde edilen verileri dinler, tıklamanızın konumunu Firebase veritabanında depolar ve ısı haritanızdaki noktaları görüntüler.

// 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);
});
Hemen deneyin

Isı haritanızda noktalar oluşturmak için haritadaki konumları tıklayın.

Artık Firebase ve Maps JavaScript API'yi kullanan, tamamen işlevsel bir gerçek zamanlı uygulamaya sahipsiniz.

Isı haritasını tıkladığınızda, tıklamanın enlem ve boylamı artık Firebase veritabanınızda görünür. Firebase hesabınıza giriş yapıp uygulamanızın veri sekmesine giderek bu durumu görebilirsiniz. Bu noktada, başka biri haritanızı tıklarsa hem siz hem de söz konusu kişi haritada noktaları görebilirsiniz. Tıklamaların konumu, kullanıcı sayfayı kapattıktan sonra bile aynı kalır. Gerçek zamanlı ortak çalışma işlevini test etmek için sayfayı iki ayrı pencerede açın. İşaretçiler gerçek zamanlı olarak her ikisinde de görünecektir.

Daha fazla bilgi

Firebase, verileri JSON olarak depolayan ve bağlı tüm istemcilerle gerçek zamanlı olarak senkronize eden bir uygulama platformudur. Uygulamanız çevrimdışıyken bile kullanılabilir. Bu eğitim, gerçek zamanlı veritabanını kullanır.