gpt4 book ai didi

google-maps-api-3 - 在没有react-google-map的情况下渲染Google map

转载 作者:行者123 更新时间:2023-12-03 13:22:35 24 4
gpt4 key购买 nike

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

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;

我尝试过的任何方法都不起作用。我也尝试过使用 refs 捕获 map ,但也没有渲染 map 。我也将谷歌地图脚本放置在 header 中(带有 key ),并验证了该 key 在普通 js 项目中有效。

最佳答案

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

https://maps.googleapis.com/maps/api/js?key= &callback=initMap

现在您可以按如下方式继续,在安装 map 组件后,您可以:

  1. window.initMap = this.initMap 使 React 中的 initMap 可供 Google map 回调。
  2. 使用 initMap 参数加载谷歌地图 JS。
  3. 在组件中的 this.initMap 中,您可以执行 map 操作,因为现在您知道您的容器和 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)

关于google-maps-api-3 - 在没有react-google-map的情况下渲染Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com