Search code examples
javascriptgoogle-mapsfirebasegoogle-maps-markersmarker

Add markers from firebase to google map in website


Firebase data structure :

enter image description here

I need to add markers in the google map using these latlang.

My code :

    <script>
    var map;

    function initMap() {

        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 6.930274, lng: 79.861618},
          zoom: 16.5,
          panControl: false,
          gestureHandling: 'greedy',
          disableDefaultUI: true,
          disableDoubleClickZoom: true,
        });

        var dbRef= firebase.database().ref('bins');
        dbRef.on('value', function(snapshot) {
            var snap = snapshot.val();
            var marker = new google.maps.Marker({
              position: {lat: snap.lat, lng: snap.lang},
              map: map
            });
        });
    }
</script>

Nothing happened when this code runs.


Solution

  • This is because you are not accessing the children of bins you have to use forEach to be able to get the values:

     var dbRef= firebase.database().ref('bins');
        dbRef.on('value', function(snapshot) {
        snapshot.forEach(function(child) {
        var childs=child.val();
        var marker = new google.maps.Marker({
              position: {lat: childs.lat, lng: childs.lang},
              map: map
              });
           });
       });