【问题标题】:Google Maps React/Redux component谷歌地图 React/Redux 组件
【发布时间】:2016-10-12 14:42:40
【问题描述】:

用于处理 Google 地图的我的 React/Redux 组件:

import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

import { changeMapCenter } from '../actions'

class Map extends Component {

  componentDidMount() {
    let script = document.createElement('script')

    script.setAttribute('type', 'text/javascript')
    script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCXg-YGJF&callback=initMap')
    document.getElementsByTagName('head')[0].appendChild(script)

    window.initMap = () => {
      this.map = new google.maps.Map(document.getElementById('map'), {
        center: this.props.defaultCenter,
        zoom: this.props.defaultZoom
      });

      this.map.addListener('center_changed', (event) => {
        let center = {
          lat: this.map.getCenter().lat(),
          lng: this.map.getCenter().lng()
        }
        this.props.onMapCenterChanging(center)
      });
    }
  }

  render() {
    return (
      <div id='map'></div>
    );  
  }
}

const mapStateToProps = (state) => {
  return {
    mapPoints: state.mapPoints
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onMapCenterChanging: (center) => {
      dispatch(changeMapCenter(center))
    }    
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Map)

正如你现在看到的,这个组件只是初始化地图并监听地图中心的变化。现在我需要渲染一些标记(mapPoints)。从 Google API 文档我可以做到(例如):

  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Click to zoom'
  });

但是我该如何使用“React 风格”呢?因为绘图标记不是“渲染”HTML,它只是调用 JS Google Maps API 函数。我可以把这个逻辑放在“initMap”函数中,但我的“mapPoints”可以改变。我应该将 JS 逻辑(删除删除点/绘制新点)放在“渲染”函数中吗?谢谢!

【问题讨论】:

  • 使用您的代码时出现google is undefined 错误。

标签: javascript google-maps google-maps-api-3 reactjs redux


【解决方案1】:

通常,封装了一些命令式 API(如 jQuery 小部件或类似物)的 React 组件通过不渲染任何内容(或仅渲染少量内容,如容器 div)来实现,然后更新包装的小部件在 React 生命周期方法期间。实际上已经有一些组件封装了 Google Maps API,特别是,https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/ 将引导您完成操作。

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2023-03-24
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2021-10-09
    • 2011-02-13
    相关资源
    最近更新 更多