Karten gemeinsam in Echtzeit mit Firebase bearbeiten

Übersicht

In dieser Anleitung erfahren Sie, wie Sie mit der Anwendungsplattform Firebase eine interaktive Karte erstellen können. Klicken Sie unten auf der Karte auf verschiedene Orte, um eine Heatmap zu erstellen.

Der folgende Abschnitt enthält den gesamten Code, den Sie zum Erstellen der Karte in dieser Anleitung benötigen.

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

Selbst ausprobieren

Sie können mit diesem Code in JSFiddle experimentieren. Klicken Sie dazu oben rechts im Codefenster auf das Symbol <>.

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

Erste Schritte

Mit dem Code in dieser Anleitung können Sie Ihre eigene Version der Firebase-Karte entwickeln. Dazu erstellen Sie zuerst eine neue Datei in einem Texteditor und speichern sie als index.html.

In den folgenden Abschnitten wird der Code beschrieben, den Sie in diese Datei einfügen können.

Basiskarte erstellen

In diesem Abschnitt wird der Code zum Erstellen einer Basiskarte beschrieben. Eventuell sind Sie beim Erstellen Ihrer ersten Karten mit der Maps JavaScript API ähnlich vorgegangen.

Kopieren Sie den Code unten in Ihre index.html-Datei. Mit dem Code wird die Maps JavaScript API geladen und die Karte im Vollbildmodus angezeigt. Außerdem wird damit die Visualization-Bibliothek geladen, die Sie weiter unten benötigen, um eine Heatmap zu erstellen.

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

Klicken Sie im Codebeispiel auf YOUR_API_KEY oder folgen Sie der Anleitung, um einen API-Schlüssel abzurufen. Ersetzen Sie YOUR_API_KEY durch den API-Schlüssel Ihrer Anwendung.

In den folgenden Abschnitten wird der JavaScript-Code beschrieben, mit dem die Firebase-Karte erstellt wird. Sie können den Code kopieren, ihn in einer firebasemap.js-Datei speichern und wie unten beschrieben zwischen den Skript-Tags darauf verweisen.

<script>firebasemap.js</script>

Alternativ können Sie den Code auch direkt zwischen den Skript-Tags einfügen, wie im vollständigen Beispielcode am Anfang dieser Anleitung.

Fügen Sie den Code unten in die Datei firebasemap.js oder zwischen den leeren Skript-Tags Ihrer index.html-Datei ein. Dadurch wird eine Funktion erstellt, die das Map-Objekt initialisiert, und das Programm gestartet.

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

Damit die anklickbare Heatmap einfacher zu verwenden ist, werden für den Code oben Kartenstile verwendet, mit denen POIs und Haltestellen deaktiviert werden, für die beim Anklicken ein Infofenster eingeblendet wird. Außerdem wird das Zoomen beim Doppelklicken deaktiviert, um versehentliches Zoomen zu verhindern. Weitere Informationen zum Gestalten von Karteninhalten

Wenn die API vollständig geladen wurde, führt der Callback-Parameter im folgenden Skript-Tag die Funktion initMap() in der HTML-Datei aus.

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

Fügen Sie den folgenden Code ein, um das Textsteuerelement oben auf der Karte zu erstellen.

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

Fügen Sie den folgenden Code nach var map in die Funktion initMap ein, um das Textsteuerfeld zu laden.

// 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);
Jetzt ausprobieren

Öffnen Sie die Datei index.html in einem Webbrowser, um die Google-Karte zu sehen, die mit dem Code erstellt wird.

Firebase einrichten

Damit die Anwendung gemeinsam bearbeitet werden kann, müssen Sie die Klicks in einer externen Datenbank speichern, auf die alle Nutzer zugreifen können. Hier bietet sich die Firebase Realtime Database an, für die keinerlei SQL-Kenntnisse erforderlich sind.

Registrieren Sie sich zuerst kostenlos bei Firebase. Wenn Sie neu bei Firebase sind, wird eine neue App mit dem Namen „My First App“ angezeigt. Falls Sie eine neue App erstellen, können Sie ihr einen neuen Namen und eine benutzerdefinierte Firebase-URL zuweisen, die auf firebaseIO.com endet, z. B. „Luises Firebase-Karte“ mit der URL https://janes-firebase-map.firebaseIO.com. Über diese URL können Sie die Datenbank mit Ihrer JavaScript-Anwendung verknüpfen.

Fügen Sie die Zeile unten nach den <head>-Tags der HTML-Datei ein, um die Firebase-Bibliothek zu importieren.

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

Fügen Sie die folgende Zeile in die JavaScript-Datei ein:

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

Klickdaten in Firebase speichern

In diesem Abschnitt wird der Code beschrieben, mit dem in Firebase Daten zu Mausklicks auf der Karte gespeichert werden.

Mit dem folgenden Code wird für jeden Mausklick auf der Karte ein globales Datenobjekt erstellt, dessen Informationen in Firebase gespeichert werden. In diesem Objekt werden Daten wie der „latLng“-Wert, der Zeitstempel des Klicks und die eindeutige ID des Browsers erfasst, in dem der Klick erfolgt ist.

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

Mit dem folgenden Code wird für jeden Klick eine eindeutige Sitzungs-ID erfasst. Dadurch lässt sich die Anzahl der Kartenzugriffe steuern, um die Firebase-Sicherheitsregeln einzuhalten.

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

Der folgende Codeabschnitt erfasst Klicks auf der Karte und fügt der Firebase-Datenbank ein untergeordnetes Objekt hinzu. Die Funktion snapshot.val() ruft dann die Datenwerte des Eintrags ab und erstellt ein neues „LatLng“-Objekt.

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

Mit dem folgenden Code wird Firebase für folgende Zwecke konfiguriert:

  • Klicks auf der Karte beobachten. Bei einem Klick erfasst die Anwendung den Zeitstempel und fügt der Firebase-Datenbank ein untergeordnetes Objekt hinzu.
  • Alle Klicks auf die Karte, die älter als 10 Minuten sind, in Echtzeit löschen.
/**
 * 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);
  });
}

Kopieren Sie den gesamten JavaScript-Code in diesem Abschnitt in Ihre firebasemap.js-Datei.

Heatmap erstellen

Im nächsten Schritt soll eine Heatmap angezeigt werden, die die relative Anzahl der Klicks an verschiedenen Stellen der Karte veranschaulicht. Weitere Informationen finden Sie im Leitfaden zu Heatmaps.

Fügen Sie den folgenden Code in die Funktion initMap() ein, um eine Heatmap zu erstellen.

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

Der folgende Code löst die Funktionen initFirebase, addToFirebase und getTimestamp aus.

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

Wenn Sie auf die Heatmap klicken, werden noch keine Punkte erstellt. Dazu müssen Sie zuerst einen Listener auf der Karte einrichten.

Punkte auf der Heatmap erstellen

Mit dem folgenden Code wird ein Listener innerhalb der Funktion initMap() hinzugefügt, und zwar nach dem Code, mit dem die Karte erstellt wird. Mit diesem Code werden die Daten jedes Klicks erfasst, der Ort des Klicks in der Firebase-Datenbank gespeichert und die Punkte auf der Heatmap angezeigt.

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

Klicken Sie auf Orte auf der Karte, um Punkte auf der Heatmap zu erstellen.

Sie haben eine voll funktionsfähige Echtzeitanwendung mit Firebase und der Maps JavaScript API erstellt.

Wenn Sie auf die Heatmap klicken, sollten der Breiten- und der Längengrad des Klicks jetzt in Ihrer Firebase-Datenbank angezeigt werden. Um dies zu prüfen, melden Sie sich in Ihrem Firebase-Konto an und öffnen Sie den Tab „Daten“ für Ihre Anwendung. Wenn nun eine andere Person auf Ihre Karte klickt, können sowohl Sie als auch diese Person Punkte auf der Karte sehen. Die Position der Klicks bleibt auch dann sichtbar, wenn der Nutzer die Seite schließt. Wenn Sie die Funktionen für die Zusammenarbeit in Echtzeit testen möchten, öffnen Sie die Seite in zwei separaten Fenstern. Die Markierungen sollten in beiden in Echtzeit angezeigt werden.

Weitere Informationen

Firebase ist eine Anwendungsplattform, die Daten im JSON-Format speichert und in Echtzeit mit allen verbundenen Clients synchronisiert. Sie ist auch dann verfügbar, wenn Ihre App offline geschaltet ist. In dieser Anleitung wird die Echtzeitdatenbank von Firebase verwendet.