score:0

to achieve your use case, in your parent component, you need to use a handlechangecenter function that will set the newvalue of your center and marker then you will pass an onchange parameter to your child component which calls the handlechangecenter function.

in your child component, instead of ondrag function of <googlemap/> object , you can use the ondragend and ondragend, you will call a handlechange function that gets the current center coordinate of the map on dragend and it will pass the new value to the props of the onchange changing the state of your center and marker.

here's a sample code and a code snippet below:

parent.js

import react, { usestate, useeffect } from 'react';
import map from './map';
export default function parent() {
const [mapcenter, setmapcenter] = usestate(undefined); 
    const [markerposition, setmarkerposition] = usestate(undefined);

    function handlechangecenter(newvalue) {
      setmapcenter(newvalue);
      setmarkerposition(newvalue)
    }


    useeffect(()=>navigator.geolocation.getcurrentposition(position => 
        {
            setmapcenter({lat:position.coords.latitude, lng:position.coords.longitude})
            setmarkerposition({lat:position.coords.latitude, lng:position.coords.longitude})
        }
        ),[])
 return(
        <div>
            { mapcenter && <map mapcenter={mapcenter}  markerposition={markerposition}  onchange={handlechangecenter} />}

        </div>
    )
}

map.js

import react from 'react';
import { googlemap, marker, withgooglemap } from 'react-google-maps';

export default function map(props) {
  let mapref;
  function handlechange() {
    // here, we invoke the callback with the new value
    const newcenter = mapref.getcenter().tojson();
    console.log(newcenter);
    props.onchange(newcenter);
  }

  const wrappedmap = withgooglemap(() => (
    <googlemap
      ref={(ref) => (mapref = ref)}
      center={props.mapcenter}
      zoom={16}
      ondragend={handlechange}
    >
      <marker position={props.markerposition} draggable={false} />
    </googlemap>
  ));

  return (
    <div style={{ height: '50vh', width: '50vh' }}>
      <wrappedmap
        loadingelement={<div style={{ height: '100%' }} />}
        containerelement={<div id="map" style={{ height: '100%' }} />}
        mapelement={<div style={{ height: '100%' }} />}
      />
    </div>
  );
}

Related Query

More Query from same tag