react-qmap和better-react-qmap的区别
- react-qmap的作者固定了腾讯地图的版本号,仅仅支持传入一个KEY值。因此我们在使用react-qmap时候,无法使用高级版本的功能和地图的插件功能。
- better-react-qmap为了解决react-qmap这个问题,使用apiVersonSrc将key值替换为腾讯API中JS的src,这样就可以用户自定义版本号了。
在react中使用腾讯地图
如何在react中使用腾讯地图?
- 常用的是在index.html中引入腾讯地图APIScript,然后在jsx里使用window.qq.maps调用;
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
- 第二种是异步加载Javascript(better-react-qmap实现原理)
function init() {
var myLatlng = new qq.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: qq.maps.MapTypeId.ROADMAP
}
var map = new qq.maps.Map(document.getElementById("container"), myOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&callback=init";
document.body.appendChild(script);
}
window.onload = loadScript;
使用方法
better-react-qmap github地址请点击这里
安装
npm install better-react-qmap
使用
import ReactQMap from 'better-react-qmap';
<ReactQMap
center={{ latitude: 30.53786, longitude: 104.07265 }}
initialOptions={{ zoomControl: true, mapTypeControl: true }}
apiVersonSrc='https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77'
style={{ height: 300 }} // 高度和宽度默认占父元素的100%
/>
ps:正在做腾讯地图相关的小伙伴赶紧行动吧~