【问题标题】:Accessing maps google maps object in react-google-maps library在 react-google-maps 库中访问地图 google maps 对象
【发布时间】:2020-11-30 04:09:23
【问题描述】:

在我的 react 应用程序中使用 react-google-maps 库,我试图在第 32 行访问谷歌地图对象调用构造函数,但我得到“谷歌未定义”错误。 这个库不公开地图对象,我如何访问谷歌对象?它也不包含在道具中

import React, { useState, useEffect } from 'react';
import flicker from '../assets/flicker.svg';
import axios from 'axios';
import { compose, withProps } from 'recompose';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from 'react-google-maps';

const MyMapComponent = compose(
  withProps({
    googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_API_KEY}&v=3.exp&libraries=geometry,drawing,places&callback=initMap`,
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap
)(props => {
  console.log(props.google);
  return (
    <GoogleMap defaultZoom={3} defaultCenter={{ lat: 46, lng: 2 }}>
      {props.datas.map(data => (
        <Marker
          key={data.countryInfo._id}
          position={{ lat: data.countryInfo.lat, lng: data.countryInfo.long }}
          defaultLabel={data.cases}
          icon={{
            url: flicker,
            size: new google.maps.Size(15, 25), ### HERE ###
          }}
        />
      ))}
    </GoogleMap>
  );
});

const CoronaMap = props => {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios
      .get('https://disease.sh/v3/covid-19/countries?yesterday=0&sort=cases')
      .then(res => setData(res.data));
  }, []);

  return <MyMapComponent datas={data} />;
};

export default CoronaMap;

但在文档中,可以访问 google 对象 https://prnt.sc/tx78tf

【问题讨论】:

    标签: reactjs google-maps google-maps-api-3 react-google-maps


    【解决方案1】:

    我无法最终复制这个问题。第 32 行在我这边正常工作,但是可以看到您需要在您提供的代码中修复的一些问题。

    1. 删除 googleMapURL 内 Google 地图脚本中的 &amp;callback=initMap,因为您的代码中没有 initMap 函数。

    2. 确保您没有在密钥中使用相同的值。看起来data.countryInfo._id 有两个null 值,这会在您的代码中引发警告。您也可以使用 index 来确保您的 key 的值是唯一的。您可以使用以下代码来做到这一点:

    {props.datas.map((data,index) => (
            <Marker
              key={index}
    
    1. Marker 的标签只接受字符串值,而且{data.cases} 的值似乎不是字符串。您需要将此值转换为字符串才能使用此数据。您可以使用{data.cases.toString()}{JSON.stringify(data.cases)} 来实现。

    这是sample code

    【讨论】:

    • 感谢您的回答,我通过添加窗口关键字“new window.google.maps.Size(15, 25)”解决了这个问题。你提供的东西也不起作用。这很奇怪:D
    猜你喜欢
    • 2021-07-20
    • 2018-02-26
    • 2020-02-22
    • 2018-02-19
    • 2011-09-24
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多