首页 > 解决方案 > 如何在反应谷歌地图中在 StandaloneSearchBox 上设置中心

问题描述

我正在使用react google maps 独立搜索框,一切都很好,但是我如何才能在 google 地图搜索提示(地点)中首先显示附近的位置,通常当我们使用带有搜索框的地图时,我们会相互附加,但在这里我没有不要添加地图。
所以在这里我的问题是我如何在谷歌地方搜索提示上设置中心或首先显示附近的搜索。

这是我的代码

import React from 'react';
import {connect} from 'react-redux';
import { Input,Icon} from 'antd';
import 'antd/dist/antd.css';
import {pickupHandler,pickupAddHandler,dropoffHandler} from '../actions';
import config from '../../../config'
const { compose, withProps, lifecycle,withHandlers } = require("recompose");
const {
    withScriptjs,
  } = require("react-google-maps");
  const { StandaloneSearchBox } = require("react-google-maps/lib/components/places/StandaloneSearchBox");


const SearchBox = compose(
  withProps({
    googleMapURL: config.MapApi,
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
  }),
  lifecycle({
    componentWillMount() {
      const refs = {}

      this.setState({
        onSearchBoxMounted: ref => {
          refs.searchBox = ref;
        },
        onBoundsChanged: () => {
            this.setState({
              bounds: refs.map.getBounds(),
              center: refs.map.getCenter(),
            })
          },
        onPlacesChanged: () => {
          const places = refs.searchBox.getPlaces();

          places.map(({ place_id, formatted_address, geometry: { location } }) =>{
            this.props.latlngHandler({lat:location.lat(),lng:location.lng()})
            this.props.AddressHandler(formatted_address)
          })
          this.setState({
            places,
          });
        },
        suffix: () =>{
            this.props.AddressHandler('')
            this.props.latlngHandler(false);
        }
      })
    },

  }),
  withHandlers(() => {
    return{
        cutPickIcon:<Icon type="close-circle" />
    }
  }),
  withScriptjs  
)(props =>
  <div data-standalone-searchbox="">
    <StandaloneSearchBox
      ref={props.onSearchBoxMounted}
      bounds={props.bounds}
      onBoundsChanged={props.onBoundsChanged}
      onPlacesChanged={props.onPlacesChanged}
    >
      <Input
        prefix={<Icon type="environment-o" style={props.name === 'pick' ? { color: '#EA4335' }: { color: '#00E64D' }} />}
        type="text"
        placeholder={props.placeHoler}
        onChange={props.Field}
        onFocus={props.FocusGA}
        value={props.Address}
        className='input'
        suffix={props.Suffix ? <Icon type="close-circle" onClick={props.suffix}/> :''}
      />
    </StandaloneSearchBox>

  </div>
);

export default connect(null,{pickupAddHandler,pickupHandler,dropoffHandler})(SearchBox)

标签: reactjsgoogle-mapsgoogle-places-apireact-google-mapsgoogleplacesautocomplete

解决方案


您可以使用地图地理编码设置 bounds prop on StandaloneSearchBox

请参考我在这篇文章中的回答。 https://stackoverflow.com/a/53396781/1661712


推荐阅读