简体   繁体   中英

Typescript error when implementing Marker in google-map-react api

I am using google map react api and trying to implement Markers but I am getting the following error:

Property 'current' does not exist on type '{ promise: Promise; resolver: undefined; rejector: undefined; }'.ts(2339)

I am using the solution presented in this thread: Adding Marker to Google Maps in google-map-react

const createControlledPromise = () => {
    let resolver;
    let rejector;
    const promise = new Promise((resolve, reject) => {
      resolver = resolve;
      rejector = reject;
    });
    return { promise, resolver, rejector };
  };

  const useMarker = ({ lat, lng }: any) => {
    const { promise: apiPromise, resolver: handleGoogleApiLoaded } = useMemo(
      createControlledPromise,
      [],
    ).current;

    useEffect(() => {
      let marker: { setMap: (arg0: null) => void };
      apiPromise.then((api: { map: any; maps: any }) => {
        const { map, maps } = api;
        marker = new maps.Marker({ position: { lat, lng }, map });
      });
      return () => {
        if (marker) {
          marker.setMap(null);
        }
      };
    }, [apiPromise, lat, lng]);
    return { handleGoogleApiLoaded };
  };

  const { handleGoogleApiLoaded } = useMarker({ lat, lng });

  return (
    <GoogleMapReact
      bootstrapURLKeys={{ key: `${process.env.REACT_APP_GOOGLE_MAPS_KEY}` }}
      center={mapCenter}
      defaultZoom={14}
      options={{ zoomControlOptions: { position: 7 } }}
      layerTypes={isTraffic ? ["TrafficLayer"] : []}
      yesIWantToUseGoogleMapApiInternals
      onGoogleApiLoaded={handleGoogleApiLoaded}
    >

2nd attempt:

 const onGoogleApiLoaded = ({ map, maps }: MapProps) =>
     renderMarkers({ map, maps });

   const renderMarkers = ({ map, maps }: MapProps) => {
   const marker = new maps.Marker({
       position: new maps.LatLngBounds(),
       map,
       title: "Hello World!",
    });
  };

return (
    <GoogleMapReact
      bootstrapURLKeys={{ key: `${process.env.REACT_APP_GOOGLE_MAPS_KEY}` }}
      center={mapCenter}
      defaultZoom={14}
      options={{ zoomControlOptions: { position: 7 } }}
      layerTypes={isTraffic ? ["TrafficLayer"] : []}
      yesIWantToUseGoogleMapApiInternals
      onGoogleApiLoaded={onGoogleApiLoaded}
    >

Like the error says, you're trying to access a current property that doesn't exist. You can use the values from useMemo through the variables you've destructured from the hook call, I'm not quite sure what you're trying to access with that prop.

The accepted answer in the thread you posted would probably be a better bet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM