Home > Software design >  How to use svg icon as Marker on Google Maps
How to use svg icon as Marker on Google Maps

Time:05-18

I have this object set for Marker icon in React:

const icon = {
      path: "M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c- 
      1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",
      fillColor: "red",
      fillOpacity: 1,
      scale: 2,
      strokeColor: "red",
      strokeWeight: 1,
};

enter image description here

enter image description here

enter image description here

The markers do not point to the exact location only when I zoom in. I tried adding this in the icon object: anchor: new google.maps.Point(15, 42), , but it returns an error when I refresh the page: Uncaught ReferenceError: google is not defined. The actual location is on the right of Varzea (see picture #3)

CodePudding user response:

You are right, you need to define the anchor property. The easiest way is to place your SVG marker along with a standard marker at the same location and adjust accordingly. 15, 42 is obviously incorrect. Don't forget you are also using scale: 2 on the icon.

I get the best results by using new google.maps.Point(12.25,21.5)

function initialize() {

    const myLatLng = new google.maps.LatLng(0,0);
    const mapOptions = {
        zoom: 4,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    const map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
    const icon = {
      path: "M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",
      fillColor: "red",
      fillOpacity: 1,
      scale: 2,
      strokeColor: "red",
      strokeWeight: 1,
      anchor: new google.maps.Point(12.25,21.5)
    };

    const marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: icon
    });
    
    const marker2 = new google.maps.Marker({
        position: myLatLng,
        map: map
    });
}

initialize();
#map-canvas {
  height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Regarding the ReferenceError: google is not defined you will need to open another question and provide a Minimal, Reproducible Example that allows to reproduce the issue.

  • Related