美文网首页程序员
React项目如何利用百度地图API获取地理位置

React项目如何利用百度地图API获取地理位置

作者: 废柴码农 | 来源:发表于2019-01-06 16:43 被阅读1次

在public文件夹下找到index.html,然后加入下面的代码

<html>
<head>
     <meta http-equiv="Access-Control-Allow-Origin" content="*"/>
</head> 
<body>
</body>
<script src="http://api.map.baidu.com/api?v=2.0&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa">//ak后面是你自己的apikey
    </script>
    <script>
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          var mk = new BMap.Marker(r.point);
          console.log(r.point);
          window.lat=r.point.lat;   //window.lat是在其他页面设置的全局变量
          window.lng=r.point.lng;   //window.lng是在其他页面设置的全局变量
        }
        else {
          alert('failed'+this.getStatus());
        }        
      },{enableHighAccuracy: true});
    </script> 
</html>

在其它页面想要获取到这个地理位置的信息从而进行处理

可以采用全局变量的方式,因为放在react的html和其他js文件是同时执行的,所以在其他页面请求的时候可能获取不到值,所以用延时器的方式能够获取到
window.lat=undefined;
window.lng=undefined;
class PunchCard extends Component{
componentDidMount(){ //获取两个值放在这个生命周期中,利用延时器就可以取到值
    setTimeout(() => {
            console.log(window.lat);
            console.log(window.lng);
        },2000); 
}
}
export default PunchCard;

相关文章

网友评论

    本文标题:React项目如何利用百度地图API获取地理位置

    本文链接:https://www.haomeiwen.com/subject/yubsrqtx.html