reactjs React谷歌MapAPI(参考错误:谷歌没有定义)

juzqafwq  于 2023-03-08  发布在  React
关注(0)|答案(5)|浏览(174)

我正在使用react-google-maps/api节点模块。我需要将zoomControlOptions的值设置为TOP_LEFT,但我最终得到了这个错误Uncaught ReferenceError: google is not defined。下面是link到repo的代码。
我在这里得到了错误

const options = {
  zoomControl: true,
  mapTypeControl: false,
  minZoom: 2,
  streetViewControl: false,
  zoomControlOptions: {
    position: google.maps.ControlPosition.TOP_LEFT, // google is undefined here
  },
};

请帮助我:)

ccgok5k5

ccgok5k51#

尝试像这样显式定义google变量:
const google = window.google;
此外,您还可以读出this答案

2hh7jdfx

2hh7jdfx2#

发生这种情况是因为您在加载GoogleMap之前对其进行了渲染。

soat7uwm

soat7uwm3#

尝试在组件内部定义“选项”并添加“窗口,”例如

position: window.google.maps.ControlPosition.TOP_LEFT

你也可以只输入一个数字

BOTTOM: 11
BOTTOM_CENTER: 11
BOTTOM_LEFT: 10
BOTTOM_RIGHT: 12
CENTER: 13
LEFT: 5
LEFT_BOTTOM: 6
LEFT_CENTER: 4
LEFT_TOP: 5
RIGHT: 7
RIGHT_BOTTOM: 9
RIGHT_CENTER: 8
RIGHT_TOP: 7
TOP: 2
TOP_CENTER: 2
TOP_LEFT: 1
TOP_RIGHT: 3
vm0i2vca

vm0i2vca4#

在React with googleapi中加载Map和标记

import React from 'react'

const loadScript = (src) =>
new Promise((resolve, reject) => {
  if (document.querySelector(`script[src="${src}"`)) return resolve()
  const script = document.createElement('script')
  script.src = src
  script.onload = () => resolve()
  script.onerror = (err) => reject(err)
  document.body.appendChild(script)
})

const MyMapComponent = ({center, zoom, marker}) => {
  const ref = React.useRef();
  const src=`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_KEY}&callback=initMap`
  
  loadScript(src)
    .then(() => {
      /*global google*/
      // console.log("Load script google: ", google)
    })
    .catch(console.error)
    React.useEffect(() => {
      const map = new window.google.maps.Map(ref.current, {
        center,
        zoom,
      });
        new google.maps.Marker({
          position: {  
             lat: -15.770,
             lng: -44.233
          },
          map,
          icon: "https://yourlovedIcon.png",            })
      ))
    });

  return <div ref={ref} id="map" style={{height: '100vh', width: '50vh'}}/>;
}

function Maps() {
 
  const center = { 
    lat: -15.770,
    lng: -44.233 };
  const zoom = 10
   
  return (
          <MyMapComponent 
          center={center}
          zoom={zoom}
          marker={center}
          />
)
}

export default Maps

如果您想使用自定义API从互联网获取坐标:

import React from 'react'
import axios from 'axios';

const loadScript = (src) =>
new Promise((resolve, reject) => {
  if (document.querySelector(`script[src="${src}"`)) return resolve()
  const script = document.createElement('script')
  script.src = src
  script.onload = () => resolve()
  script.onerror = (err) => reject(err)
  document.body.appendChild(script)
})

const MyMapComponent = ({center, zoom, marker}) => {
  const ref = React.useRef();
  const src=`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_KEY}&callback=initMap`
  
  loadScript(src)
    .then(() => {
      /*global google*/
      // console.log("Load script google: ", google)
    })
    .catch(console.error)
    React.useEffect(() => {
      const map = new window.google.maps.Map(ref.current, {
        center,
        zoom,
      });
      marker.features.map(selectedData => (
        new google.maps.Marker({
          position: {  
            lat: selectedData.coordinates[0],
            lng: selectedData.coordinates[1]
          },
          map,
          icon: "https://yourlovedIcon.png",
        })
      ))
    });

  return <div ref={ref} id="map" style={{height: '100vh', width: '50vh'}}/>;
}

function Maps() {
  const [data, setData] = React.useState('');

  React.useEffect(() => {
    async function fetchData() {
      const response = await axios.get("https:\\YOURAPI.LOAD")
      setData(response.data)
    }
    fetchData();
  },[])
  
  const center = { 
    lat: -15.770,
    lng: -44.233 };
  const zoom = 10
    
  return data && 
          <MyMapComponent 
          center={center}
          zoom={zoom}
          marker={data}
          />
}

export default Maps
z9zf31ra

z9zf31ra5#

您可以尝试这样做,特别是使用next.js

zoomControlOptions: {
   position:
     typeof google !== "undefined"
     ? google.maps.ControlPosition.TOP_RIGHT
     : null,
}

相关问题