next.js 使用百度地图

使用 React-BMapGL

安装

npm install react-bmapgl --save

新建一个页面 map.tsx

//map.tsx
import React from 'react';
import { Map, Marker, MapApiLoaderHOC } from 'react-bmapgl';

class BaiduMap extends React.Component {
    render() {
        return (
            <Map
                style={{ height: 356 }}
                center={new BMapGL.Point(xxxx, xxxx)}
                zoom={12}
                enableScrollWheelZoom={true}
            >
                <Marker
                    position={new BMapGL.Point(xxxx, xxxxx)}
                />
            </Map >
        )
    }
}
export default MapApiLoaderHOC({ak:'申请的密钥' })(BaiduMap) 

要使用的页面:

//about.tsx
import * as React from 'react';
import dynamic from 'next/dynamic';
// 百度地图要使用windows对象,所以用dynamic
const BaiduMap = dynamic(import('./map'),{ssr:false});

function About() {
	return{
		<div>
			<div className={styles.rightContent}>
                <BaiduMap />
            </div>
		</div>
	}
}
export default About;

2022-09-15更新
这个方法 会导致next打包 报错window is not defined
那就直接简单粗暴

next.js 使用百度地图_第1张图片
next.js 使用百度地图_第2张图片

现在执行 npm run build 就不会报错了

你可能感兴趣的:(javascript,react.js,typescript)