Muneeb
Muneeb

Reputation: 13

Is there a way to add DOM element as marker for google map js api

I was able to find an archived library with "RichMarker.js" which solves my problem but is there any new or better solution to this problem.

What I am trying to do

Marker Image

I need to display different type of info boxes for each of the semi-circle when clicked and the data in the marker is dynamic. Any help would be appreciated.

Upvotes: 0

Views: 701

Answers (2)

PaulCrp
PaulCrp

Reputation: 978

Use .svg

To personalize at best custom markers with dynamic shape/color/textContent... you can draw .svg object in javascript (see this or this).

After, you just need to set it like an image

iconForMarker = {url: iconSvg, size:new google.maps.Size(20, 20)};
let marker = new google.maps.Marker({
    position: latLng,
    map: gMap,
    icon: iconForMarker,
    // optimized false only if you have 200 or more markers  
    optimized: false
 });

You can update your image at anytime by doing

newIconForMarker = {url: newIconSvg, size:new google.maps.Size(20, 20)};
marker.setOptions({'icon':newIconForMarker });

Use canvas

You can also use 2d canvas (see this post from stackexchange)

let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
context.canvas.width = 38 * scale;
context.canvas.height = 46 * scale;
let sources = {
    pin: createPin(colorPin, scale),
    photo: dataPhoto                
};
loadImages(sources, function(images) {
    context.drawImage(images.pin, 0, 0);
    context.drawImage(images.photo, 5 * scale, 3 * scale);
    // creating a marker
    let marker = new google.maps.Marker({
        position: latlng,
        map: null,
        icon: canvas.toDataURL()
    });
    callback(marker);                   
});

Upvotes: 3

Sakops
Sakops

Reputation: 19

This is one of the solutions I was able to dig out on google. Fredik title's approach. It uses jQuery, but I think your could rewrite it as js

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

    if (!this.hovercardInitialized) {

        var markerInDOM = $('div[title="' + this.title + '"]').get(0);

        // do whatever you want with the DOM element

        this.hovercardInitialized = true;
    }

});

Upvotes: -1

Related Questions