google-mapssvggoogle-maps-api-3google-maps-markersgoogle-maps-advanced-marker-element

Draw AdvancedMarkerElement on center of its position


I am drawing google.maps.markers.AdvancedMarkerElement's on a map.

I use them as handles/control points to change the path of a polyline.

They are drawn with a custom shape(basically a rectangle).

The issue is, that the marker is always above the position that it is bound to.

My code:

const parser = new DOMParser();
const pinSvg = parser.parseFromString(
        '<svg xmlns="http://www.w3.org/2000/svg" height="16px" viewBox="0 -960 960 960" width="16px" fill="#000" " ><path d="M214-74q-59.12 0-99.56-40.44Q74-154.88 74-214v-532q0-59.13 40.44-99.56Q154.88-886 214-886h532q59.13 0 99.56 40.44Q886-805.13 886-746v532q0 59.12-40.44 99.56Q805.13-74 746-74H214Z"/></svg>'
,
        "image/svg+xml"
      ).documentElement;

 let marker =
        new google.maps.marker.AdvancedMarkerElement({
          map: this.map as google.maps.Map,
          position: point.latLng,
          content: pinSvg,
          gmpDraggable: true,
          gmpClickable: true,
        });

The outcome:

Not properly centered AdvancedMarkerElement

As you can see the cross (added by google when hovering or grabbing the marker) is at the bottom of the marker. But I need the marker to be properly centered on top.

I tried changing the viewbox or x and y coordinates. Nothing helped.

It only distorted the shape.

Do you have any idea how I can fix this?


Solution

  • Warning : The SVG path you shared has syntax errors (one too many double quotes). Fix that first.

    There are 2 options.

    Option 1

    You can use the transform function of the SVG itself. Your SVG being 16x16, you will need to translate the Y axis by 8 so that it appears vertically centered.

    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -960 960 960" transform="translate(0 8)" fill="#000"><path d="M214-74q-59.12 0-99.56-40.44Q74-154.88 74-214v-532q0-59.13 40.44-99.56Q154.88-886 214-886h532q59.13 0 99.56 40.44Q886-805.13 886-746v532q0 59.12-40.44 99.56Q805.13-74 746-74H214Z"/></svg>
    

    Here is a working demo :

    async function initMap() {
    
      // Request needed libraries.
      const { Map } = await google.maps.importLibrary("maps");
      const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
      const center = {
        lat: 0,
        lng: 0
      }
      
      const map = new Map(document.getElementById("map"), {
        center: center,
        zoom: 14,
        mapId: "4504f8b37365c3d0",
      });
    
      const parser = new DOMParser();
      const pinSvg = parser.parseFromString(
        '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -960 960 960" transform="translate(0 8)" fill="#000"><path d="M214-74q-59.12 0-99.56-40.44Q74-154.88 74-214v-532q0-59.13 40.44-99.56Q154.88-886 214-886h532q59.13 0 99.56 40.44Q886-805.13 886-746v532q0 59.12-40.44 99.56Q805.13-74 746-74H214Z"/></svg>', "image/svg+xml"
      ).documentElement;
    
      let marker = new google.maps.marker.AdvancedMarkerElement({
        map: map,
        position: center,
        content: pinSvg
      });
    
      let defaultMarker = new google.maps.marker.AdvancedMarkerElement({
        map: map,
        position: center
      });
    }
    
    initMap();
    #map {
      height: 150px;
    }
    <div id="map"></div>
    
    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
            ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "weekly"});</script>

    Option 2

    Second option is to do the transform via CSS.

    Use marker.content.style.transform = 'translateY(8px)'

    or

    marker.content.style.transform = 'translateY(50%)'

    Here is the second working demo :

    async function initMap() {
    
      // Request needed libraries.
      const { Map } = await google.maps.importLibrary("maps");
      const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
      const center = {
        lat: 0,
        lng: 0
      }
      
      const map = new Map(document.getElementById("map"), {
        center: center,
        zoom: 14,
        mapId: "4504f8b37365c3d0",
      });
    
      const parser = new DOMParser();
      const pinSvg = parser.parseFromString(
        '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -960 960 960" fill="#000"><path d="M214-74q-59.12 0-99.56-40.44Q74-154.88 74-214v-532q0-59.13 40.44-99.56Q154.88-886 214-886h532q59.13 0 99.56 40.44Q886-805.13 886-746v532q0 59.12-40.44 99.56Q805.13-74 746-74H214Z"/></svg>', "image/svg+xml"
      ).documentElement;
    
      let marker = new google.maps.marker.AdvancedMarkerElement({
        map: map,
        position: center,
        content: pinSvg
      });
        
      marker.content.style.transform = 'translateY(50%)'
    
      let defaultMarker = new google.maps.marker.AdvancedMarkerElement({
        map: map,
        position: center
      });
    }
    
    initMap();
    #map {
      height: 150px;
    }
    <div id="map"></div>
    
    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
            ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "weekly"});</script>