Rotate Markers in Google Maps
by Génesis García Morilla
HTML
<script src="https://maps.google.com/maps/api/js"></script>
<input type="number" placeholder="rotation">
<div id="map"></div>
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;
}
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})`))}`
)
}