来自firebase数据库的Google地图上的多个标记 [英] multiple markers on google maps from firebase database

查看:95
本文介绍了来自firebase数据库的Google地图上的多个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-html lang-html prettyprint-override> <!DOCTYPE html>< html> < HEAD> <标题>地理位置< /标题> < meta name =viewportcontent =initial-scale = 1.0,user-scalable = no> < meta charset =utf-8> <风格> / *始终显式设置地图高度以定义包含地图的div *元素的大小。 * / #map {height:100%; } / *可选:使示例页面填满窗口。 * / html,body {身高:100%;保证金:0;填充:0; }< / style> <! - 将其放在HTML头中;现在不要使用异步延迟 - >< 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> <脚本> var config = {apiKey:AIzaSyCWZjRe2CK8Hu2VN35AgZOQ7lQZKcI-UWM,authDomain:carrier-35d7c.firebaseapp.com,databaseURL:https://carrier-35d7c.firebaseio.com,projectId:carrier-35d7c,storageBucket: carrier-35d7c.appspot.com,messagingSenderId:827792028763}; if(!firebase.apps.length){firebase.initializeApp(config); } //在firebase位置创建一个节点,将位置添加为子键var locationsRef = firebase.database()。ref(locations); //在用户Firebase位置下创建一个新的GeoFire密钥var geoFire = new GeoFire(locationsRef.push()); < /脚本> < /头> <身体GT; < div id =map>< / div> <脚本> //注意:此示例要求您在浏览器提示//时同意位置共享。如果您看到错误地理定位服务//失败。,则表示您可能未授权浏览器找到您。 var map,infoWindow; var lat,lng; function initMap(){map = new google.maps.Map(document.getElementById('map'),{center:{lat:-34.397,lng:150.644},zoom:18}); infoWindow = new google.maps.InfoWindow; //尝试HTML5地理位置。 if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position){lat = position.coords.latitude; lng = position.coords.longitude; var pos = {lat:lat,lng:lng}; _setGeoFire() ; var locationsRef = firebase.database()。ref(locations); locationsRef.on('child_added',function(snapshot){var bounds = new google.maps.LatLngBounds(); //声明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);}); infoWindow.setPosition(pos); infoWindow.setContent('Location found。') ; infoWindow.op en(map); map.setCenter(pos); },function(){handleLocationError(true,infoWindow,map.getCenter()); }); } else {//浏览器不支持Geolocation handleLocationError(false,infoWindow,map.getCenter()); function handleLocationError(browserHasGeolocation,infoWindow,pos){infoWindow.setPosition(pos); infoWindow.setContent(browserHasGeolocation?'错误:Geolocation服务失败。':'错误:您的浏览器不支持地理定位。'); infoWindow.open(地图); } function _setGeoFire(){geoFire.set(User,[lat,lng])。then(()=> {console.log(Location added);})。catch(function(error){console .log(错误);});}< / script> < script src =https://maps.googleapis.com/maps/api/js?key=AIzaSyD2nPlSt_nM7PSKD8So8anbUbBYICFWcCA&callback=initMap> < /脚本> < / body>< / html>



我需要一些帮助在Google地图上绘制我的firebase实时数据库中的多个坐标点。我正在使用geofire将用户的当前位置同步到数据库。另一个堆栈溢出用户给了我一些代码使用,我把它放在我的程序中但由于某种原因,它适用于他们,但不适合我。
代码段:



  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}) ; //初始化Firebase var config = {apiKey:AIzaSyCWZjRe2CK8Hu2VN35AgZOQ7lQZKcI-UWM,authDomain:carrier-35d7c.firebaseapp.com,databaseURL:https://carrier-35d7c.firebaseio.com,projectId:carrier-35d7c ,storageBucket:carrier-35d7c.appspot.com,messagingSenderId:827792028763}; firebase.initializeApp(配置); //在firebase位置创建一个节点,将位置添加为子键var locationsRef = firebase.database()。ref(locations); var bounds = new google.maps.LatLngBounds(); locationsRef.on('child_added',function(snapshot){console.log(snapshot)var data = snapshot.val(); console.log(data); var marker = new google.maps.Marker({position:{lat :data.User.l [0],lng:data.User.l [1]},map:map}); bounds.extend(marker.getPosition()); marker.addListener('click',(function(数据){return function(e){infowindow.setContent(this.getPosition()。toUrlValue(6)+< br>+ data.User.g); infowindow.open(map,this);}}( data))); map.fitBounds(bounds);});} google.maps.event.addDomListener(window,load,initialize);  

  html,body,#map_canvas {height:100%;宽度:100%;保证金:0px;填充: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>  


<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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>
    <!-- Place this inside the HTML head; don't use async defer for now -->
<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>

  <script>
        
        var config = {
    apiKey: "AIzaSyCWZjRe2CK8Hu2VN35AgZOQ7lQZKcI-UWM",
    authDomain: "carrier-35d7c.firebaseapp.com",
    databaseURL: "https://carrier-35d7c.firebaseio.com",
    projectId: "carrier-35d7c",
    storageBucket: "carrier-35d7c.appspot.com",
    messagingSenderId: "827792028763"
  };
        if (!firebase.apps.length) {
            firebase.initializeApp(config);
        }
        
        //Create a node at firebase location to add locations as child keys
        var locationsRef = firebase.database().ref("locations");
        
        // Create a new GeoFire key under users Firebase location
        var geoFire = new GeoFire(locationsRef.push());
      </script>


  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      var lat, lng;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 18
        });
        infoWindow = new google.maps.InfoWindow;
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            lat = position.coords.latitude;
            lng = position.coords.longitude;
            var pos = {lat: lat, lng: lng };
                _setGeoFire();
              var locationsRef = firebase.database().ref("locations");
locationsRef.on('child_added', function(snapshot) {
  var bounds = new google.maps.LatLngBounds(); // declaration 
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);
});
          
            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }
      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
      function _setGeoFire(){
    geoFire.set("User", [lat, lng]).then(()=>{
            console.log("Location added");
        }).catch(function(error) {
            console.log(error);
        });
}
    </script>
    <script 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2nPlSt_nM7PSKD8So8anbUbBYICFWcCA&callback=initMap">
    </script>
  </body>
</html>

I need some help plotting multiple coordinate points from my firebase real-time database on a google map. I'm using geofire to sync the user's current location to the database. Another stack overflow user gave me some code to use and I put it in my program but for some reason, It works for them but does not work for me. How To Display Multiple Markers Coordinates Stored In Firebase Database On Google Maps. That's the link to the question I asked a couple weeks ago. If anyone could help me figure out why this is not working, I would really appreciate it

解决方案

You now have multiple positions in your data.

The code works if you change it to read the data format in your database. You have your coordinates in an array named l in the User object.

locationsRef.on('child_added', function(snapshot) {
  var data = snapshot.val();
  var marker = new google.maps.Marker({
    position: {
      lat: data.User.l[0],
      lng: data.User.l[1]
    },
    map: map
  });
  bounds.extend(marker.getPosition());
  marker.addListener('click', (function(data) {
    return function(e) {
      infowindow.setContent(this.getPosition().toUrlValue(6) + "<br>" + data.User.g);
      infowindow.open(map, this);
    }
  }(data)));
  map.fitBounds(bounds);
});

proof of concept fiddle

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: "AIzaSyCWZjRe2CK8Hu2VN35AgZOQ7lQZKcI-UWM",
    authDomain: "carrier-35d7c.firebaseapp.com",
    databaseURL: "https://carrier-35d7c.firebaseio.com",
    projectId: "carrier-35d7c",
    storageBucket: "carrier-35d7c.appspot.com",
    messagingSenderId: "827792028763"
  };
  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) {
    console.log(snapshot)
    var data = snapshot.val();
    console.log(data);
    var marker = new google.maps.Marker({
      position: {
        lat: data.User.l[0],
        lng: data.User.l[1]
      },
      map: map
    });
    bounds.extend(marker.getPosition());
    marker.addListener('click', (function(data) {
      return function(e) {
        infowindow.setContent(this.getPosition().toUrlValue(6) + "<br>" + data.User.g);
        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>

这篇关于来自firebase数据库的Google地图上的多个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆