Google Maps

Google provide a JavaScript api that can be used to place Google maps into a webpage. You need to get a GoogleMap API key in order to use Google Maps. You can get a free Google Maps API key at this link. To use the API on your webpage, you need to include the following code:

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

Your map can hold any number of place-markers. The place-markers' names, latitudes and longtitudes are stored in an array, as shown below:

let locations = [['DkIT', 53.98485693, -6.39410164, 1],
                 ['Dundalk', 54.00428271, -6.40210535, 2],
                 ['Blackrock', 53.96251869, -6.36627104, 3]];

A for-loop is used to step through each place-marker, as shown below:

for (let i = 0; i < locations.length; i++)
{
   /* code for each place-marker */
} 

The initial centre of the map and the zoom value of the map are set using the code below:

let dkit_map = new google.maps.Map(document.getElementById('mapDiv'), 
                                     {zoom : 12,
                                      center : new google.maps.LatLng(53.98485693, -6.39410164),
                                      mapTypeId : google.maps.MapTypeId.ROADMAP});

Example of a GoogleMap (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
  width:600px;
  height:600px;
  border:thin solid black;

}
</style>
</head> 

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

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"></script>
  
<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
// hide the webpage loading message
document.getElementById('loadingMessage').style.visibility = "hidden"; displayMap(); } function displayMap(); { // These constants must start at 0 // These constants must match the data layout in the 'locations' array below let CONTENT = 0; let LATITUDE = 1; let LONGITUDE = 2; let locations = [['DkIT', 53.98485693, -6.39410164], ['Dundalk', 54.00428271, -6.40210535], ['Blackrock', 53.96251869, -6.36627104]]; let dkit_map = new google.maps.Map(document.getElementById('mapDiv'), {zoom : 12, center : new google.maps.LatLng(53.98485693, -6.39410164), mapTypeId : google.maps.MapTypeId.ROADMAP}); let location_marker; let mapWindow = new google.maps.InfoWindow(); for (let i = 0; i < locations.length; i++) { location_marker = new google.maps.Marker({position : new google.maps.LatLng(locations[i][LATITUDE], locations[i][LONGITUDE]), map : dkit_map}); google.maps.event.addListener(location_marker, 'click', (function(location_marker, i) { return function() { mapWindow.setContent(locations[i][CONTENT]); mapWindow.open(dkit_map, location_marker); } })(location_marker, i)); } } </script> </body> </html>

Finding Latitude and Longtitude

Use the Google Maps Latitude and Longtitude finder to get the values for the map markers.

http://gps.ie/gps-lat-long-finder.htm

Write code to show the location of your own home city. Scale the map, so that it includes your entire country, as shown here.

google.maps.Marker can allow markers to animate. Write code to animate the marker for your hometown, as shown here.

google.maps.Marker can be changed to used different icons. Write code to place a symbol over various parking places in your own town, as shown here.

Write code to show text when a user hovers over a marker, as shown here.

Custom Content

The content of a place-marker can be customised by placing the code to describe the content inside a string and replacing the place-marker title with the new strinctx. In the example below, the code is place into a variable called dkit_content_string

let dkit_content_string = '<div id="dkit_content"><h1>Dundalk Institute of Technology</h1><div id="content"><img src = "dkit_photo.jpg"><p>Dundalk Institute of Technology is the best place to study computing in Ireland.</p><p>For more information, see our website<br><a href="http://www.dkit.ie">www.dkit.ie</a></p></div></div>';

The style of the content can be set in the normal way using style sheets, as shown in the code below:

#dkit_content
{
  width:400px;
  height:200px;
}

#dkit_content img
{
  clear:both;
  float:left;
  width: 150px;
  border-radius:100px;
  margin: 20px;
  margin-top:0px;
  border:thin solid #CCC;
}

Example of a Custom Content GoogleMap (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Custom Google Map Demo</title> 

<style>
#mapDiv
{
  width:600px;
  height:600px;

  border:thin solid black;
}

#dkit_content
{
  width:400px;
  height:200px;
}

#dkit_content img
{
  clear:both;
  float:left;
  width: 150px;
  border-radius:100px;
  margin: 20px;
  margin-top:0px;
  border:thin solid #CCC;
}


</style>
</head> 

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

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"></script>
  
<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
// hide the webpage loading message
document.getElementById('loadingMessage').style.visibility = "hidden"; displayMap(); } function displayMap(); { let dkit_content_string = '<div id="dkit_content"><h1>Dundalk Institute of Technology</h1><div id="content"><img src = "dkit_photo.jpg"><p>Dundalk Institute of Technology is the best place to study computing in Ireland.</p><p>For more information, see our website<br><a href="http://www.dkit.ie">www.dkit.ie</a></p></div></div>'; // These constants must start at 0 // These constants must match the data layout in the 'locations' array below let CONTENT = 0; let LATITUDE = 1; let LONGITUDE = 2; let locations = [[dkit_content_string, 53.98485693, -6.39410164], ['Dundalk', 54.00428271, -6.40210535], ['Blackrock', 53.96251869, -6.36627104]]; let dkit_map = new google.maps.Map(document.getElementById('mapDiv'), {zoom : 12, center : new google.maps.LatLng(53.98485693, -6.39410164), mapTypeId : google.maps.MapTypeId.ROADMAP}); let location_marker; let mapWindow = new google.maps.InfoWindow(); for (let i = 0; i < locations.length; i++) { location_marker = new google.maps.Marker({position : new google.maps.LatLng(locations[i][1], locations[i][2]), map : dkit_map}); google.maps.event.addListener(location_marker, 'click', (function(location_marker, i) { return function() { mapWindow.setContent(locations[i][0]); mapWindow.open(dkit_map, location_marker); } })(location_marker, i)); } } </script> <p>Click on the DkIT place-marker to see an example of a custom place-marker.</p> </body> </html>

Make your own cutom content for a marker. Do not copy the design from the example above.

Create custom content that displays a marker's content in a speech bubble, as shown here. Hint: Search the www to see how you can replace the "google.maps.InfoWindow" with custom content.

Amend the example above to dynamically load the marker details from a JSON string, as shown here.

Nearby Services

The Google Maps API allows us to get a list of nearby services, such as hotels, schools and hospitals.

Example of Google Maps Nearby Services (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
    width:600px;
    height:600px;
    border:thin solid black;

}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4&libraries=places"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    let services_centre_location = {lat: 54.00428271, lng: -6.40210535};  // Dundalk
    let dkit_map = new google.maps.Map(document.getElementById('mapDiv'),
            {
                zoom: 17,
                center: new google.maps.LatLng(services_centre_location),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

    let mapWindow = new google.maps.InfoWindow();

    let service = new google.maps.places.PlacesService(dkit_map);
    service.nearbySearch(
            {
                location: services_centre_location, // centre of the search
                radius: 500                         // radius (in metres) of the search
            }, getNearbyServicesMarkers);


    function getNearbyServicesMarkers(results, status)
    {
        if (status === google.maps.places.PlacesServiceStatus.OK)
        {
            for (let i = 0; i < results.length; i++)
            {
                createMarker(results[i]);
            }
        }
    }


    function createMarker(place)
    {
        let marker = new google.maps.Marker(
                {
                    map: dkit_map,
                    position: place.geometry.location
                });

        google.maps.event.addListener(marker, 'click', function ()
        {
            mapWindow.setContent(place.name);
            mapWindow.open(dkit_map, this);
        });
    }
}
</script>
</head> 
<body>
<div id="mapDiv"></div>
<p>Show all nearby services in Dundalk</p>
</body>
</html>

 

We can filter the nearby services to only include specific services, such as cafes.

Example showing nearby cafes (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
    width:600px;
    height:600px;
    border:thin solid black;

}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4&libraries=places"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    let services_centre_location = {lat: 54.00428271, lng: -6.40210535};
    let dkit_map = new google.maps.Map(document.getElementById('mapDiv'),
            {
                zoom: 17,
                center: new google.maps.LatLng(services_centre_location),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

    let mapWindow = new google.maps.InfoWindow();

    let service = new google.maps.places.PlacesService(dkit_map);
    service.nearbySearch(
            {
                location: services_centre_location,
                radius: 500,
                type: ['cafe']
            }, getNearbyServicesMarkers);


    function getNearbyServicesMarkers(results, status)
    {
        if (status === google.maps.places.PlacesServiceStatus.OK)
        {
            for (let i = 0; i < results.length; i++)
            {
                createMarker(results[i]);
            }
        }
    }


    function createMarker(place)
    {
        let marker = new google.maps.Marker(
                {
                    map: dkit_map,
                    position: place.geometry.location
                });

        google.maps.event.addListener(marker, 'click', function ()
        {
            mapWindow.setContent(place.name);
            mapWindow.open(dkit_map, this);
        });
    }
}
</script>
</head> 
<body>
<div id="mapDiv"></div>
<p>Show all cafes in Dundalk</p>
</body>
</html>

Write code to only show the cafes that are close by a marker when the marker has been clicked, as shown here.

Write code that allows the user to choose to display either restaurants or cafes, as shown here.

Google Maps provides a default icon for each marker type. The code below uses the default restaurant and cafe icons.

Example using default Google Maps icons (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
    width:600px;
    height:600px;
    border:thin solid black;

}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4&libraries=places"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    // These constants must start at 0
    // These constants must match the data layout in the 'locations' array below
    let CONTENT = 0;
    let LATITUDE = 1;
    let LONGITUDE = 2;
    let locations = [['DkIT', 53.98485693, -6.39410164],
        ['Dundalk', 54.00428271, -6.40210535],
        ['Blackrock', 53.96251869, -6.36627104]];

    let dkit_map = new google.maps.Map(document.getElementById('mapDiv'),
            {zoom: 13,
                center: new google.maps.LatLng(53.98485693, -6.39410164),
                mapTypeId: google.maps.MapTypeId.ROADMAP});

    let location_marker;
    let mapWindow = new google.maps.InfoWindow();

    for (let i = 0; i < locations.length; i++)
    {
        location_marker = new google.maps.Marker({position: new google.maps.LatLng(locations[i][LATITUDE], locations[i][LONGITUDE]), map: dkit_map});

        google.maps.event.addListener(location_marker, 'click', (function (location_marker, i)
        {
            return function ()
            {
                mapWindow.setContent(locations[i][CONTENT]);
                mapWindow.open(dkit_map, location_marker);

                let services_centre_location = {lat: locations[i][LATITUDE], lng: locations[i][LONGITUDE]};

                let service = new google.maps.places.PlacesService(dkit_map);

                let serviceType = "";
                if (document.getElementById('restaurant').checked === true)
                {
                    serviceType = "restaurant";
                }
                if (document.getElementById('cafe').checked === true)
                {
                    serviceType = "cafe";
                }

                service.nearbySearch(
                        {
                            location: services_centre_location,
                            radius: 500,
                            type: [serviceType]

                        }, getNearbyServicesMarkers);

            }
        })(location_marker, i));
    }


    let nearbyServicesMarkers = []; // used in both getNearbyServicesMarkers() and createMarker()
    function getNearbyServicesMarkers(results, status)
    {
        if (status === google.maps.places.PlacesServiceStatus.OK)
        {
            // hide any previously displayed services markers
            if (nearbyServicesMarkers.length > 0)
            {
                for (let i = 0; i < nearbyServicesMarkers.length; i++)
                {
                    nearbyServicesMarkers[i].setVisible(false);
                }
            }
            // empty nearbyServicesMarkers[], so that it can be used to hold the nearby services markers for the currently clicked marker
            nearbyServicesMarkers = [];

            for (let i = 0; i < results.length; i++)
            {
                createMarker(results[i]);
            }
        }
    }


    function createMarker(place)
    {
        let icon =
                {
                    url: place.icon, // url
                    scaledSize: new google.maps.Size(30, 30), // scale the image to an icon size
                };

        let marker = new google.maps.Marker(
                {
                    map: dkit_map,
                    position: place.geometry.location,
                    icon: icon
                });

        // add the marker to nearbyServicesMarkers[]       
        nearbyServicesMarkers.push(marker);

        google.maps.event.addListener(marker, 'click', function ()
        {
            mapWindow.setContent(place.name);
            mapWindow.open(dkit_map, this);
        });
    }
}
</script>
</head> 
<body>
<div id='controlPanel'>
<label for='restaurant'>Restaurant</label><input type='radio' name='search' id='restaurant' value='restaurant' checked onclick='displayMap()'>
<label for='cafe'>Cafe</label><input type='radio' name='search' id='cafe' value='cafe' onclick='displayMap()'>
</div>
<br>

<div id="mapDiv"></div>
<p>Click on a marker to see the local restaurants or cafes</p>
</body>
</html>

Write code that overwrites the default Google Maps restaurant and cafe icons with user defined icons, as shown here.

Google maps allows for text based nearby services searches.

Example showing a text search of nearby places (Run Example).

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
    width:600px;
    height:600px;
    border:thin solid black;

}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4&libraries=places"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    // These constants must start at 0
    // These constants must match the data layout in the 'locations' array below
    let CONTENT = 0;
    let LATITUDE = 1;
    let LONGITUDE = 2;
    let locations = [['DkIT', 53.98485693, -6.39410164],
        ['Dundalk', 54.00428271, -6.40210535],
        ['Blackrock', 53.96251869, -6.36627104]];

    let dkit_map = new google.maps.Map(document.getElementById('mapDiv'),
            {zoom: 13,
                center: new google.maps.LatLng(53.98485693, -6.39410164),
                mapTypeId: google.maps.MapTypeId.ROADMAP});

    let location_marker;
    let mapWindow = new google.maps.InfoWindow();

    for (let i = 0; i < locations.length; i++)
    {
        location_marker = new google.maps.Marker({position: new google.maps.LatLng(locations[i][LATITUDE], locations[i][LONGITUDE]), map: dkit_map});

        google.maps.event.addListener(location_marker, 'click', (function (location_marker, i)
        {
            return function ()
            {
                mapWindow.setContent(locations[i][CONTENT]);
                mapWindow.open(dkit_map, location_marker);

                let services_centre_location = {lat: locations[i][LATITUDE], lng: locations[i][LONGITUDE]};

                let service = new google.maps.places.PlacesService(dkit_map);

                /* This code is removed
                 let serviceType = "";
                 if (document.getElementById('restaurant').checked === true)
                 {
                 serviceType = "restaurant";
                 }
                 if (document.getElementById('cafe').checked === true)
                 {
                 serviceType = "cafe";
                 }
                 
                 service.nearbySearch(
                 {
                 location: services_centre_location,
                 radius: 500,
                 type: [serviceType]
                 
                 }, getNearbyServicesMarkers);
                 */


                /* The removed code is replaced by the code below */

                let serviceType = document.getElementById('search').value;
                service.textSearch(
                        {
                            location: services_centre_location,
                            radius: 500,
                            type: [serviceType]

                        }, getNearbyServicesMarkers);

                /******************************/                
            }
        })(location_marker, i));
    }

    let nearbyServicesMarkers = []; // used in both getNearbyServicesMarkers() and createMarker()
    function getNearbyServicesMarkers(results, status)
    {
        if (status === google.maps.places.PlacesServiceStatus.OK)
        {
            // hide any previously displayed services markers
            if (nearbyServicesMarkers.length > 0)
            {
                for (let i = 0; i < nearbyServicesMarkers.length; i++)
                {
                    nearbyServicesMarkers[i].setVisible(false);
                }
            }
            // empty nearbyServicesMarkers[], so that it can be used to hold the nearby services markers for the currently clicked marker
            nearbyServicesMarkers = [];

            for (let i = 0; i < results.length; i++)
            {
                createMarker(results[i]);
            }
        }
    }


    function createMarker(place)
    {
        let icon =
                {
                    url: place.icon, // url
                    scaledSize: new google.maps.Size(30, 30), // scale the image to an icon size
                };

        let marker = new google.maps.Marker(
                {
                    map: dkit_map,
                    position: place.geometry.location,
                    icon: icon
                });

        // add the marker to nearbyServicesMarkers[]       
        nearbyServicesMarkers.push(marker);

        google.maps.event.addListener(marker, 'click', function ()
        {
            mapWindow.setContent(place.name);
            mapWindow.open(dkit_map, this);
        });
    }
}
</script>
</head> 
<body>
<div id='controlPanel'>
<label for='search'>Search: </label><input type="text" id="search"> 
<input type="button" value="Submit" onclick="displayMap()">
</div>
<br>

<div id="mapDiv"></div>
<p>Click on a marker to see the local restaurants or cafes</p>
</body>
</html>

We can display the details of a google maps marker when the marker is clicked.

Example that displays some details of a clicked marker (Run Example)

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<title>Google Map Demo</title> 

<style>
#mapDiv
{
    width:600px;
    height:600px;
    border:thin solid black;

}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4&libraries=places"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    // These constants must start at 0
    // These constants must match the data layout in the 'locations' array below
    let CONTENT = 0;
    let LATITUDE = 1;
    let LONGITUDE = 2;
    let locations = [['DkIT', 53.98485693, -6.39410164],
        ['Dundalk', 54.00428271, -6.40210535],
        ['Blackrock', 53.96251869, -6.36627104]];

    let dkit_map = new google.maps.Map(document.getElementById('mapDiv'),
            {zoom: 13,
                center: new google.maps.LatLng(53.98485693, -6.39410164),
                mapTypeId: google.maps.MapTypeId.ROADMAP});

    let location_marker;
    let mapWindow = new google.maps.InfoWindow();

    for (let i = 0; i < locations.length; i++)
    {
        location_marker = new google.maps.Marker({position: new google.maps.LatLng(locations[i][LATITUDE], locations[i][LONGITUDE]), map: dkit_map});

        google.maps.event.addListener(location_marker, 'click', (function (location_marker, i)
        {
            return function ()
            {
                mapWindow.setContent(locations[i][CONTENT]);
                mapWindow.open(dkit_map, location_marker);

                let services_centre_location = {lat: locations[i][LATITUDE], lng: locations[i][LONGITUDE]};

                let service = new google.maps.places.PlacesService(dkit_map);

                let serviceType = document.getElementById('search').value;
                service.textSearch(
                        {
                            location: services_centre_location,
                            radius: 500,
                            type: [serviceType]

                        }, getNearbyServicesMarkers);
            }
        })(location_marker, i));
    }


    let nearbyServicesMarkers = []; // used in both getNearbyServicesMarkers() and createMarker()
    function getNearbyServicesMarkers(results, status)
    {
        if (status === google.maps.places.PlacesServiceStatus.OK)
        {
            // hide any previously displayed services markers
            if (nearbyServicesMarkers.length > 0)
            {
                for (let i = 0; i < nearbyServicesMarkers.length; i++)
                {
                    nearbyServicesMarkers[i].setVisible(false);
                }
            }
            // empty nearbyServicesMarkers[], so that it can be used to hold the nearby services markers for the currently clicked marker
            nearbyServicesMarkers = [];

            for (let i = 0; i < results.length; i++)
            {
                /* Remove the code below                  
                 createMarker(results[i]);
                 */

                /* Replace the removed code with the code below */
                let request = {
                    placeId: results[i].place_id
                };
                service = new google.maps.places.PlacesService(dkit_map);
                service.getDetails(request, createServiceMarkers);
                /**********/
            }
        }
    }

    /* Also, replace the removed code with the code below */
    function createServiceMarkers(place, status)
    {
        if (status == google.maps.places.PlacesServiceStatus.OK)
        {
            createMarker(place);
        }
    }
    /**********/

    function createMarker(place)
    {
        let icon;
        if (place.icon.indexOf("restaurant") > 0)
        {
            icon = {
                url: "images/restaurant_icon.png",
                scaledSize: new google.maps.Size(30, 30), // scaled size
            };
        }
        else if (place.icon.indexOf("cafe") > 0)
        {
            icon = {
                url: "images/cafe_icon.png", // url
                scaledSize: new google.maps.Size(30, 30), // scaled size
            };
        }
        else
        {
            icon = {
                url: place.icon,
                scaledSize: new google.maps.Size(30, 30), // scaled size
            };
        }

        let marker = new google.maps.Marker(
                {
                    map: dkit_map,
                    position: place.geometry.location,
                    icon: icon
                });

        // add the marker to nearbyServicesMarkers[]       
        nearbyServicesMarkers.push(marker);

        google.maps.event.addListener(marker, 'click', function ()
        {

            let htmlContent = "<p><strong>" + place.name + "</strong><br>" + place.formatted_address + "</br>" + place.international_phone_number + "</p>";
            mapWindow.setContent(htmlContent);
            mapWindow.open(dkit_map, this);
        });
    }
}
</script>
</head> 
<body>
<div id='controlPanel'>
<label for='search'>Search: </label><input type="text" id="search"> 
<input type="button" value="Submit" onclick="displayMap()">
</div>
<br>

<div id="mapDiv"></div>
<p>Click on a marker to see the local restaurants or cafes</p>
</body>
</html>

Amend the above code, so that the address is formatted, as shown here.

Route Planner

Example of a Route Planner (Run Example)

<!DOCTYPE html>
<html>
<head>
<title>Route Finder Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD3GNUNqilg3CdYIedKxEY5zgCl4p7xp-4"></script>


<style>
#mapDiv 
{
    width:100%;
    height:600px;
    border:thin solid #CCC;
}

#controlPanel
{
    position: absolute;
    top: 50px;
    left: 10px;
    z-index: 2;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
}

#directions
{
    float:left;
    width:100%;
    margin:0px;
}
</style>


<script>
let currentLocationMap;
let directionsDisplay;
let directionsService;
let currentLocationMap;

window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
    // hide the webpage loading message
    document.getElementById('loadingMessage').style.visibility = "hidden";

    displayMap();
}


function displayMap()
{
    directionsService = new google.maps.DirectionsService();
    // route planner
    directionsDisplay = new google.maps.DirectionsRenderer();
    let currentLocationMap = new google.maps.LatLng(54, -6.3);  // DkIT

    let mapOptions = {zoom: 10, center: currentLocationMap};
    currentLocationMap = new google.maps.Map(document.getElementById('mapDiv'), mapOptions);
    directionsDisplay.setMap(currentLocationMap);
}


function calculateRoute()
{
    let start = document.getElementById('start').value;
    let end = document.getElementById('end').value;

    let request = {origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING};


    directionsService.route(request, function (response, status)
    {
        if (status == google.maps.DirectionsStatus.OK)
        {
            directionsDisplay.setDirections(response);
        }
    });
}


</script>
</head>

<body>
<div id="controlPanel">
<b>Start:</b>
<select id="start">
<option value="Dundalk Institute of Technology Louth Ireland">DkIT</option>
<option value="Dublin City University Collins Avenue Extension Whitehall Dublin 9">DCU</option>
<option value="Maynooth University Ireland">Maynooth</option>
</select>

<br>
<b>End: </b>
<select id="end">
<option value="Dundalk Institute of Technology Louth Ireland">DkIT</option>
<option value="Dublin City University Collins Avenue Extension Whitehall Dublin 9">DCU</option>
<option value="Maynooth University Ireland">Maynooth</option>
</select>

   
<button onclick='calculateRoute()'>Submit</button>
</div>

<div id="mapDiv"></div>           

</body>
</html>

Adjust the code above, so that the user can type in the start and end locations using the Google Maps API predictive place names, as shown here.

Route Planner with Directions

GoogleMaps API provides can provide text directions for a Route Planner. The code below will output the text directions into the div called 'directions'.


directionsDisplay.setPanel(document.getElementById('directions'));

Example of a Route Planner with text directions (Run Example)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Route Finder Demo</title>
<style>
#controlPanel 
{
    float:left;
    width:49%;
}

#mapDiv 
{
    width:49%;
    height:600px;
    float:right;
    border:thin solid #CCC;
}

#directions
{
    float:left;
    width:100%;
    margin:0px;
}
</style>

<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"></script>

<script>
window.onload = onAllAssetsLoaded;
document.write("<div id='loadingMessage'>Loading...</div>");
function onAllAssetsLoaded()
{
// hide the webpage loading message
document.getElementById('loadingMessage').style.visibility = "hidden"; displayMap(); } function displayMap(); { let currentLocationMap; let directionsDisplay; let directionsService; let currentLocationMap; function init() { directionsService = new google.maps.DirectionsService(); // route planner directionsDisplay = new google.maps.DirectionsRenderer(); let currentLocationMap = new google.maps.LatLng(54, -6.3); // DkIT let mapOptions = {zoom: 10, center: currentLocationMap}; currentLocationMap = new google.maps.Map(document.getElementById('mapDiv'), mapOptions); directionsDisplay.setMap(currentLocationMap); // add directions to the route directionsDisplay.setPanel(document.getElementById('directions')); } function calculateRoute() { let start = document.getElementById('start').value; let end = document.getElementById('end').value; let request = {origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING}; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } } </script> </head> <body onload='init()'> <div id="controlPanel"> <b>Start:</b> <select id="start"> <option value="Dundalk Institute of Technology Louth Ireland">DkIT</option> <option value="Dublin City University Collins Avenue Extension Whitehall Dublin 9">DCU</option> <option value="Maynooth University Ireland">Maynooth</option> </select> <br> <b>End: </b> <select id="end"> <option value="Dundalk Institute of Technology Louth Ireland">DkIT</option> <option value="Dublin City University Collins Avenue Extension Whitehall Dublin 9">DCU</option> <option value="Maynooth University Ireland">Maynooth</option> </select>     <button onclick='calculateRoute()'>Submit</button> <br> <br> <br> <div id="directions"></div> </div> <div id="mapDiv"></div> </body> </html>

Adjust the above code, so that the user can press a button to select the type of transport that they will use for the journey, as shown here.

Adjust the above code, so that the directions can be minimised by the user, as shown here.

 
<div align="center"><a href="../../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>