在react项目中调用百度地图API的BMap后报错解决方案

我这里是使用了react+typescript技术栈,在./public/index.html文件中引入百度地图项目的文件,就相当于是全局导入了,但是并不能直接使用相关的API。

<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=应用的key"></script>

需要在使用的文件中这样声明一下,然后就可以直接使用了。

const wins:any = window;
const BMap = wins.BMap;

使用例子:

class MapPage extends React.Component{
    
    
    componentDidMount(){
    
    
        let map = new BMap.Map("map-wrapper")
        map.addControl(new BMap.NavigationControl()) //开启平移缩放控件
        map.addControl( new BMap.ScaleControl() ) //开启比例尺
        
        let myCity = new BMap.LocalCity()
        myCity.get((result:any)=>{
    
    
            let myGeo = new BMap.Geocoder()
            myGeo.getPoint(result.name, function(point:any){
    
          
                if (point) {
    
    
                    map.centerAndZoom(point, 16)
                    map.addOverlay(new BMap.Marker(point))
                }
            }, 
            result.name)
        })
    }
    render(){
    
    
        return(
            <div>
	            // 需要给地图设置一个高度	
                <div id="map-wrapper" style={
    
    {
    
     height:"90vh" }}></div>
            </div>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/cautionHua/article/details/115912596