04 April 2017

How To Add Google Map with Marker in Pure JavaScript

Okay, I said 'pure' JavaScript. Forgive me if I use a few CSS lines.

Here's my sample webpage displaying a Google map and our sample offices in Norway and in Makati City (Philippines):

<!DOCTYPE html>
<html>

<head>
    <title>Sample Google Map with Marker</title>
    <style type="text/css">
        #place_map_here {
            height: 500px;
            width: 1000px;
        }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
        function initialize() {
            var pointDestinations = [
                {
                    lat: 61.792135,
                    lon: 8.381478,
                    title: "Grosvik Norway",
                    description: "Norway office"
                },
                {
                    lat: 14.557985,
                    lon: 121.023870,
                    title: "Grosvik Phils.",
                    description: "Makati office"
                }
            ];
            var initialLocation = {
                zoom: 2,
                center: new google.maps.LatLng(61.792135, 8.381478),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("place_map_here"), initialLocation);

            var infoAboutThePlace = new google.maps.InfoWindow({
                content: ''
            });
            var y;
            for (y = 0; y < pointDestinations.length; y++) {

                var marker = new google.maps.Marker({
                    title: pointDestinations[y].title,
                    position: new google.maps.LatLng(pointDestinations[y].lat, pointDestinations[y].lon),
                    map: map
                });
                markerAndInformationBinder(marker, map, infoAboutThePlace, "<p>" + pointDestinations[y].description + "</p>");
            }
        }
        function markerAndInformationBinder(marker, map, infoAboutThePlace, html) {
            google.maps.event.addListener(marker, 'click', function () {
                infoAboutThePlace.setContent(html);
                infoAboutThePlace.open(map, marker);
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

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

</html>

No comments:

Post a Comment