Drawing Markers and Custom Markers On Google Map

What is a marker?

A marker specifies the location on Google Maps. To denote a location, address, place, city, town, country, etc we use the marker on Google Maps. Usually, we have a default icon to display markers. But we can customize the marker icon. Customization is allowed to change the icon, size, color of the marker. Markers give us a way to interact with the map. We can click on the marker to perform some action. In some applications, we can open an interactive customizable information window on the map displaying information regarding the location or place. Markers have different features such as padding, title, draggable, color, icon-image, etc. 

Adding One Marker On Google Map

We will see how we can add a marker on the Google Map. We will use google.map.Marker constructor to add the marker with some fields:
  • Position(Required Field): This is the required field when we add a marker. We need to specify the latitude and longitude values to define the location of the marker. 
  • Map(Optional field): This is the reference of the map on which we need to place the marker. Basically, we are attaching the marker to a map with this field. If we don't specify this field then a marker will be created but it is not attached to any map. 
Now we will see the code how we can add one marker on the Google Map:

var marker = new google.maps.Marker({
  position: {lat: -25.344, lng: 131.036},
  map: map
});

Here the position property sets the position of the marker. The second is the map reference which we have created. So the code with the marker looks like:

  mapInit() {
  var pos = {lat: -25.344, lng: 131.036};
    var mapOptions = {
      streetViewControl: false,
      center: pos,
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.HYBRID,
    };
    var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
    var marker = new google.maps.Marker({
                    position: pos, 
                    map: map
                 });
}

The full code for one marker looks like as below. The API key used here is obtained from Google. You can use your own API key for the project.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Marker Clustering</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #Gmap {
        height: 600px;
        width: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="Gmap"></div>
    <script>
  function initMap() {
  var pos = {lat: -25.344, lng: 131.036};
    var mapOptions = {
      streetViewControl: false,
      center: pos,
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.HYBRID,
    };
    var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
    var marker = new google.maps.Marker({
                    position: pos, 
                    map: map
                 });
}
    </script>
    <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAwJVIkcjN4RsV2GJZhZ5YrE1DT-m_wpBM&callback=initMap">
    </script>
  </body>
</html>

Adding Multiple Marker

We can add multiple markers on the Google Map by applying a loop such as for loop, forEach loop on the above method. In this case, we will have one array of objects consisting of various latitude and longitude values. These values denote different locations on which marker needs to be added. We will see how we can do this:

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Marker On Map</title>
    <style>
        #Gmap {
            height: 600px;
            width: 100%;
        }

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

<body>
    <div id="Gmap"></div>
    <script>
        function initMap() {
            var locations = [
                [-33.890542, 151.274856],
                [-33.923036, 151.259052],
                [-45.67677, -90.253456],
                [-20.334544, -70.35345435]

            ];
            var mapOptions = {
                streetViewControl: false,
                center: {lat:-45.67677, lng:-90.253456},
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.HYBRID,
            };
            var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
            locations.forEach(el => {
              let pos = el;
                var marker = new google.maps.Marker({
                    position: {lat: el[0], lng: el[1]},
                    map: map
                });
            });
        }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAwJVIkcjN4RsV2GJZhZ5YrE1DT-m_wpBM&callback=initMap">
        </script>
</body>
</html>










Changing Icon for the Marker

We can change the image for the marker icon using the icon property of the Marker. Set this property to the URL of the image which we want as the marker image. There is no need to define the size of the icon here. The Google Map API automatically size the icon.

      function initMap() {
            var locations = [
                [-33.890542, 151.274856],
                [-33.923036, 151.259052],
                [-45.67677, -90.253456],
                [-20.334544, -70.35345435]
            ];
            var mapOptions = {
                streetViewControl: false,
                center: { lat: -45.67677, lng: -90.253456 },
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.HYBRID,
            };
            var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
             var marker = new google.maps.Marker({
                             position: { lat: -50, lng: -100 },
                             map: map,
                             icon: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png"
              
            });
        }









Setting Title And Number or Alphabet Label For Marker

We can set title which will appear as a tooltip for the marker using the title property of the Marker constructor. The label appears inside the marker. It can be an alphabet or a number. We can specify label property to define a label on the marker. Alternatively, we can call the setLabel() method to attach a label on the existing one. 

        function initMap() {
            var numberLabel = "123456789";
            var defineIndex = 0;
            var locations = [
                [-33.890542, 151.274856],
                [-33.923036, 151.259052],
                [-45.67677, -90.253456],
                [-20.334544, -70.35345435]
            ];
            var mapOptions = {
                streetViewControl: false,
                center: { lat: -45.67677, lng: -90.253456 },
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.HYBRID,
            };
            var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
            locations.forEach(el => {
                var marker = new google.maps.Marker({
                    position: { lat: el[0], lng: el[1] },
                    map: map,
                    title: "Hello World",
                    label: numberLabel[defineIndex++ % numberLabel.length]                    
                });
            });
        }
In the above code, we will see number 1 as a label on the first location. Number 2 on the second location and so on. Like this, we can even specify alphabet labels to show labels as alphabets.

Making Marker Draggable

To make the marker draggable by the user to a different location, set the draggable property of Marker to true. 

       function initMap() {
            var numberLabel = "123456789";
            var defineIndex = 0;
            var locations = [
                [-33.890542, 151.274856],
                [-33.923036, 151.259052],
                [-45.67677, -90.253456],
                [-20.334544, -70.35345435]
            ];
            var mapOptions = {
                streetViewControl: false,
                center: { lat: -45.67677, lng: -90.253456 },
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.HYBRID,
            };
            var map = new google.maps.Map(document.getElementById('Gmap'), mapOptions);
            locations.forEach(el => {
                var marker = new google.maps.Marker({
                    position: { lat: el[0], lng: el[1] },
                    map: map,
                    title: "Hello World",
                    draggable: true

                });
            });
        }

Comments