Google Maps JS: Custom Marker

Resources

by andriika

HTML

<!DOCTYPE html>
<html>

  <head>
    <title>Custom Marker</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initMap&libraries=&v=weekly" defer></script>
  </head>

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

</html>

CSS

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

.marker {
  color: white;
  background-color: black;
  border: solid 1px black;
  font-weight: 900;
  padding: 4px;
  top: -8px;
}

.marker::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, 0%), rotate(45deg);
  border: solid 8px transparent;
  border-top-color: black;
}

JavaScript

function initMap() {

  class MyMarker extends google.maps.OverlayView {
    constructor(params) {
      super();
      this.position = params.position;

      const content = document.createElement('div');
      content.classList.add('marker');
      content.textContent = params.label;
      content.style.position = 'absolute';
      content.style.transform = 'translate(-50%, -100%)';

      const container = document.createElement('div');
      container.style.position = 'absolute';
      container.style.cursor = 'pointer';
      container.appendChild(content);

      this.container = container;
    }

    onAdd() {
      this.getPanes().floatPane.appendChild(this.container);
    }

    onRemove() {
      this.container.remove();
    }

    draw() {
      const pos = this.getProjection().fromLatLngToDivPixel(this.position);
      this.container.style.left = pos.x + 'px';
      this.container.style.top = pos.y + 'px';
    }
  }

  const map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -33.9,
      lng: 151.1
    },
    zoom: 10,
  });

  const marker = new MyMarker({
  	position: new google.maps.LatLng(-33.9, 151.1),
    label: '$2.45m'
  });
  marker.setMap(map);
}