Nextjs React 使用谷歌地图js api

701 阅读1分钟
//1.安装谷歌地图依赖
yarn add @react-google-maps/api

// 2.新建Map.tsx文件
import { GoogleMap, MarkerF, useJsApiLoader } from '@react-google-maps/api';
import { Spin } from 'antd';

const containerStyle = {
  width: '100%',
  height: '100%',
};

const center = {
  lat: 40,
  lng: -74,
};

function Map() {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: '谷歌key',
  });

  return !!isLoaded ? (
    <GoogleMap mapContainerStyle={containerStyle} center={center} zoom={17}>
      <MarkerF
        position={center}
        title="marker title"
      />
    </GoogleMap>
  ) : (
    <Spin size="large" />
  );
}

export default Map;

//3.在page组件动态引入Map.tsx
import dynamic from 'next/dynamic';
const GoogleMap = dynamic(() => import('@/Components/Map'), { ssr: false });
<div className={styles.map}>
  <GoogleMap />
</div>