首页 > 解决方案 > Google Maps Api:map() 函数不返回标记

问题描述

我使用地震 api通过“react-google-maps”(Doc )获取这个JsonData。但不知何故,标记没有出现,我不明白为什么。

const url =
  "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson";

const Map = () => {
  const defaultCoordinate = { lat: -0.8962, lng: -91.4445 }; 

  const getMarkers = () => {
    FetchEarthquakeData(url).then(result => {
      console.log(result.features);                     //LOG1
      result.features.map(earthquake => (
        console.log(earthquake),                        //LOG2
        <Marker
          key={earthquake.id}
          position={{
            lat: earthquake.geometry.coordinates[1],
            lng: earthquake.geometry.coordinates[0]
          }}
        />
      ));
    });
  };

  return (
    <GoogleMap defaultCenter={defaultCoordinate} defaultZoom={8}>
      {getMarkers()}
    </GoogleMap>
  );
};

const WrappedMap = withScriptjs(withGoogleMap(Map));

第一个 console.log (LOG1) 从 JsonData 返回数组。LOG 2 返回数组的每个对象。控制台中没有错误。

标签: javascriptreactjsasynchronousgoogle-maps-api-3

解决方案


您需要向(和回调)添加一条return语句。(但这不是这里唯一的问题,更多信息请参见下面的代码块)getMarkers.then

问题不是.map没有返回任何东西,而是getMarkers没有返回.map.

更新getMarkers

const getMarkers = () => {
  return FetchEarthquakeData(url).then(result => {
    console.log(result.features);                     //LOG1
    return result.features.map(earthquake => (
      console.log(earthquake),                        //LOG2
      <Marker
        key={earthquake.id}
        position={{
          lat: earthquake.geometry.coordinates[1],
          lng: earthquake.geometry.coordinates[0]
        }}
      />
    ));
  });
};

然而 getMarkers,它是一个异步函数,因此您不能直接在渲染函数(或功能组件的主体)中使用它的输出。相反,您应该将数据存储FetchEarthquakeData在状态变量中,然后在渲染时从状态中获取。您还可以在获取地震数据时添加加载状态。

例如:

const url =
  "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson";

const Map = () => {
  const defaultCoordinate = { lat: -0.8962, lng: -91.4445 };

  const [isLoading, setIsLoading] = React.useState(true);
  const [earthquakes, setEarthquakes] = React.useState([]);

  React.useEffect(() => {
    (async () => {
      setIsLoading(true);

      const result = await FetchEarthquakeData(url);
      console.log(result.features); // LOG1
      setEarthquakes(result.features);

      setIsLoading(false);
    })();
  }, []);

  if (isLoading) {
    return "loading...";
  }

  const markers = earthquakes.map(earthquake => (
    console.log(earthquake), // LOG2
    <Marker
      key={earthquake.id}
      position={{
        lat: earthquake.geometry.coordinates[1],
        lng: earthquake.geometry.coordinates[0]
      }}
    />
  ));

  return (
    <GoogleMap defaultCenter={defaultCoordinate} defaultZoom={8}>
      { markers }
    </GoogleMap>
  );
};

const WrappedMap = withScriptjs(withGoogleMap(Map));

注意这里我们把取数据逻辑和渲染逻辑分开,把取到的数据存放在组件的 state 中,然后在渲染的时候就从 state 中取数据。

此外,useEffect语法可能看起来有点奇怪,但这只是必要的,因为传递给的回调useEffect不能是异步的,所以我们创建了一个匿名异步函数并立即调用它。


推荐阅读