gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Rotate Markers in Google Maps

Still as of today (post’s date) you cannot rotate markers in Google Maps, you only can resize them, however if you are using SVGs (what I always recommend) you can do any transformation you want 🙂

Live demo no longer available.

HTML

<input type="number" placeholder="rotation">
<div id="map"></div>

JavaScript

let marker_, svg_, size_ = 100, rotation_ = 25


// Get SVG
fetch('https://upload.wikimedia.org/wikipedia/commons/7/78/Space-shuttle.svg')
.then(response => response.text())
.then(text => {
  svg_ = text;
  svg_ = svg_
    .replace(/^<\?(.+)\?>$/gm, '') // unsupported unnecessary line
    // You can replace anything you want, but first of all check your svg code
    .replace(/width.+\Wheight\S+/, 
      'width="{{width}}" height="{{height}}" transform="{{transform}}"')
	
  // Load Map
  initMap(svg_)
})


// Map
function initMap(svg) {
  const position = {lat: 36.720426, lng: -4.412573};
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 19,
    center: position
  })
  marker_ = new google.maps.Marker({
    position: position,
    map: map,
    icon: `data:image/svg+xml;charset=utf-8,
      ${encodeURIComponent(svg
      .replace('{{width}}', size_)
      .replace('{{height}}', size_)
      .replace('{{transform}}', `rotate(${rotation_})`))}`
  })
}

// Change rotation
$input_ = document.querySelector('input')
$input_.value = rotation_
$input_.onchange = () => {
  marker_.setIcon(
  `data:image/svg+xml;charset=utf-8,
      ${encodeURIComponent(svg_
      .replace('{{width}}', size_)
      .replace('{{height}}', size_)
      .replace('{{transform}}', `rotate(${$input_.value})`))}`
  )
} 

CSS

* {
  padding: 0;
  margin: 0;
}

#map {
  width: 100%;
  height: 100vh;
}

input {
  position: fixed;
  z-index: 1;
  margin: 10px;
  padding: 10px;
  border-radius: 2px;
  background-color: white;
  border: none;
  color: #555;
  font-family: 'Roboto';
  width: 70px;
}
Open in JSFiddle

Tags: Google Maps API, marker, rotation, SVG