Set the anchor of the Marker

3.1k views Asked by At

We are trying to use a custom icon for our marker using react-google-maps.

It is working, however the "anchor" of the icon appears to default to the top left of the pin (0,0) which does not work with our icon.

I can see that using the google-maps-api directly there is a .Point:

anchor: new google.maps.Point(17, 34)

But we can't see how to set this within the react-google-maps components.

Here is our code:

const icon = {
  path: 'M32,0C20.8,0...',
  fillColor: '#444',
  fillOpacity: 1,
  strokeWeight: 0,
  scale: 0.75
};

....

<Marker position={marker.position} key={index} icon={icon} />

Ideally there would be some sort of anchor key we can set directly in our Icon object.

Any help would be greatly appreciated.

3

There are 3 answers

1
Bulut Kartal On

this usage example should work for you.

var anchor = new google.maps.MarkerImage('/xxx/images/anchor.png',
                new google.maps.Size(34, 34),
                new google.maps.Point(0, 0),
                new google.maps.Point(17, 17));
1
Yury Volkov On

In fact you can use new google.maps.Point(), it is the ESLint that does not know where google comes from.

You can disable ESLint by adding the following line to the top of your file:

/*global google*/

(original source: https://github.com/tomchentw/react-google-maps/issues/434)

0
Temba On

As suggested by Mel Macaluso, the simplest solution is to use the window object as follows:

anchor: new window.google.maps.Point(17, 34)

For anyone still having issues creating a custom marker from scratch using the react-google-maps package, try specifying the scale and fillColor as well.

The example below is from the official Google Maps API documentation, with one change which is the use of the window object to create the anchor:

const svgMarker = {
    path: "M10.453 14.016l6.563-6.609-1.406-1.406-5.156 5.203-2.063-2.109-1.406 1.406zM12 2.016q2.906 0 4.945 2.039t2.039 4.945q0 1.453-0.727 3.328t-1.758 3.516-2.039 3.070-1.711 2.273l-0.75 0.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.906 2.039-4.945t4.945-2.039z",
    fillColor: "blue",
    fillOpacity: 0.6,
    strokeWeight: 0,
    rotation: 0,
    scale: 2,
    anchor: new window.google.maps.Point(15, 30),
  };