Google Maps Custom controls

Google Maps Custom controls

by Daan De Smedt

HTML

<!DOCTYPE html>
<html>

  <head>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

  </head>

  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=visualization&v=weekly" async></script>
  </body>

</html>

CSS

#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.map-control {
  top: 10px;
  background: none padding-box rgb(255, 255, 255);
  display: table-cell;
  border: 0px;
  margin: 0px;
  position: relative;
  cursor: pointer;
  direction: ltr;
  overflow: hidden;
  text-align: center;
  height: 40px;
  vertical-align: middle;
  color: rgb(86, 86, 86);
  font-family: Roboto, Arial, sans-serif;
  font-size: 18px;
  border-bottom-left-radius: 2px;
  border-top-left-radius: 2px;
  box-shadow: rgb(0 0 0 / 30%) 0px 1px 4px -1px;
  min-width: 36px;
}

.map-control-button {

  background: none padding-box rgb(255, 255, 255);
  display: table-cell;
  border: 0px;
  margin: 0px;
  padding: 0px 17px;
  text-transform: none;
  position: relative;
  cursor: pointer;
  overflow: hidden;
  text-align: center;
  height: 40px;
  vertical-align: middle;
  color: rgb(0, 0, 0);
  font-family: Roboto, Arial, sans-serif;
  font-size: 18px;
  border-bottom-right-radius: 2px;
  border-top-right-radius: 2px;
  min-width: 66px;
  font-weight: 500;
  box-shadow: rgb(0 0 0 / 30%) 0px 1px 4px -1px;
}

.active {
  background: none padding-box rgb(50 76 220) !important;
  color: rgb(255, 255, 255);
}

JavaScript

let map;


function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    mapTypeId: "hybrid",
    zoom: 8,
    center: {
      lat: 50.5010789,
      lng: 4.4764595
    }
  });

  // custom control
  const controlDIV = document.createElement("div");

  const controlUI = document.createElement("div");
  controlUI.className = "map-control";
  controlDIV.appendChild(controlUI);

  const controlTextCluster = document.createElement("span");
  controlTextCluster.className = "map-control-button active";
  controlTextCluster.innerHTML = "Cluster";
  controlTextCluster.changeToId = "cluster";

  const controlTextHeat = document.createElement("span");
  controlTextHeat.className = "map-control-button";
  controlTextHeat.innerHTML = "Heat";
  controlTextHeat.changeToId = "heat";

  controlUI.appendChild(controlTextCluster);
  controlUI.appendChild(controlTextHeat);

  controlUI.addEventListener("click", (e) => {
    console.log('Change to : ' + e.target.changeToId);
  });

  map.controls[google.maps.ControlPosition.TOP_CENTER].push(controlDIV);

}