When I call to google.maps.services, my map desappears

367 views Asked by At

I'm using ReactJS and react-google-maps/api to make my application that calls to my backend and google API.

I add a few markers to the map and when I click on them, I call the google API to get the details of that establishment according to its google ID.

But when I call the function getInfo that connects to the google API, my map disappears even though I receive the data from the api without problem and I can print it to console.

Here is the code of my markers and the call to getInfo.

import React, { useState, useEffect } from "react";

import { InfoWindow, Marker } from "@react-google-maps/api";
import { getInfo } from "../../helpers/googlePlaces";


export const MainMarkers = () => {

    const [activeMarker, setActiveMarker] = useState(null);
    const [markers, setMarkers] = useState([]);
    const [placeResult, setPlaceResult] = useState(null);

    useEffect(() => {
        fetch('https://localhost:7028/api/Coordinates/GetCoords')
          .then((response) => {
            return response.json()
          })
          .then((markers) => {
            setMarkers(markers)
          })
    }, []);

    const handleActiveMarker = (marker) => {
        if (marker === activeMarker) {
          return;
        }
        setActiveMarker(marker);
    };
    
    const callGoogle = (idGoogle) => {  
        setPlaceResult(getInfo(idGoogle));

        console.log('place:', placeResult)
    }


    return(
        <>
        {markers.map(({ id, idGoogle, latitud, longitud }) => (
            <Marker
              key={id}
              position={{lat: latitud, lng: longitud}}
              onClick={() => {handleActiveMarker(id); callGoogle(idGoogle) } }
            >
              {activeMarker === id ? (
                <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                  <div id="infowWindow">{idGoogle}</div>
                </InfoWindow>
              ) : null}
            </Marker>
          ))}    
        </>
    )
}

Here's the code of getInfo function.

/* global google */

function getInfo(idGoogle) {

    const service = new window.google.maps.places.PlacesService(document.getElementById('map'));
    let placeService = null;

    let request = {
        placeId: idGoogle,
        fields: ['name', 'formatted_address', 'rating',
          'website']
    };
  
    service.getDetails(request, callback);
        
    function callback(placeResult, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            console.log(placeResult);
            placeService = placeResult;

        } else {
            console.log('fail');
            placeService = 'fail';
        }
    }
    console.log('done')
    return placeService;
}

export {
    getInfo
}

If the function doesn't call to google API, the map doesn't disappear.

EDIT: The code of rendering the map:

export const MainMap = () => {

  const [center, setCenter] = useState();
  const [map, setMap] = useState(null);

  useEffect(() => {
    navigator?.geolocation.getCurrentPosition(
      ({ coords: { latitude: lat, longitude: lng } }) => {
        setCenter({ lat, lng });
      }
    );

  }, []);

  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: apiKey,
    libraries: libraries
    // ...otherOptions
  })

  const renderMap = () => {
    return(  
      <GoogleMap
        id="map"
        onLoad={map => {setMap(map)}}
        zoom={15}
        center={center}>
          
         <MainMarkers />    // this is the component that I show above

      </GoogleMap>
    )
  }
  if (loadError) {
    return <div>Map cannot be loaded right now, sorry.</div>
  }

  return isLoaded ? renderMap() : 'Loading...'
  
}

EDIT2: I tried to use ref as:

const mapa = useRef(null);


const callGoogle = (idGoogle) => {  
    const service = new window.google.maps.places.PlacesService(mapa);

    let request = {
        placeId: idGoogle,
        fields: ['name', 'formatted_address', 'rating',
          'website']
    };
  
    service.getDetails(request, callback);
        
    function callback(placeResult, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            console.log(placeResult);

        } else {
            console.log('fail');
        }
    }
    console.log('done')
  }

In GoogleMap from renderMap const i added ref={mapa} and in Marker i added onClick={() => callGoogle(idGoogle}

Now I get the error

Uncaught (in promise) TypeError: this.j.getElementsByTagName is not a function

0

There are 0 answers