How To Display Multiple Markers Coordinates Stored In Firebase Database On Google Maps

好久不见. 提交于 2019-12-02 07:49:05

Related question:

I only get one result from that database:

c20ej76jhb
45.546058,-122.813203

Using this code (uses on rather than once) with a reference to a database I created with multiple locations (and a different format of data):

var locationsRef = firebase.database().ref("locations");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var marker = new google.maps.Marker({
  position: {
    lat: data.lat,
    lng: data.lng
  },
  map: map
});
bounds.extend(marker.getPosition());
marker.addListener('click', (function(data) {
  return function(e) {
    infowindow.setContent(data.name + "<br>" + this.getPosition().toUrlValue(6) + "<br>" + data.message);
    infowindow.open(map, this);
  }
}(data)));
map.fitBounds(bounds);

});

proof of concept fiddle

from your database:

from mine (with multiple locations and the modified code above):

code snippet:

function initialize() {
  var infowindow = new google.maps.InfoWindow();
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyC8HcClvIT_FlG8ZwCji4LG-qNx8D9VCrs",
    authDomain: "geocodeziptest.firebaseapp.com",
    databaseURL: "https://geocodeziptest.firebaseio.com",
    projectId: "geocodeziptest",
    storageBucket: "geocodeziptest.appspot.com",
    messagingSenderId: "1096545848604"
  };
  firebase.initializeApp(config);
  //Create a node at firebase location to add locations as child keys
  var locationsRef = firebase.database().ref("locations");
  var bounds = new google.maps.LatLngBounds();
  locationsRef.on('child_added', function(snapshot) {
    var data = snapshot.val();
    console.log(data);
    var marker = new google.maps.Marker({
      position: {
        lat: data.lat,
        lng: data.lng
      },
      map: map
    });
    bounds.extend(marker.getPosition());
    marker.addListener('click', (function(data) {
      return function(e) {
        infowindow.setContent(data.name + "<br>" + this.getPosition().toUrlValue(6) + "<br>" + data.message);
        infowindow.open(map, this);
      }
    }(data)));
    map.fitBounds(bounds);
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/geofire/4.1.2/geofire.min.js"></script>
<div id="map_canvas"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!