2016-06-11 9 views
3

は私が反応/ Reduxのコンポーネント/ Reduxのコンポーネントに反応:Googleマップは、Googleマップを使用するための

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' 
    }); 

しかし、どのように、私は「リアクト-スタイル」で行うことができますか?描画マーカーはHTMLを 'レンダリング'しないので、JS Google Maps API関数を呼び出すだけです。私はこのロジックを 'initMap'関数に入れることができますが、私の 'mapPoints'は変更できます。私はJSロジック(削除ポイントを削除する/新しいポイントを描画する) 'レンダリング'機能に配置する必要がありますか?ありがとう!

+4

コードを使用して「google is undefined」エラーが発生します。 –

答えて

4

通常、いくつかの必須API(jQueryウィジェットなど)をラップするReactコンポーネントは、何も描画しない(またはコンテナdivのように最小限のコンテンツをレンダリングする)だけで、ラップされたReactライフサイクルメソッドの間、ウィジェット。実際にはすでにGoogle Maps APIを完成させるいくつかのコンポーネントがあります。具体的には、https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/がその方法を説明しています。

関連する問題