JavaScript is one of the many fundamentals of tech when it comes to a freelancer’s technical skills. That, along with HTML and CSS. All of which play into some of the most in-demand technical skills in today’s industry. The backbone of all things web related. It’s important to have a good understanding of these aspects in order to further your career as a tech freelancer.

In this JavaScript training tutorial, we will have a look at Google Maps JavaScript API and how to build a map with this function. In addition, we will look at how to provide directions from one address to another.

For beginners, let’s start with the basics. What is Google Maps JavaScript API? According to Google, “the Google Maps JavaScript API is a powerful, popular mapping API. It’s simple to use to add maps to your website, or web or mobile application, and provides a wide range of services and utilities for data visualisation, map manipulation, directions, and more.”

In order to use Google Maps API, you need to get YOUR_API_KEY first.

First Step

The first step in this JavaScript training will be to create a simple map. In your application directory, create an html file with the code below:

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0"/>
    <meta charset="utf-8">
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        #map {
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        var map;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: {
                    lat: -34.397,
                    lng: 150.644
                },
                zoom: 8
            });
        }
    </script>https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async></script>
</body>
</html>

To run this example, open terminal and go to the application directory and run:

$ php -S localhost:8080

Javascript Training: How to Create Google Maps with JS API

Find Direction

Most first-time users may not realise that this is very a simple app. With the help of this JavaScript training, this app is even easier!  Now, let’s create a map with the ‘find direction’ function. In the layout, we need two more inputs to enter the address from and the address to. Change your index.html file by following the code below:

Maps

The moment you’ve been waiting for. These next steps in this Javascipt training will show you how to actually build your map. Follow the directions below.

Create maps.js file in the same directory with index.html file

maps.js

var map;

function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: {
            lat: 15,
            lng: 35
        }
    });
    directionsDisplay.setMap(map);
    var getDirection = function() {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    };
    document.getElementById('get-direction').addEventListener('click', getDirection);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
        origin: document.getElementById('start-point').value,
        destination: document.getElementById('end-point').value,
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            directionsDisplay.setDirections(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}

Reload your map. You should get a result similar to this.

Javascript Training: How to Create Google Maps with JS API

Test it out by entering an address for the start and an end inputs.

Javascript Training: How to Create Google Maps with JS API

In this next step, we will mark each waypoint along the route with the instruction text below to show when to click in markers. Edit maps.js like this:

maps.js

var map;

function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: {
            lat: 15,
            lng: 35
        }
    });
    directionsDisplay.setMap(map);
    var getDirection = function() {
        calculateAndDisplayRoute(directionsService, directionsDisplay, map);
    };
    document.getElementById('get-direction').addEventListener('click', getDirection);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay, map) {
    var arrMarkers = [];
    directionsService.route({
        origin: document.getElementById('start-point').value,
        destination: document.getElementById('end-point').value,
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            directionsDisplay.setDirections(response);
            showSteps(response, arrMarkers, map);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}

function showSteps(directionResult, arrMarkers, map) {
    var myRoute = directionResult.routes[0].legs[0];
    for (var i = 0; i < myRoute.steps.length; i++) {
        var marker = arrMarkers[i] = arrMarkers[i] || new google.maps.Marker;
        marker.setMap(map);
        marker.setPosition(myRoute.steps[i].start_location);
        infoWindow(marker, myRoute.steps[i].instructions, map);
    }
}

function infoWindow(marker, text, map) {
    google.maps.event.addListener(marker, 'click', function() {
        var iw = new google.maps.InfoWindow({
            content: text,
            maxWidth: 350
        });
        iw.open(map, marker);
    });
}

Reload localhost:8080 to get the following result:

Screen Shot 2016-09-02 at 5.54.38 AM.png

 

And there you go! Who would’ve thought building a Google map would be this simple? In conclusion, we hope this JavaScript training helps you take your tech skills to the next level. If you think you’ve found a knack for JavaScript, take a peek at the future of JavaScript blog post.

 

If you’re ready to take the next step, then let’s get started. If you’re applying as a top freelance simply click ‘Become a Pangara Talent.‘ For clients, ‘Hire a Pangara Talent.’ We look forward to working with you!

Stay tuned for Pangara’s latest news updates and events on their Facebook page, LinkedIn and Twitter.