在 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);
- Windows.lat=r.point.lat; //Windows.lat 是在其他页面设置的全局变量
- Windows.lng=r.point.lng; //Windows.lng 是在其他页面设置的全局变量
- }
- else {
- alert('failed'+this.getStatus());
- }
- },{enableHighAccuracy: true});
- </script>
- </HTML>
在其它页面想要获取到这个地理位置的信息从而进行处理
可以采用全局变量的方式, 因为放在 react 的 HTML 和其他 JS 文件是同时执行的, 所以在其他页面请求的时候可能获取不到值, 所以用延时器的方式能够获取到
- Windows.lat=undefined;
- Windows.lng=undefined;
- class PunchCard extends Component{
- componentDidMount(){ // 获取两个值放在这个生命周期中, 利用延时器就可以取到值
- setTimeout(() => {
- console.log(Windows.lat);
- console.log(Windows.lng);
- },2000);
- }
- }
- export default PunchCard;
来源: http://www.jianshu.com/p/c41c828ea422