Initialize React Google Maps StandaloneSearchBox with geocode

后端 未结 2 376
日久生厌
日久生厌 2021-01-15 21:31

Can someone tell me how to initialize React Google Maps\'s StandaloneSearchBox component with types: [\'geocode\'] (like in the original google.maps.places.Autocomplete, so

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 22:14

    I was able to do something like this with alexandar's suggestion. Pass an address into the address search and use geocode to do a near by search. Hope this helps.

    import React from 'react';
    import { compose, withProps, lifecycle } from 'recompose';
    import { withScriptjs } from 'react-google-maps';
    import StandaloneSearchBox from 'react-google-maps/lib/components/places/StandaloneSearchBox';
    import get from 'lodash/get';
    import head from 'lodash/head';
    import { Search } from '../components';
    
    const GOOGLE_API_KEY = '123';
    
    const AddressSearchbox = compose(
      withProps(props => {
        return {
          ...props,
          googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&v=3.exp&libraries=geometry,drawing,places`,
          loadingElement: 
    , containerElement:
    , }; }), withScriptjs, lifecycle({ componentDidMount() { const refs = {}; this.setState({ places: [], searchText: '', error: null, onSearchBoxMounted: ref => { refs.searchBox = ref; }, onPlacesChanged: () => { const places = refs.searchBox.getPlaces(); this.setState({ places, searchText: '', }); }, }); *** const geocoder = new google.maps.Geocoder(); geocoder.geocode({ address: this.props.placeName }, (results, status) => { if (status === google.maps.DirectionsStatus.OK) { const lngs = results[0].geometry.bounds.j; const lats = results[0].geometry.bounds.l; this.setState({ boundSearch: new google.maps.LatLngBounds( new google.maps.LatLng(lats.l, lngs.l), new google.maps.LatLng(lats.j, lngs.j) ), }); } else { this.setState({ error: status, }); } *** }); }, }) )(props => { return (
    {get(head(props.places), 'formatted_address')}
    ); }); export default AddressSearchbox;

提交回复
热议问题