Realtime moving Cars on Google Maps JavaScript & Google Firebase

Realtime Moving Cars on Map using Firebase

Our aim has always been providing the solutions which are difficult to find or difficult to implement. Here’s another solution for real-time moving cars on Google Maps JavaScript using Google Firebase Real-time Database.  The complete working example is available on Github, you can find the link at the bottom of this post. 

You may also check Demo here:

Realtime Map Demo

What is Firebase?

Firebase is a real-time application platform. It allows developers to build rich, collaborative applications quickly using just client-side code. Applications built with Firebase:

  • Can be built rapidly
  • Update in realtime
  • Remain responsive even when a network connection is unavailable

Setup Firebase

If you don’t have a Firebase account, you can go to the Signup page and create an account. If you already have an account, you can Login here.

Once you are on Account’s page, you will have an option there to create a new Firebase app.

Firebase Console - Coding Infinite
Firebase Console – Coding Infinite

From Firebase Console find “Add Firebase to your web app”

You will find JavaScript Code with your project key & other credentials.


<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
    apiKey: "project-key-here",
    authDomain: "realtime-on-map-example.firebaseapp.com",
    databaseURL: "https://realtime-on-map-example.firebaseio.com",
    projectId: "realtime-on-map-example",
    storageBucket: "",
    messagingSenderId: "851837622908"
};
firebase.initializeApp(config);
</script>

Firebase Realtime Database

Create a Database for Latitude, Longitude, and angle of the car. How my database looks like

Firebase Realtime Database - Coding Infinite
Firebase Realtime Database – Coding Infinite

Simple Google Maps Setup

For moving realtime cars on Maps using Firebase our first step is to display a Google Map using Google Maps JavaScript API, for doing this, first you need to get API key for Google Maps and then use the below code to display Google Maps

<!DOCTYPE html>
<html>
    <head>
        <style>
            #map {
                height: 100%;
            }

            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
    </head>

    <body>
        <div id="map"></div>

        <!-- jQuery CDN -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>

            var map;
            function initMap() { // Google Map Initialization... 
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 16,
                    center: new google.maps.LatLng(31.52011, 74.368604),
                    mapTypeId: 'terrain'
                });
            }

        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7DtKqWoAtgKFmYtUu-PceyA7bV1Y9NTU&callback=initMap">
        </script>

    </body>
</html>

Firebase Add, Remove, Update Events

Now we need to add Events for Car Added, Car Removed or if Car changes location, we do not need to get all Cars List from Firebase Database, Add Event will do the job automatically for you.

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

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

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

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

Adding Car Marker

you can see in the above code that we child_added and chiled_changed methods calling AddCar Method, Job of this method is to create a car marker and Add marker on the Map.

function AddCar(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.4,
        fillColor: "#427af4", //<-- Car Color, you can change it 
        fillOpacity: 1,
        strokeWeight: 1,
        anchor: new google.maps.Point(0, 5),
        rotation: data.val().angle //<-- Car angle
    };

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

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

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

After combining the code you can view realtime moving cars on Google Maps. when you’ll update latitude or longitude at firebase database your car will move in realtime.

 
 
 

LEAVE A REPLY

Please enter your comment!
Please enter your name here