Google maps addListener using React

Asked

Viewed 39 times

-1

I need to add the dragend event to get the center of the map

google.maps.event.addListener(map, 'dragend', function(evt) {
        console.log(map.getCenter());
});

however do not know how to make this addition, below follows the complete code that I use to create the map:

import React, { useEffect, useRef, useState } from 'react';

export default function Map({ options, onMount, className, onMountProps }) {
  const ref = useRef();
  const [map, setMap] = useState();

  useEffect(() => {
    function onLoad() {
      if (window.google) {
        setMap(new window.google.maps.Map(ref.current, options));
      }
    }

    onLoad();
  }, [options]);

  if (map && typeof onMount === `function`) onMount(map, onMountProps);

  return (
    <div
      style={{
        height: `400px`,
        margin: `0`,
        borderRadius: `4px`,
        border: `1px solid #ccc`,
      }}
      {...{ ref, className }}
    />
  );
}

Map.defaultProps = {
  options: {
    zoom: 10,
    minZoom: 10,
    maxZoom: 10,
    mapTypeControl: false,
    streetViewControl: false,
    rotateControl: false,
    fullscreenControl: false,
    zoomControl: false,
    center: { lat: 48, lng: 8 },
  },
};

1 answer

0


The following code from your example creates a map instance

var map = new window.google.maps.Map(ref.current, options)
setMap(map)
...

Refer to the object created by this call, and pass it in the parameter map.

google.maps.event.addListener(map, 'dragend', function(evt) {
        console.log(map.getCenter());
});
  • I tried ref.google.maps.event.addListener... But returns that there is no google parameter

  • I’ll edit the example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.