从Firebase获取数据并将其存储在javascript变量中

时间:2018-12-25 14:57:10

标签: javascript firebase-realtime-database

我正在尝试从Firebase检索位置数据,然后将其存储在javascript变量中,以便我可以使用这些坐标来指向用户在Google地图上的位置。 我正在使用以下javascript和HTML代码

<html>
<head>
<meta charset="utf-8"/>
<script src="https://www.gstatic.com/firebasejs/5.5.9/firebase.js"></script>    
<title>Firebase Project</title>
</head>

<body>
<pre id="latitude"></pre>
<pre id="longitude"></pre>
<pre id="mock"></pre>

<script>
var preObject = document.getElementById('latitude');
var preObject1 = document.getElementById('longitude');
var preObject2 = document.getElementById('mock');  
var latitude = firebase.database().ref().child('location/latitude');
var longitude = firebase.database().ref().child('location/longitude');
var mock = firebase.database().ref().child('location/fromMockProvider');

latitude.on('value', snap => {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});

longitude.on('value', snap => {
preObject1.innerText = JSON.stringify(snap.val(), null, 3);
});

mock.on('value', snap => {
preObject2.innerText = JSON.stringify(snap.val(), null, 3);  
});
</script>
</body>
</html>

我能够在网络浏览器上获取并显示位置数据,但无法将这些数据存储到javascript变量中。我正在使用

var x = document.getElementById("latitude").value;
document.write(x);

,但浏览器显示“未定义”。 还有其他方法可以将这些数据存储在javascript变量中。

1 个答案:

答案 0 :(得分:0)

最后,我能够完成我想做的事情,这是我的代码。

   <!DOCTYPE html>
   <html>
   <head>

    <style>
        #map {
            height: 100%;
        }

        HTML, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #over_map {
            position: absolute;
            top: 10px;
            left: 85%;
            z-index: 99;
            background-color: #ccffcc;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <div id="over_map">
        <div>
            <span>Online Users: </span><span id="users">0</span><br>
            <span>Mock Location: </span><span id="mock">.</span>                
        </div>
    </div>

    <script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>

    <script>
        var config = {
           your firebase api key etc.
        };
        firebase.initializeApp(config);
    </script>

    <script>

        // counter for online users
        var users_count = 0;

        // markers array to store all the markers, so that we could remove marker when any user goes offline and its data will be remove from realtime database
        var markers = [];
        var map;
        function initMap() { // Google Map Initialization
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 5,
                center: new google.maps.LatLng(22.4051656, 78.4614163),
                mapTypeId: 'terrain'
            });
        }

        // This Function will create a car icon and add/display that as a marker on the map
        function AddUser(data) {

            var icon = { // car icon
                path: 'M29.395,0H17.636c-3.117,0-5.643,3.467-5.643,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759   c3.116,0,5.644-2.527,5.644-5.644V6.584C35.037,3.467,32.511,0,29.395,0z M34.05,14.188v11.665l-2.729,0.351v-4.806L34.05,14.188z    M32.618,10.773c-1.016,3.9-2.219,8.51-2.219,8.51H16.631l-2.222-8.51C14.41,10.773,23.293,7.755,32.618,10.773z M15.741,21.713   v4.492l-2.73-0.349V14.502L15.741,21.713z M13.011,37.938V27.579l2.73,0.343v8.196L13.011,37.938z M14.568,40.882l2.218-3.336   h13.771l2.219,3.336H14.568z M31.321,35.805v-7.872l2.729-0.355v10.048L31.321,35.805',
                scale: 0.5,
                fillColor: "#427af5", // Car Color, you can change it(but don't, I like this color).
                fillOpacity: 1,
                strokeWeight: 1,
                anchor: new google.maps.Point(0, 5),
            };

            var uluru = { lat: data.val().latitude, lng: data.val().longitude };

            var marker = new google.maps.Marker({
                position: uluru,
                icon: icon,
                map: map
            });

            markers[data.key] = marker; // add marker in the markers array
            document.getElementById("users").innerHTML = users_count;
        }

            var preObject2 = document.getElementById('mock');
            var mock = firebase.database().ref().child('location/fromMockProvider');
            mock.on('value', snap => {
            preObject2.innerText = JSON.stringify(snap.val(), null, 3);
            });

        // get firebase database reference
        var users_Ref = firebase.database().ref('/');

        // this event will be triggered when a new object will be added in the database
        users_Ref.on('child_added', function (data) {
            users_count++;
            AddUser(data);
        });           

        // this event will be triggered on location change of any user
        users_Ref.on('child_changed', function (data) {
            markers[data.key].setMap(null);
            AddUser(data);
        });


        // If any user goes offline then this event will get triggered and we'll remove the marker of that user
        users_Ref.on('child_removed', function (data) {
            markers[data.key].setMap(null);
            users_count--;
            document.getElementById("users").innerHTML = users_count;
        });     


    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY=initMap">
    </script>

</body>
</html>