Google maps api 3 在不使用谷歌地图的情况下渲染谷歌地图

Google maps api 3 在不使用谷歌地图的情况下渲染谷歌地图,google-maps-api-3,reactjs,Google Maps Api 3,Reactjs,是否有人能够使用React而不是React google地图插件渲染google地图?我正在尝试这样的事情: var MapTab = React.createClass({ render: function() { return <div className="map-container"> <div id='map' ></div> </div> }, componentDidMount: functi

是否有人能够使用React而不是React google地图插件渲染google地图?我正在尝试这样的事情:

var MapTab = React.createClass({

render: function() {

    return  <div className="map-container">
       <div id='map' ></div>
     </div>

},

componentDidMount: function(){

        console.log("Hello")



window.onload = function(){
    (function initMap() {
        var markers = [];
        var geocoder = new google.maps.Geocoder();

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: {lat: 37.7749300, lng: -122.4194200}
        });
    })(); 
}


}// end of cdm;
}); 
module.exports = MapTab;
var-MapTab=React.createClass({
render:function(){
返回
},
componentDidMount:function(){
log(“你好”)
window.onload=函数(){
(函数initMap(){
var标记=[];
var geocoder=new google.maps.geocoder();
var map=new google.maps.map(document.getElementById('map'){
缩放:12,
中心:{lat:37.7749300,lng:-122.4194200}
});
})(); 
}
}//清洁发展机制结束;
}); 
module.exports=MapTab;

我试过的都没用。我也尝试过使用refs捕捉地图,但也没有渲染地图。我已经将GoogleMaps脚本也放在了标题中(带有密钥),并且已经验证了密钥在一个vanilla js项目中是有效的

摆脱
window.onload
。当调用
componentDidMount
方法时,窗口已经加载,因此您的
initMap()
函数永远不会启动。

您似乎还不熟悉React组件的生命周期

或者:(这有react方法执行顺序表)

实际上,在组件didmount()中(“DID mount”表示元素已经在页面上,因此您可以开始将事件绑定到它)

React组件的想法很有趣,所以我们不需要使用javascript的“window.onload()”或jQuery的“$(document.ready()”

因此,您的代码可以修改如下:

render: function() {
    return  <div className="map-container">
       <div id='map' ></div>
     </div>
},

componentDidMount: function(){

    console.log("Hello")

    var markers = [];
    var geocoder = new google.maps.Geocoder();

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: {lat: 37.7749300, lng: -122.4194200}
    });

}// end of cdm;
render:function(){
返回
},
componentDidMount:function(){
log(“你好”)
var标记=[];
var geocoder=new google.maps.geocoder();
var map=new google.maps.map(document.getElementById('map'){
缩放:12,
中心:{lat:37.7749300,lng:-122.4194200}
});
}//清洁发展机制结束;

PS:此外,为了使贴图显示,您需要正确设置贴图容器和贴图的样式(需要以像素为单位的高度,“0 px宽度”的情况下,可能也需要将宽度设置为px或100%)不过,您可以随意设置它们的样式!

使用componentDidMount,您知道map container div已经加载,但是您不能保证外部maps api已经加载。Google为您提供了提供回调函数的选项(在其示例中为initMap())

&callback=initMap

现在,您可以按照以下步骤进行操作,在地图组件安装完成后,您可以:

  • window.initMap=this.initMap使initMap from react可用于Google maps的回调
  • 使用initMap参数加载google maps JS
  • 在组件中的this.initMap中,您可以执行映射操作,因为现在您知道已经加载了容器和Google API

    const React = require('react')
    const PropTypes = require('prop-types')
    import Reflux from 'reflux'
    const Radium = require('radium')
    
    class Map extends Reflux.Component {
    
        constructor(props) {
            super(props)
            this.loadJS = this.loadJS.bind(this)
            this.initMap = this.initMap.bind(this)
        }
    
        componentDidMount() {
            window.initMap = this.initMap;
            if (typeof google === 'object' && typeof google.maps === 'object') {
                this.initMap()
            } else {
                this.loadJS('https://maps.googleapis.com/maps/api/js?key=<API_KEY>&callback=initMap')   
            }
        }
    
        // https://github.com/filamentgroup/loadJS/blob/master/loadJS.js
        loadJS(src) {
            var ref = window.document.getElementsByTagName("script")[0];
            var script = window.document.createElement("script");
            script.src = src;
            script.async = true;
            ref.parentNode.insertBefore(script, ref);
        }
    
        initMap() {
            var map = new google.maps.Map(this.refs.map, {
              center: {lat: -34.397, lng: 150.644},
              zoom: 8
            })
        }
    
        render() {
            return (<div ref='map'></div>)
        }
    
    }
    module.exports = Radium(Map)
    
    const React=require('React'))
    const-PropTypes=require('prop-types')
    从“回流”导入回流
    常数镭=需要(‘镭’)
    类映射扩展了.Component{
    建造师(道具){
    超级(道具)
    this.loadJS=this.loadJS.bind(this)
    this.initMap=this.initMap.bind(this)
    }
    componentDidMount(){
    window.initMap=this.initMap;
    if(typeof google=='object'&&typeof google.maps=='object'){
    this.initMap()
    }否则{
    这个.loadJS('https://maps.googleapis.com/maps/api/js?key=&callback=initMap')   
    }
    }
    // https://github.com/filamentgroup/loadJS/blob/master/loadJS.js
    loadJS(src){
    var ref=window.document.getElementsByTagName(“脚本”)[0];
    var script=window.document.createElement(“脚本”);
    script.src=src;
    script.async=true;
    ref.parentNode.insertBefore(脚本,ref);
    }
    initMap(){
    var map=new google.maps.map(this.refs.map{
    中心:{纬度:-34.397,液化天然气:150.644},
    缩放:8
    })
    }
    render(){
    返回()
    }
    }
    module.exports=镭(Map)
    

  • 您可以使用React轻松呈现google地图,这是与第三方库集成时的理想解决方案。如下所示:

    class App extends React.Component {
      constructor(props){
        super(props)
        this.state = {
          // no state for now..
        }
    
        // Use createRef() to create a reference to the DOM node we want
        this.myMapContainer = React.createRef()
      }
    
      componentDidMount() {
        // Instead of using: document.getElementById, use the ref we created earlier to access the element
        let map = new google.maps.Map(this.myMapContainer.current, {
          center: { lat: -34.9973268, lng: -58.582614 },
          scrollwheel: false,
          zoom: 4
        })
      }
    
      render() {
        return (
          <div className="container">
            <div ref={this.myMapContainer} id="map"></div>
            <div id="text"><p>Google Maps now requires the use of a valid API Key.
              That's why you see the popup window "This page can't load Google Maps correctly."</p>
              <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">Go get one!</a>
            </div>
          </div>
        )
      }
    }
    
    类应用程序扩展了React.Component{
    建造师(道具){
    超级(道具)
    此.state={
    //暂时没有州。。
    }
    //使用createRef()创建对所需DOM节点的引用
    this.myMapContainer=React.createRef()
    }
    componentDidMount(){
    //不要使用:document.getElementById,而是使用前面创建的ref来访问元素
    让map=new google.maps.map(this.myMapContainer.current{
    中心:{lat:-34.9973268,lng:-58.582614},
    滚轮:错误,
    缩放:4
    })
    }
    render(){
    返回(
    谷歌地图现在需要使用有效的API密钥。
    这就是为什么您会看到弹出窗口“此页面无法正确加载谷歌地图”

    ) } }


    注意:不要忘记放置调用Google Maps API的
    。如果您使用创建项目,可以将脚本放置在
    public/index.html

    中。这并不能解决问题,但我确实删除了window.onload。我发现地图的渲染宽度为0px,因此我现在修复了所有问题我看到地图应该放在一个灰色的框中——没有错误或任何东西。这有任何更新吗?我很好奇这种方法的限制/优点是什么?我发现
    react google map
    文档很难遵循。