Rotating image / marker image on Google map V3

How could I rotate an image (marker image) on a Google map V3?

  • There is an excellent example for V2 here, exactly doing what I need. But for GMap2! They do it with a rotating canvas.
  • Image rotating with JS / JQuery is frequently used, there are multiple answers about this. But how could I apply this to my maps image?
  • One mentioned approach is to have different images for different angles and to switch among them - this is NOT what I want. I do not like to have so many images, I want to rotate by code.

Remark: There are similar questions, but all for V2 and not V3 (as far I can tell). I need it for V3.



I have done the rotation in v3 with the following code:

<canvas id="carcanvas" width="1" height="1"></canvas>

    if (document.getElementById('carcanvas').getContext) {
        var supportsCanvas = true;
    } else {
        var supportsCanvas = false;

    var rImg = new Image();

    // Returns the bearing in radians between two points.
    function bearing( from, to ) {
        // Convert to radians.
        var lat1 = from.latRadians();
        var lon1 = from.lngRadians();
        var lat2 = to.latRadians();
        var lon2 = to.lngRadians();
        // Compute the angle.
        var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
        if ( angle < 0.0 )
            angle  += Math.PI * 2.0;
        if (angle == 0) {angle=1.5;}
        return angle;

    function plotcar() {
        canvas = document.getElementById("carcanvas").getContext('2d');
        var cosa = Math.cos(angle);
        var sina = Math.sin(angle);

and in the animation method :

if (supportsCanvas) {
                    angle = bearing(new google.maps.LatLng(lat1, lng1),new google.maps.LatLng(lat2, lng2));

I hope that help.


My js class for solving this problem is:

var RotateIcon = function(options){
    this.options = options || {};
    this.rImg = options.img || new Image();
    this.rImg.src = this.rImg.src || this.options.url || '';
    this.options.width = this.options.width || this.rImg.width || 52;
    this.options.height = this.options.height || this.rImg.height || 60;
    var canvas = document.createElement("canvas");
    canvas.width = this.options.width;
    canvas.height = this.options.height;
    this.context = canvas.getContext("2d");
    this.canvas = canvas;
RotateIcon.makeIcon = function(url) {
    return new RotateIcon({url: url});
RotateIcon.prototype.setRotation = function(options){
    var canvas = this.context,
        angle = options.deg ? options.deg * Math.PI / 180:
        centerX = this.options.width/2,
        centerY = this.options.height/2;

    canvas.clearRect(0, 0, this.options.width, this.options.height);;
    canvas.translate(centerX, centerY);
    canvas.translate(-centerX, -centerY);
    canvas.drawImage(this.rImg, 0, 0);
    return this;
RotateIcon.prototype.getUrl = function(){
    return this.canvas.toDataURL('image/png');

Call it like this:

var marker = new google.maps.Marker({
    icon: {
        url: RotateIcon
            .setRotation({deg: 92})

See live example here


I have found two extensions to the Google MAP V3: infobox.js and markerwithlabel.js Both can handle an image DOM element as content, which in turn I can rotate via the jQuery image rotate plugin.

This even works without setting the marker's image again after rotation.

Edit: As of questions / comments below:

The extension for label is required, because it can handle other DOM elements. So I can add arbitrary HTML as label, in my particular case I add the image. And then I do rotate this image (child of the label) with the rotate plugin. So assign the image an id in order to easily access it. Actually I am using one label just for the image, and another for descriptive text.

Edit 2: Due to Stephan's comment on the DOM readiness

In my code I have found the following lines. This shows that I force a draw on the label before rotating the image.

    if (!this._drawn) myImageLabel.draw(); // 1st time force a draw, otherwise rotating the image will fail because an asynchronously drawn object has not all tags in place
    if (this.heading != 0) this.rotateImage(this.heading, true);

Edit 3: Code example how to create the Infobox.js

this._img = document.createElement('img');
... further manipulations of _img / Size / Id / ...
var planeImageLabelOptions = {
            content: this._img,
            disableAutoPan: true,
            boxStyle: planeImageLabelBoxStyle,
            pixelOffset: new google.maps.Size(-imgOffsetW / 2, -imgOffsetH / 2),
            closeBoxURL: "",
            position: latlng,
            zIndex: this.altitude < 0 ? 100 : this.altitude
 var planeImageLabel = new InfoBox(planeImageLabelOptions);

I also had a hard time to figure out the way to rotate .png marker. I solved it like below. You can create many markers with same custom image and rotate a specific marker you want to rotate. I hope it helpful to you.

var id = 'my_marker_01';
var img_url = "../img/car.png";
var my_icon = img_url + "#" + id;
var marker = new google.maps.Marker({
    icon: my_icon,

var rotate = 45;
    {'-webkit-transform' : 'rotate('+ rotate +'deg)',
       '-moz-transform' : 'rotate('+ rotate +'deg)',
       '-ms-transform' : 'rotate('+ rotate +'deg)',
       'transform' : 'rotate('+ rotate +'deg)'}); 

How could I rotate an image (marker image) on a Google map V3?

I had the same problem and I solved it with the next code:

var gmap;
    gmap = map;

I suppose that you have a variable with the icon, for example:

var imagePath = 'img/customMarker.png';

First, we need to create our marker options:

var markerOptions = {
    location: [x, y],
    title:'some text',
    draggable: true,
    icon: imagePath

Let's create a marker:

var marker = new google.maps.Marker(markerOptions);

And we have to set the map:


Now if you want to rotate the image you need to do the next:

  • Change the imagePath variable's value to 'img/customMarker.png#yourId'
  • Set rotation value with css (e.g. with JQuery)

Let's see

imagePath = 'img/customMarker.png#markerOne';

     'transform': 'rotate(45deg)'

Of course you can do it fancier:

function rotateMarker(selector, degree){
         'transform': 'rotate('+degree+'deg)'

And your call:

rotateMarker('markerOne', 45);

That's all.

I hope it could be helpful.


You did not state it in your question, but I am assuming that you want this rotation in relation to a line between point a and point b, which would be their path. In order to make a google svg icon that can be rotated, you will want to use the google symbol class object to define the properties of your marker symbol. This does not use a full .svg file, but only the d attribute of the path. Note that the google symbol class can only take one path per marker.

Additional attributes for color, stroke, width, opacity, etc. may be set after the marker has been created with javascript (updating the marker object properties directly), or with CSS (updating the marker properties by adding and removing classes).

As an example, the following will create an arrow marker that can be dragged, and it will be rotated around the point on the map that is the lat and long for the marker even after it is moved.


<body id="document_body" onload="init();">
  <div id="rotation_control">
    Heading&deg;<input id="rotation_value" type="number" size="3" value="0" onchange="setRotation();" />
  <div id="map_canvas"></div>

The CSS (yes,verbose... I hate ugly)

#document_body {
    border: 0;
    padding: 10px;
    font-family: Arial,sans-serif;
    font-size: 14px;
    font-weight: bold;
    color: #f0f9f9;
    text-align: center;
    text-shadow: 1px 1px 1px #000;
  #map_canvas, #rotation_control {
    margin: 1px;
    border:1px solid #000;
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
  #map_canvas { 
    width: 100%;
    height: 360px;
  #rotation_control { 
    width: auto;
  #rotation_value { 
    margin: 1px;
    border:1px solid #999;
    width: 60px;
    font-weight: bold;
    color: #00cc00;
    text-align: center;
    border-radius: 4px;

The Javascript (in plain vanilla flavor for understanding core concepts)

var map, arrow_marker, arrow_options;
var map_center = {lat:41.0, lng:-103.0};
var arrow_icon = {
  path: 'M -1.1500216e-4,0 C 0.281648,0 0.547084,-0.13447 0.718801,-0.36481 l 17.093151,-22.89064 c 0.125766,-0.16746 0.188044,-0.36854 0.188044,-0.56899 0,-0.19797 -0.06107,-0.39532 -0.182601,-0.56215 -0.245484,-0.33555 -0.678404,-0.46068 -1.057513,-0.30629 l -11.318243,4.60303 0,-26.97635 C 5.441639,-47.58228 5.035926,-48 4.534681,-48 l -9.06959,0 c -0.501246,0 -0.906959,0.41772 -0.906959,0.9338 l 0,26.97635 -11.317637,-4.60303 c -0.379109,-0.15439 -0.812031,-0.0286 -1.057515,0.30629 -0.245483,0.33492 -0.244275,0.79809 0.0055,1.13114 L -0.718973,-0.36481 C -0.547255,-0.13509 -0.281818,0 -5.7002158e-5,0 Z',
  strokeColor: 'black',
  strokeOpacity: 1,
  strokeWeight: 1,
  fillColor: '#fefe99',
  fillOpacity: 1,
  rotation: 0,
  scale: 1.0

function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: map_center,
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID
  arrow_options = {
    position: map_center,
    icon: arrow_icon,
    clickable: false,
    draggable: true,
    crossOnDrag: true,
    visible: true,
    animation: 0,
    title: 'I am a Draggable-Rotatable Marker!' 
  arrow_marker = new google.maps.Marker(arrow_options);

function setRotation(){
  var heading = parseInt(document.getElementById('rotation_value').value);
  if (isNaN(heading)) heading = 0;
  if (heading < 0) heading = 359;
  if (heading > 359) heading = 0;
  arrow_icon.rotation = heading;
  document.getElementById('rotation_value').value = heading;

And the best yet, doing it this way assures the marker is a Google MVC object, giving it all the additional methods provided by the MVC object.

If you must have multi-colored images as your marker, then creating a .png sprite sheet with a rendition of the image at all the angles you want it to be shown, and then problematically select the correct image to use based on the computed bearing between the two points you are using. However,this would not be an SVG image, but a regular marker image.

Hope this helps in making some decisions regarding your map markers.


This is how i implemented my image rotated, I considered the marker in the form of overlay and that overlay is position to the position, Below code will be added .

Without using any additional library it is rotated,And you need to workaround to add click events and mouse events for the overlay, not similar to marker click events.

With googleMap markers customization, there will be addition memory usage in the map. This will also reduce the memory consumption of custom markers in your map.

    <script type="text/javascript" src=""></script>
    <style>html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    #map_canvas {
        height: 100%;
    div.htmlMarker {
        color: red;
        cursor: pointer;

    <body onload="initialize()">
        <div id="map_canvas"></div>

    var overlay;

    function initialize() {
        var myLatLng = new google.maps.LatLng(40, -100);
        var mapOptions = {
            zoom: 10,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        var gmap = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

        function HTMLMarker(lat, lng, rotation) {
   = lat;
            this.lng = lng;
             this.rotation = rotation;
            this.pos = new google.maps.LatLng(lat, lng);

        HTMLMarker.prototype = new google.maps.OverlayView();
        HTMLMarker.prototype.onRemove = function () {}

        //Initilize your html element here
        HTMLMarker.prototype.onAdd = function () {
            div = document.createElement('DIV');
  'rotate('+this.rotation +'deg)';
  'rotate('+this.rotation +'deg)';
            div.className = "htmlMarker";
           //image source use your own image in src
            div.innerHTML = '<img src="prudvi.png" alt="Mountain View" style="width:25px;height:22px">' ;
            var panes = this.getPanes();

        HTMLMarker.prototype.draw = function () {
            var overlayProjection = this.getProjection();
            var position = overlayProjection.fromLatLngToDivPixel(this.pos);
            var panes = this.getPanes();
   = position.x + 'px';
   = position.y - 30 + 'px';

        //Added 50 marker with random latlng location and random rotation,
        for (i = 0; i < 50; i++) {
        var PoslatLng = new google.maps.LatLng( + Math.random() - 0.5, myLatLng.lng() + Math.random() - 0.5);
        var htmlMarker = new HTMLMarker( + Math.random() - 0.5,myLatLng.lng() + Math.random() - 0.5, Math.floor(Math.random() * 359));
    google.maps.event.addListener(htmlMarker, 'click', function() {

Nobody mentioned about using pre-rotated icons. Depending on your application, you could take one icon and rotate it +10 degrees, +20 degrees ... +350 degrees and instead of rotating marker itself, just assign different icon to it - one out of 36 if 10 degrees resolution is good enough. That's also very light on client's resources.

In the example below I generated 36 icons, every one of them is 10 degrees rotated. Their names are: icon0.png, icon10.png, icon20.png, ... icon340.png, icon350.png, icon360.png. The 0 and 360 are the very same icon (e.g symlink)

var rotation = 123 // degrees
var iconName = "icon" + (Math.round(rotation/10)*10).toString() + ".png"
var marker = new google.maps.Marker({
    icon: iconName

You could call the yourmarker.setIcon(canvas.toDataUrlOrSomeThig) every time the image changes. I don't see anything in the api reference for using the canvas element directly, except if you implement you own google.maps.OverlayView.

If you only want animation you could use a gif, and add the marker option optimized: false to it.


The idea is to first draw the rotated marker image on a hidden canvas.

Say, you have a hidden canvas:

<canvas id="carCanvas" width="50" height="50" style="display:none"></canvas>

Now you can do this:

function updateCarMarker(i,lat, lng, icon = "img/carIcon.png") {
    var latLong = new google.maps.LatLng(lat, lng);
    if (!carMarkers[i]){
        var carImage = new Image();
        carImage.onload = ()=>{
    } else {

function drawMovedCar(i,latLong,I){
    let m=carMarkers[i];
    let canvas = document.getElementById("carCanvas");
    let C = canvas.getContext('2d');
    if (m){
        var distance = google.maps.geometry.spherical.computeDistanceBetween(
                                                               m.getPosition(), latLong);
        var deg = (distance<2)?carMarkers[i].deg
                              :google.maps.geometry.spherical.computeHeading(m, latLong);
     } else {
        var deg=0;
        C.clearRect(0, 0, canvas.width, canvas.height);
        C.rotate(deg * Math.PI / 180);
    if (!m){
        m = new google.maps.Marker({
            position: latLong,
            map: map,
            icon: canvas.toDataURL("image/png",1)
        m.deg = deg;
        m.carImage = I;
    } else {

The above is my original code. I have left it intact so that you can see my other optimizations.


Using MarkerWithLabel Library, you can achieve that in such way:

var ico = document.createElement('img');
ico.src = 'ImageSource';
ico.setAttribute('style', 'transform:rotate('30deg);');
mapMarkers[0].labelContent = ico;
var icon = {
   path: aeroplanePath/image,
   fillColor: '#0000FF',
   fillOpacity: .6,
   anchor: new google.maps.Point(0,0),
   strokeWeight: 0,
   scale: 1,
   rotation: 180

var marker = new google.maps.Marker({
   position: positions[k],
   icon: icon,
   draggable: true,
   title: "BOING-707",    

I was able to solve this pretty easily but using the marker.icon.rotation option pointing to a custom symbol that uses the svg path syntax.

$scope.triangle = {
  path: 'M 0 0 L -35 -100 L 35 -100 z',
  fillColor: '#3884ff',
  fillOpacity: 0.7,
  scale: 1,
  strokeColor: '#356cde',
  rotation: 90,
  strokeWeight: 1


If using angular-google-maps it is trivial to bind a ui control to change the triangle.rotation.

Like I did with this slider.

<slider  ng-model="triangle.rotation" floor="0" ceiling="359" step="5" precsion="1"></slider>

But you could use a forum too.

here is my plunker


The easiest way may be to use the rotation property of google.maps.Symbol. Just set it as a property of your icon when creating or updating your marker:

new google.maps.Marker({
  position: map.getCenter(),
  icon: {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    scale: 7,
    rotation: 193
  map: map



I have found an easy way to rotate the png image marker for the google marker. Create an custom marker overriding google.maps.OverlayView and rotate the image simply with css/inline style

export const createCustomMarker = ({ OverlayView = google.maps.OverlayView, ...args }) => {

class GoogleMarker extends OverlayView {

    options: any = {};
    div: any = null;
    innerHtml: any = null;

    constructor(options) {
        this.options = options;

    createDiv() {
        const options = this.options;
        this.div = document.createElement('div'); = 'absolute';
        if (options.icon) {

    getInnerImageHtml(options) {
        const size = this.getSize(options);
        const label = this.options.label;
        const labelHtml = label ? `<span style="color:black;margin-left: -40px;width: 100px;text-align: center;display: block;font-weight:bold;">${label}</span>` : "";
        return `<img style="height:${size.height}px;width:${size.width}px" id="${ || ''}" src="${options.icon}">${labelHtml}`;

    addListeners() {
        const self = this;
        google.maps.event.addDomListener(this.div, 'click', event => {
            google.maps.event.trigger(self, 'click');

        this.div.onmouseenter = function () {
            google.maps.event.trigger(self, 'onmouseenter');

        this.div.onmouseover = function () {
            google.maps.event.trigger(self, 'onmouseover');

        this.div.onmouseleave = function () {
            google.maps.event.trigger(self, 'onmouseleave');

        this.div.onmouseout = function () {
            google.maps.event.trigger(self, 'onmouseout');

    appendDivToOverlay(appendDiv: any) {
        const panes: google.maps.MapPanes = this.getPanes();

    setRotation(degrees: number) {
        if (this.div) {
   = 'rotate(' + degrees + 'deg)';
        this.options.rotation = degrees;

    getRotation() {
        return this.options.rotation;

    setInnerHtml(html: string) {
        this.innerHtml = html;
        this.div.innerHTML = this.innerHtml;

    private positionDiv(div: any, options: any) {
        if (div != null) {
            const point = this.getProjection().fromLatLngToDivPixel(options.latlng);
            if (point) {
                const size = this.getSize(options);
                const anchor = options.anchor ? options.anchor : new google.maps.Point((size.width / 2), (size.height / 2))
                const leftAnchor = anchor.x;
                const topAnchor = anchor.y;
       = `${point.x - leftAnchor}px`;
       = `${point.y - topAnchor}px`;

    private getSize(options) {
        const size = options.size || { height: 52, width: 52 };
        return size;

    draw() {
        if (!this.div) {
        this.positionDiv(this.div, this.options);

    remove() {
        if (this.div) {
            this.div = null;

    setVisible(value: boolean) {
        if (this.div) {
  ["display"] = value ? "block" : "none";

    getVisible() {
        if (this.div) {
            return["display"] == "none";
        return false;

    setPosition(position) {
        this.options.latlng = position;
        this.infoOptions.latlng = position;
        this.positionDiv(this.div, this.options);

    getPosition() {
        return this.options.latlng;

    getDraggable() {
        return false;

    isHTML(html: string) {
        return /<([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)<\/\1>/.test(html);
return new GoogleMarker(args)


After creating this custom marker - Initialize the marker in the following way

import { createCarMarker } from "./marker.component"; // dynamic path to component

let marker = createCarMarker({
        id: id, // will add id to the parent container div
        latlng: new google.maps.LatLng(0, 0), // replace latitude-longitude with your values
        size: new google.maps.Size(52, 52), // replace the image size with your values
        rotation: markerData.direction, // Provide values in degrees
        icon: iconUrl, // Replace it with your image url
        label: markerLabel // Provide marker label. Optional field

Now simply rotate the marker using the following method

marker.setRotation(180); // You just need to call only this method every-time the degrees changes.

To listen the changes on the marker.

google.maps.event.addDomListener(marker, 'click', function (event) {


    google.maps.event.addListener(marker, 'onmouseenter', function (event) {


    google.maps.event.addListener(marker, 'onmouseleave', function (event) {


    google.maps.event.addListener(marker, 'onmouseover', function (event) {


    google.maps.event.addListener(marker, 'onmouseout', function (event) {


You can customize the listeners or add new/update in the custom marker class according to your requirement.


Assuming you only use that image within Google Maps, you can do the following

bearing = 20

document.querySelectorAll('img[src="/images/imageName"]').forEach((node) => {['transform'] = `rotate(${bearing}deg)`['webkitTransform'] = `rotate(${bearing}deg)`['MozTransform'] = `rotate(${bearing}deg)`['msTransform'] = `rotate(${bearing}deg)`['OTransform'] = `rotate(${bearing}deg)`

This reaches down the dom tree and sets the transform for the marker icon to rotate the degrees you want. The image imageName should be facing North

Not to sure if the webkit, Moz, ms and O version are needed but hey ??????????? cant hurt


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.