Google Maps API Tutorials (JavaScript)

How To Get Real-Time Tracking Using JavaScript & Google Maps API

Last modified on June 12th, 2023
Raja Tamil
Google Maps API Javascript

By the end of this quick JavaScript tutorial, you’re going to learn how to simulate real-time vehicle tracking from one location to another using Google Maps API like the animation below.

1. Create A Div Element & Make It Full Screen

Create a div element with an id map and make it full screen to the browser.

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

<style>
    html,
    body {
        height: 100%;
        margin: 0;
    }
    
    #map {
        height: 100%;
        background:red;
    }
</style>

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW

2. Add Google Maps To The View

1. Include the Google Maps JavaScript Library in your HTML file.

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>

Make sure to replace [YOUR_API_KEY] with in the URL. Learn how to get your own Google Maps API key if you’re not sure about how to get one.

2. Enable Google Maps JavaScript API from Google Cloud Console

3. Create a Map Object.

const map = new google.maps.Map(document.getElementById('map'), {
    center: {
        lat: 45.4222931,
        lng: -75.6870167
    },
    zoom: 13
});

I’ve used Ottawa geographic cooridnates in this example inside center object in the above code.

You can get coordinates of any city by going to this website.

3. Get Start And End Locations Of Your Choice

Determine two addresses of your choice and get their geographical coordinates.

This website helps you to convert any street address to geographical coordinates (latitude and longitude values)

I used two addresses from Ottawa city area in this example.

const startLocation = {
    lat: 45.4222931,
    lng: -75.6870167
}

const endLocation = {
    lat: 45.4199184,
    lng: -75.710681
}

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW

4. Draw Directions Path Between Two Locations

Using Google Maps API DirectionsService, you can easily draw a directions path between two locations.

const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();

directionsService.route({
    origin: startLocation,
    destination: endLocation,
    travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
        directionsRenderer.setDirections(response);
        directionsRenderer.setMap(map);
    }
})

I know it feels like magic!

5. Get The Steps From The Directions Service Response Object

In the directions service response object, you can find the overview_path which has all the direction steps between start and end locations in an array format.

if (status === google.maps.DirectionsStatus.OK) {
    ...

    const steps = response.routes[0].overview_path;
    console.log(steps);
}

Now we can easily loop through the steps array and get the steps from the starting location to the ending location in a linear way.

6. Position Marker To The First Step

1. Create a marker object which will be acting as the current location of the vehicle.

2. Position the marker with the first step which is the first item in the steps array.

if (status === google.maps.DirectionsStatus.OK) {
    ...
    var steps = response.routes[0].overview_path;

    const marker = new google.maps.Marker({
        map: map,
        position: {
            lat: steps[0].lat(),
            lng: steps[0].lng()
        },
        label: '🚘',
        zIndex: 1,
    });

}

7. Move The Marker Between Steps By Specific Interval

Finally, use the setInterval() method to simulate the vehicle movement from the starting location to the ending location by moving one step to the next with a specific interval.

For every interval of 1 second, increment the index of the steps array and set the new position to the marker.

let i = 0;
const interval = setInterval(function() {
    i++;
    if (i === steps.length) {
        clearInterval(interval);
        return
    }

    marker.setPosition({
        lat: steps[i].lat(),
        lng: steps[i].lng()
    });

}, 1000);

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW