Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data from Firebase database and put on map's marker using JavaScript

I'm trying to read my database on Firebase but nothing happens.

My database is very simple, just a node gps and inside it more two nodes: lat and lng Currenty I'm using JavaScript.

All scripts are loaded on header as firebase.js, firebase-database.js and firebase-app.js. My code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>    
    <script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js"></script>
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>       
        function initMap() {

        var firebase = require("firebase/app");
        require("firebase/auth");
        require("firebase/database");
        var config = {
            apiKey: "AIzaxxxxxxxxxxxxxxxxxxxxx",
            authDomain: "xxxxxxxxxxxxxx.firebaseapp.com",
            databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
            projectId: "xxxxxxxxxxxx",
            storageBucket: "xxxxxxxxxxxxxx.appspot.com",
            messagingSenderId: "xxxxxxxxxxxxxxxxx"
        };
        firebase.initializeApp(config);

        var latlng = new google.maps.LatLng(9.682796, 21.473007);
        var myOptions = { zoom: 9, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);            
        var myLat = 0;
        var myLng = 0;
        var myLatLngRef = firebase.database().ref('gps');
        myLatLng.on('lat', function (snapshot) {
            myLat = snapshot.val();
            alert(myLat);
        });
        myLatLng.on('lng', function (snapshot) {
            myLng = snapshot.val();
            alert(myLng);
        });
        var myLatLng = { lat: myLat, lng: myLng };
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: 'gps'
        });
    }               
</script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaxxxxxxxxxxxx&libraries=visualization&callback=initMap">
</script>

like image 971
user1801745 Avatar asked Feb 04 '26 16:02

user1801745


1 Answers

There are a few mistakes that I can see:

  1. The way you're initializing Firebase works for node but not a browser; if you go to the Firebase console, select your project and in the Project Overview (Welcome to Firebase! Get started here.), the third button says Add Firebase to your web app, click it, press copy, and paste it in your html, before your own script. That's all you need.

  2. You don't have the right code to read from the database, it's close but here's an example on how to do it correctly:

firebase.database().ref('gps').on('value', function(snapshot) {
    var val = snapshot.val();
    var myLatLng = {
        lat: val.lat,
        lng: val.lng,
    };
});
  1. The database calls run asynchronously, that means your code will run till completion, create an empty marker, and only when the current processing thread is over will the database callbacks be invoked and run. This means you should wait until the data is retrieved before populating your map.

Here's an example of how to put this all together, with a basic html template I normally use, and your code intertwined:

<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<style>
    #map {
        height: 100%;
    }
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
</style>
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
<script>
    // Initialize Firebase
    var config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxxxx.firebaseapp.com",
        databaseURL: "https://xxxxxxxxxxxxxxx.firebaseio.com",
        projectId: "xxxxxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxxxxx.appspot.com",
        messagingSenderId: "xxxxxxxxxxxx"
    };
    firebase.initializeApp(config);
</script>
<div id="map"></div>
<script>
    function initMap() {
        var latlng = new google.maps.LatLng(9.682796, 21.473007);
        var myOptions = { zoom: 9, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);
        firebase.database().ref('gps').on('value', function() {
            var val = snapshot.val();
            var marker = new google.maps.Marker({
                position: {
                    lat: val.lat,
                    lng: val.lng,
                },
                map: map,
                title: 'gps'
            });
        });
    }
</script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaxxxxxxxxxxxx&libraries=visualization&callback=initMap">
</script>
like image 140
Hanuman Avatar answered Feb 07 '26 05:02

Hanuman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!