uiwjs / react-baidu-map

基于 React 封装的百度地图组件,支持 React Hook,帮助你轻松的接入地图到 React 项目中。
https://uiwjs.github.io/react-baidu-map
MIT License
225 stars 22 forks source link

BMap is not defined #111

Closed mcl950121 closed 3 years ago

mcl950121 commented 3 years ago

BMap is not defined

jaywcjlove commented 3 years ago

@mcl950121 APILoader 是去加载 百度地图 API,如果你在加载API 之前使用了 BMap 就会报错

import ReactDOM from 'react-dom';
import { Map, APILoader } from '@uiw/react-baidu-map';

const Demo = () => (
  <div style={{ width: '100%', height: '300px' }}>
    <APILoader akay="GTrnXa5hwXGwgQnTBG28SHBubErMKm3f">
      <Map />
    </APILoader>
  </div>
);
ReactDOM.render(<Demo />, _mount_);

上面代码改造一下,APILoader 组件会判断 百度API加载完成,再去渲染子组件

import ReactDOM from 'react-dom';
const CustomIcon = () => {
  const [position, setPosition] = useState({ lng: 121.466008, lat: 31.220001 });
  const icon = new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/fox.gif', new BMap.Size(300, 157));
  return (
    <>
      <button onClick={() => setPosition({lng: 121.545202, lat: 31.246679})}>设置 position</button>
      <Map zoom={13} center={{ lng: 121.460977, lat: 31.227906 }}>
        <Marker position={position} icon={icon} animation={2} />
      </Map>
    </>
  );
}

const Demo = () => (
  <div style={{ width: '100%', height: '350px' }}>
    <APILoader akay="GTrnXa5hwXGwgQnTBG28SHBubErMKm3f">
      <CustomIcon />
    </APILoader>
  </div>
);
ReactDOM.render(<Demo />, _mount_);
mcl950121 commented 3 years ago

可以了 感谢