首页 > 解决方案 > react-google-maps 街景中的空白屏幕

问题描述

大约 50% 的时间里,StreetViewPanorama 会根据坐标显示为空白屏幕。在我决定显示街景之前,有没有办法检查屏幕是否会显示为空白?如果可以,那么我只想显示常规地图

const StreetView = withScriptjs(
  withGoogleMap(props => {
    const { coordinates, address, city, state, zip } = props;
    return (
      <GoogleMap
        defaultZoom={14}
        defaultCenter={{
          lat: coordinates[1],
          lng: coordinates[0],
        }}
      >
        <StreetViewPanorama
          defaultPosition={{
            lat: coordinates[1],
            lng: coordinates[0],
          }}
          visible
        />
      </GoogleMap>
    );
  }),
);
export default props => {
  return (
    <StreetView
      {...props}
      googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&libraries=visualization`}
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: `800px` }} />}
      mapElement={<div style={{ height: `100%` }} />}
    />
  );
};

标签: reactjsreact-google-maps

解决方案


Google 有一个端点来检查有效坐标。如果街景视图不存在,您可以使用三元组检查状态并呈现标记。

const StreetView = withScriptjs(
  withGoogleMap(props => {
    const { coordinates, address, city, state, zip } = props;
    const [streetView, setStreetView] = useState(null);
    axios
      .get(
        `https://maps.googleapis.com/maps/api/streetview/metadata?key=${GOOGLE_API_KEY}&location=${
          coordinates[1]
        },${coordinates[0]}`,
      )
      .then(resp => setStreetView(resp.data.status));
    return (
      <GoogleMap
        defaultZoom={14}
        defaultCenter={{
          lat: coordinates[1],
          lng: coordinates[0],
        }}
      >
        {streetView === 'OK' ? (
          <StreetViewPanorama
            defaultPosition={{
              lat: coordinates[1],
              lng: coordinates[0],
            }}
            visible
          />
        ) : (
          <></>
        )}
      </GoogleMap>
    );
  }),
);
export default props => {
  return (
    <StreetView
      {...props}
      googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&libraries=visualization`}
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: `800px` }} />}
      mapElement={<div style={{ height: `100%` }} />}
    />
  );
};

推荐阅读