1

나는 매우 간단한 반응 응용 프로그램을 사용하여 https://github.com/tomchentw/react-google-maps을 사용하고 있지만 현재지도 나 참조하는 방법을 이해하는 데 어려움이 있습니다. google.maps.Map 객체에 액세스하는 방법 맞춤 구성 요소에서반응 Google지도로 google.maps.Map 객체에 액세스하는 방법

나는 repo에서 this을 찾았지만 게시물을 읽은 후에 나는 여전히 약간 혼란 스럽습니다.

DirectionsRenderer 예제를 기반으로 응용 프로그램을 시작하고 있습니다.

내가하고 싶은 것은 시작 지점을 선택하고 Google지도 자동 완성 API를 사용하기위한 맞춤 구성 요소를 추가하는 것입니다.

예, 패키지에 이미 해당 구성 요소가 포함되어 있음을 알고 있지만 은지도에서 위치를 검색하는 것 이상을 수행해야합니다.

내가

const autocomplete = new google.maps.places.Autocomplete(node); 
autocomplete.bindTo('bounds', map); 

node 같은 것을 할 것입니다 내 요구를 달성하기 위해 내가 자동 완성 기능을 결합하고있어 mapgoogle.maps.Map 객체의 인스턴스 인 요소입니다. 지금까지

내 응용 프로그램 :

App.jsx

const App = ({ store }) => (
    <Provider store={store}> 
    <div> 
     <Sidebar> 
     <StartingPoint defaultText="Choose starting point&hellip;" /> 
     </Sidebar> 
     <GoogleApiWrapper /> 
    </div> 
    </Provider> 
); 

GoogleApiWrapper

const GoogleMapHOC = compose(
    withProps({ 
    googleMapURL: 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=__GAPI_KEY', 
    loadingElement: <div style={{ height: '100vw' }} />, 
    containerElement: <div style={{ height: '100vh' }} />, 
    mapElement: <div style={{ height: '100%' }} />, 
    }), 
    withScriptjs, 
    withGoogleMap, 
    lifecycle({ 
    componentDidMount() { 
     const DirectionsService = new google.maps.DirectionsService(); 

     // make google object available to other components 
     this.props.onLoad(google); 

     DirectionsService.route({ 
     origin: new google.maps.LatLng(41.8507300, -87.6512600), 
     destination: new google.maps.LatLng(41.8525800, -87.6514100), 
     travelMode: google.maps.TravelMode.DRIVING, 
     }, (result, status) => { 
     if (status === google.maps.DirectionsStatus.OK) { 
      this.setState({ 
      directions: result, 
      }); 
     } else { 
      console.error(`error fetching directions ${result}`); 
     } 
     }); 
    }, 
    }), 
)(props => (
    <GoogleMap 
    ref={props.onMapMounted} 
    defaultZoom={13} 
    defaultCenter={new google.maps.LatLng(37.771336, -122.446615)} 
    > 
    {props.directions && <DirectionsRenderer directions={props.directions} />} 
    </GoogleMap> 
)); 

내가 래퍼 I의 외부 google.maps.Map 개체에 액세스 할 수 없습니다 해요 경우 양자 택일로 elemen에 대한 참조에 액세스하고 싶다. t는지도가 포함되어 있으므로 인스턴스를 만들 수 있습니다. new google.maps.Map(ref_to_elem, options);

도움이 될만한 정보가 있으면 감사하겠습니다.

답변

0

react-google-maps 설명서, 예제 및 문제점을 완전히 읽은 후 해당 응용 프로그램에 대해 수행해야 할 많은 작업이 the package does not support임을 알게되었습니다.

즉, 나는 Fullstack React에 의해 수행 된 작업을 기반으로 내 자신의 Google Maps API wrapper를 작성하기 시작했습니다. 나는 아래에 언급 된 많은 유틸리티를 생략했습니다. 그들은 here 또는 here입니다.

내 솔루션은 높은 차수의 구성 요소에 구글이 컨테이너를 매핑 포장하고 window 객체를 통해 Map 객체를 노출하는 것입니다 말했다되고 그건 :

const App = ({ store }) => (
    <Provider store={store}> 
    <div> 
     <Sidebar> 
     <StartingPoint /> 
     {/* TODO */} 
     </Sidebar> 
     <GoogleMap /> 
    </div> 
    </Provider> 
); 

용기/GoogleMap으로/싸개.jsx 구글지도 높은 주문 구성 요소 GoogleMap으로 컨테이너를 래핑

const defaultCreateCache = (options) => { 
    const opts = options || {}; 
    const apiKey = opts.apiKey; 
    const libraries = opts.libraries || ['places']; 
    const version = opts.version || '3.24'; 
    const language = opts.language || 'en'; 

    return ScriptCache({ 
    google: GoogleApi({ 
     apiKey, 
     language, 
     libraries, 
     version, 
    }), 
    }); 
}; 

const wrapper = options => (WrappedComponent) => { 
    const createCache = options.createCache || defaultCreateCache; 

    class Wrapper extends Component { 
    constructor(props, context) { 
     super(props, context); 

     this.scriptCache = createCache(options); 
     this.scriptCache.google.onLoad(this.onLoad.bind(this)); 

     this.state = { 
     loaded: false, 
     google: null, 
     }; 
    } 

    onLoad() { 
     this.GAPI = window.google; 

     this.setState({ loaded: true, google: this.GAPI }); 
    } 

    render() { 
     const props = Object.assign({}, this.props, { 
     loaded: this.state.loaded, 
     google: window.google, 
     }); 
     const mapRef = (el) => { this.map = el; }; 

     return (
     <div> 
      <WrappedComponent {...props} /> 
      <div ref={mapRef} /> 
     </div> 
    ); 
    } 
    } 
    Wrapper.propTypes = { 
    dispatchGoogleAPI: PropTypes.func, 
    }; 
    Wrapper.defaultProps = { 
    dispatchGoogleAPI: null, 
    }; 

    return Wrapper; 
}; 

export default wrapper; 

용기/GoogleMap으로/index.jsx 구글지도 컨테이너 심판 반작용에 의해 당신은 그것을 할 수

class Container extends Component { 
    constructor(props) { 
    super(props); 

    this.loadMap = this.loadMap.bind(this); 
    this.calcRoute = this.calcRoute.bind(this); 
    } 

    componentDidUpdate() { 
    const { origin, destination, route } = this.props; 

    this.calcRoute(origin, destination); 
    } 

    loadMap(node) { 
    if (this.props && this.props.google) { 
     const { google } = this.props; 

     // instantiate Direction Service 
     this.directionsService = new google.maps.DirectionsService(); 

     this.directionsDisplay = new google.maps.DirectionsRenderer({ 
     suppressMarkers: true, 
     }); 

     const zoom = 13; 
     const mapTypeId = google.maps.MapTypeId.ROADMAP; 
     const lat = 37.776443; 
     const lng = -122.451978; 
     const center = new google.maps.LatLng(lat, lng); 

     const mapConfig = Object.assign({}, { 
     center, 
     zoom, 
     mapTypeId, 
     }); 

     this.map = new google.maps.Map(node, mapConfig); 

     this.directionsDisplay.setMap(this.map); 

     // make the map instance available to other components 
     window.map = this.map 
    } 
    } 

    calcRoute(origin, destination) { 
    const { google, route } = this.props; 

    if (!origin && !destination && !route) return; 

    const waypts = []; 

    waypts.push({ 
     location: new google.maps.LatLng(37.415284, -122.076899), 
     stopover: true, 
    }); 

    const start = new google.maps.LatLng(origin.lat, origin.lng); 
    const end = new google.maps.LatLng(destination.lat, destination.lng); 

    this.createMarker(end); 

    const request = { 
     origin: start, 
     destination: end, 
     waypoints: waypts, 
     optimizeWaypoints: true, 
     travelMode: google.maps.DirectionsTravelMode.DRIVING, 
    }; 

    this.directionsService.route(request, (response, status) => { 
     if (status === google.maps.DirectionsStatus.OK) { 
     this.directionsDisplay.setDirections(response); 
     const route = response.routes[0]; 
     console.log(route); 
     } 
    }); 

    this.props.calculateRoute(false); 
    } 

    createMarker(latlng) { 
    const { google } = this.props; 

    const marker = new google.maps.Marker({ 
     position: latlng, 
     map: this.map, 
    }); 
    } 

    render() { 
    return (
     <div> 
     <GoogleMapView loaded={this.props.loaded} loadMap={this.loadMap} /> 
     </div> 
    ); 
    } 
} 

const GoogleMapContainer = wrapper({ 
    apiKey: ('YOUR_API_KEY'), 
    version: '3', // 3.* 
    libraries: ['places'], 
})(Container); 

const mapStateToProps = state => ({ 
    origin: state.Trip.origin, 
    destination: state.Trip.destination, 
    route: state.Trip.route, 
}); 

const mapDispatchToProps = dispatch => ({ 
    dispatchGoogleMap: (map) => { 
    dispatch(googleMap(map)); 
    }, 
    calculateRoute: (route) => { 
    dispatch(tripCalculation(route)); 
    }, 
}); 

const GoogleMap = connect(mapStateToProps, mapDispatchToProps)(GoogleMapContainer); 

export default GoogleMap; 
0

:

<GoogleMap ref={(map) => this._map = map} /> 
function someFunc() { 
    //using, for example as: 
    this._map.getCenter() 
    this._map.setZoom(your desired zoom); 
} 
0

내 반응에 지금 무엇을 했는가? 하위 구성 요소에 소품으로

/*global google*/ 

// your imports // 

var map; 

class GoogleMap extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     // your states 
    }; 
    } 

    // your functions 

    componentWillReceiveProps(nextProps) { 

    } 

    componentDidMount() { 

    // code 

    // render googlemap 

    map = new google.maps.Map(this.refs.map, yourMapProps); 

    // add click event listener to the map 

    map.addListener('click', function(e) { 
     //code 
    }); 

    //viewport listener 

    map.addListener('idle', function(){ 
     // code 
    }); 
    } 

    render() { 
     return (
     <div id="map" ref="map"> 
      {places.map((place) => { 
      return(<Marker place={place} key={place.key} map={map} />); 
      })} 
     </div> 
    } 
} 

function mapDispatchToProps(dispatch) { 
    //code 
} 

export default connect(mapDispatchToProps)(GoogleMap); 

패스지도 : 나도 몰라

/*global google*/ 

import React, { Component } from 'react'; 

class Marker extends Component { 
    componentDidMount() { 
    this.renderMarker(); 
    } 

    renderMarker() { 
    var { place, map } = this.props; 
    place.setMap(map); 
    } 

    render() { 
    return null; 
    } 
} 

export default Marker; 

이 좋습니다 -redux 어플은 외부의 comnponent GoogleMap으로 반응 전역 변수 맵을 지정합니다. 부작용. 나는지도 객체를 전역 windows.map으로 설정하는 것을 피하는 방법을 찾기 위해 싱글 톤에 관한 모든 것을 읽는 등의 작업을 시도했다. 그리고 나서 이것이 내 머리로왔다. 이제 window.map을 브라우저 concole에 입력하면 div id = "map"이됩니다.