, and then you can use the BMap object introduced in the script to call various APIs ​ Problems I encountered: I am in the entry file——index.ht"/> , and then you can use the BMap object introduced in the script to call various APIs ​ Problems I encountered: I am in the entry file——index.ht">
search
HomeWeb Front-endJS TutorialWhat should I do if the react framework meets Baidu Maps?

The usage instructions of Baidu Map official document say this: Introduce , then you can use the BMap object introduced in the script to call various APIs
The problem I encountered:
After I introduced the above script in the entry file - index.html, when I accessed BMap in another JS file, an error was reported, prompting that BMap is not defined,
My ideas for solving the problem:
1. Go to github Find out if there is an open source SDK (if there is, install the dependency package through npm install, and then I can introduce BMap through require or import) ——Failed, there is no open source dependency package at all
2. Directly introduce the http address through require or import, such as require('http..../*The address of the above script*/')—— Failure, require or import can only directly introduce local resource files, and cannot directly introduce external
3. Bind BMap to the Window object to achieve cross-file access - success! (It can be implemented but not recommended, implemented for the sake of implementation)
4. Implement require access through the externals attribute in the webpack output object ——Success ! (Recommended practice)
Reproduce the problem:
My directory:
##My index.html looks like this:
/*剩下的部分自己想象*/<script></script>/*剩下的部分自己想象*/
My test/index.js looks like this:
import React from 'react'
 class Test extends React.Component{
componentDidMount () {   var map = new BMap.Map("allmap")
}
render () {return (<div></div>)   }
}
However, an error was reported when rendering Test:
A fact In front of you:
When building an application in a modular manner, you cannot directly access the variables in the entry file in the JS module, So How do we import the variables in the entry HTML file into a JS file?
#Or in this example, how can we obtain the BMap object in the script introduced in HTML in test/index.js?
Maybe many students will think: Just use export/import! But exporting variables directly in HTML files is obviously not a reasonable approach
Method 1: Save BMap with Window object Variables, realizing variable transfer between HTML files and JS files
在引入百度地图的脚本下再加入这一段脚本:
<script></script>
<script> window.BMap = BMap</script>

 

没错,就是把BMap对象保存到全局可访问的window对象中
当要使用BMap的时候这样用:
 BMap = window.BMap map =  BMap.Map("allmap");
例子如下:
import React from 'react'import ReactDOM from 'react-dom'class BaiduMap extends React.Component {
 
componentDidMount () {  var BMap = window.BMap  var map = new BMap.Map("allmap"); // 创建Map实例
  map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 初始化地图,设    置中心点坐标和地图级别
  map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
  map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
  map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放}
 
render () {  return (<div>
    <div></div>
</div>    )
  }
}
ReactDOM.render(<baidumap></baidumap>,
document.getElementById('root')
)

 

demo:

 


 

 
方法二.通过webpack的externals加载BMap使它可以通过require或import引入
在webpack.config.js中
module.exports = {/*此处省略了entry,output,modules等配置*/
  externals:{    'BMap':'BMap'
  },
}
在使用到BMap的时候,这样引入:
import BMap from 'BMap'var map = new BMap.Map("allmap"); // 创建Map实例//通过map调用API
例子:
import React from 'react'import ReactDOM from 'react-dom'import BMap from 'BMap'class BaiduMap extends React.Component {
 
componentDidMount () {  var map = new BMap.Map("allmap"); // 创建Map实例
  map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 初始化地图,设置中心点坐标和地图级别
  map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
  map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
  map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放}
 
render () {  return (<div>
      <div></div>
    </div>       )
       }
}
ReactDOM.render(  <baidumap></baidumap>,
  document.getElementById('root')
)

 

webpack的externals的具体作用我概括为两点:
1.写入externals中的依赖是不会被打包进最后的bundle里面的
2.虽然它不会被打包,但在程序运行的时候你仍然能通过模块化的方式去引入这些依赖,如commonJS,AMD,ES6的import等
(原文:Prevent bundling of certain imported packages and instead retrieve these external dependencies at runtime.)
 
demo同上:

 

百度地图新手(尤其是用react的)容易犯的错误及其解决方式:
1.忘记写
这个元素(id不一定要是allmap,只要和 new BMap.map(参数)里的字符串参数相同便可)
然后控制台就会报:TypeError: Cannot read property 'gc' of undefined的错误
解决方法:记得写
 
2.你写入了
,但还是报了TypeError: Cannot read property 'gc' of undefined的错误,你可能犯了一个原生JS码农不太可能会犯但是react码农可能会犯的错误:你
渲染前就执行了 var map = new BMap.Map("allmap");这一行代码
例如:
render () {   var map = new BMap.Map("allmap"); // 创建Map实例
   return (<div></div>) )
}

 

解决办法:在渲染
后才执行var map = new BMap.Map("allmap"); 例如将初始化map的代码放入组件类的
componentDidMount ()钩子函数中(这个函数将在组件被初次渲染完毕后调用)
例如:
class BaiduMap extends React.Component {
componentDidMount () {    var map = new BMap.Map("allmap"); // 创建Map实例}
render () {    return <div></div> )
}
3.你写入了
,控制台也没有报错,但是你就是看!不!到!地!图!
这多半是你没有给
加上宽高,百度地图的API是不会给你的div加宽高的,所以height默认是0就是0
解决方法:给目标地图div加上宽高(严格地说是高,宽默认为width:auto)
render () {return <div></div>
}
 
为此,我写了一封反馈的信件给百度地图的工作者们,目前在等待回应中(希望能有所回应吧)

 

以下为详细内容:
 
亲爱的百度地图开发者您好,作为一名react框架开发者,我在入门百度地图API时遇到困难——我不知道如何在模块化JS中使用BMap的API(问题现已解决)。因为你们只提供了原生JS下的入门指导,而没有任何关于模块化JS编程下的指导内容。这对于一些框架新手来说确实有些难以下手
 
我遇到的问题是:在引入携带AK的script的前提下,在一个JS模块文件(不是入口文件)中使用BMap报错:"error! BMap is not defined!"
 
我的解决法是通过在Webpack输出对象中的externals属性中加入BMap:"BMap",然后通过在对后在对应的JS页面中通过Window.BMap取得。
 
希望你们能够提供更为详细的操作指导,例如webpack下BMap的用法。这将让你们的产品变得更好。
 
以上 —— 某个爱好javaScript的大二学生

 

The above is the detailed content of What should I do if the react framework meets Baidu Maps?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool