Search code examples
javascriptfirebasefirebase-realtime-databasegeofire

GoogleMap with Firebase Realtime Database - Javascript


How can I show lat, lng data from realtime database on google maps ?

My database structure :

/driversAvailable /A85edr0ers0A89rxartas7c5d1(user's id) /g: 787fe78fe
                                                          l:
                                                            0:45.789454
                                                            1:98.44578

My Code :

function initMap(latitude, longitude) {
   var map;
   var database = firebase.database();
   database.ref("driversAvailable//").once('value', function(snapshot) {
     if (snapshot.exists()) {
       snapshot.forEach(function(data) {
         var latitude = l[0].val();
         var longitude = l[1].val();

       });
     }
   });
   map = new google.maps.Map(document.getElementById('map'), {
     center: {
       lat: 41.04,
       lng: 29.0778390
     },
     zoom: 12,
     position: {
       lat: parseFloat(latitude),
       lng: parseFloat(longitude)
     }

   });
 }

Error:

Uncaught ReferenceError: l is not defined

Solution

  • You're not getting the data from the snapshot yet, so your l is undefined. If you get the value from the snapshot first, you can then find l from there:

       snapshot.forEach(function(data) {
         var latitude = data.val().l[0];
         var longitude = data.val().l[1];
       })
    

    If you have a problem like this, it helps to console.log the value of your snapshot to see what's in it:

       snapshot.forEach(function(data) {
         console.log(data.val());
       })