Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-maps-markers

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.


Solution

  • 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);                   
    });