2

what im trying to do

  • place a marker on the map and calculate the distance between the marker and a static location on the map.
  • if the distance is greater than 1000 metres then i display address not available modal

problem description

  • Unable to access google inside UseEffect .
  • I loaded the script properly and followed the documentation
  • window.google is available in the onMapClick function but not anywhere in my index component or inside the useEffect hook
  • How do i access it ? Everything else works fine
  Unhandled Runtime Error
ReferenceError: google is not defined
import React, { useRef, useState, useEffect, useCallback } from 'react';
import {
  GoogleMap,
  useLoadScript,
  Marker,
  InfoWindow,
  MarkerClusterer,
} from '@react-google-maps/api';
import '@reach/combobox/styles.css';
import usePlacesAutoComplete, {
  getGeocode,
  getLatLng,
} from 'use-places-autocomplete';
import getDistanceFromLatLonInKm from '../../utils/getDistanceFromLatLonInKm.js';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import { Circle } from '@react-google-maps/api';

const libraries = ['places', 'geometry'];
const mapContainerStyle = {
  width: '100%',
  height: '40vh',
};
const center = {
  lat: 25.33800452203996,
  lng: 55.393221974372864,
};
const options = {
  zoomControl: true,
};

const circleOptions = {
  strokeColor: '#00a3a6',
  strokeOpacity: 0.4,
  strokeWeight: 2,
  fillColor: '#00a3a6',
  fillOpacity: 0.1,
  clickable: false,
  draggable: false,
  editable: false,
  visible: true,
  radius: 1050,
  zIndex: 1,
};

const initialMarker = { lat: null, long: null };

export default function index() {
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
    libraries,
  });
  const [marker, setMarker] = useState(initialMarker);
  const [showModal, setShowModal] = useState(false);

  const handleModalClose = () => {
    setShowModal(false);
    setMarker(initialMarker);
  };

  const onMapClick = (event) => {
    setMarker({
      lat: event.latLng.lat(),
      lng: event.latLng.lng(),
    });
    console.log(window.google); //accessible here
  };

  const renderMap = () => {
    return (
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={14}
        options={options}
        center={center}
        onClick={onMapClick}>
        <Circle center={center} options={circleOptions} />
        {marker && <Marker position={{ lat: marker.lat, lng: marker.lng }} />}
      </GoogleMap>
    );
  };

  useEffect(() => {
    if (
      //cant access google here
      google.maps.geometry.spherical.computeDistanceBetween(
        new google.maps.LatLng(center.lat, center.lng),
        new google.maps.LatLng(marker.lat, marker.lng)
      ) > 1000
    ) {
      setShowModal(true);
    }
  }, [marker.lat]);

  if (loadError) return 'Error Loading Maps';
  if (!isLoaded) return 'Loading Maps';

  return (
    <>
      <div>{renderMap()}</div>
      <Modal
        show={showModal}
        onHide={handleModalClose}
        backdrop="static"
        keyboard={false}
        centered>
        <Modal.Header closeButton>
          <Modal.Title>Address is out of bounds</Modal.Title>
        </Modal.Header>
        <Modal.Body>Sorry ! We Dont Deliver Food In Your Area .</Modal.Body>
        <Modal.Footer>
          <Button onClick={handleModalClose}>Choose New Address</Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

  • If you are using typescript just install `@types/googlemaps` or add `/* global google */` to the top of the file I didnt try – Lashan Fernando Nov 10 '20 at 19:37
  • @LashanFernando thanks for the reply ! i'm not using typescript . – Mohamed Sauood Nov 11 '20 at 10:08
  • did u find solution ? – Sushilzzz May 07 '21 at 08:44
  • According to [docs](https://www.npmjs.com/package/@react-google-maps/api): "If you want to use `window.google` object, you need to extract `GoogleMap` in separate module, so it is lazy executed then `google-maps-api` script is loaded and executed by ``. If you try to use `window.google` before it is loaded it will be undefined and you'll get a TypeError." – CherryDT Jan 02 '22 at 10:59

2 Answers2

0

I was also getting error that google is not define so it must be loading issue. I found in the doc How it is being loaded there so followed it just for loading the script and it worked for me.

before:

const isLoaded = useLoadScript({
        googleMapsApiKey: "API Key",
    });

after:

const { isLoaded } = useJsApiLoader({
        id: "google-map-script",
        googleMapsApiKey: "API Key",
    });
Heymi
  • 1
  • 1
-11

Turn on the internet connection in your computer...it will definitely work