开发者问题收集

在 UseEffect 钩子内部访问时出现 @react-google-maps/api“google 未定义”错误

2020-11-10
4185

我想做什么

  • 在地图上放置一个标记,并计算标记与地图上静态位置之间的距离。
  • 如果距离大于 1000 米,则显示地址不可用模式

问题描述

  • 无法在 UseEffect 中访问 google。
  • 我正确加载了脚本并遵循 文档
  • window.google 在 onMapClick 函数中可用,但在我的索引组件或 useEffect 钩子内的任何地方都不可用
  • 我如何访问它?其余一切正常
  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>
    </>
  );
}

2个回答

我还收到错误,说 google 未定义,所以一定是加载问题。 我在 doc 中找到了如何加载它,因此按照它来加载脚本,它对我有用。

之前:

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

之后:

const { isLoaded } = useJsApiLoader({
        id: "google-map-script",
        googleMapsApiKey: "API Key",
    });
Heymi
2023-03-16

打开你电脑的互联网连接...它一定会起作用

Jagannath
2022-01-02