【问题标题】:How to get formatted_address out of two different SearchBoxes with react-google-maps?如何使用 react-google-maps 从两个不同的 SearchBox 中获取 formatted_address?
【发布时间】:2020-01-14 00:40:49
【问题描述】:

我想在 React 的同一个 GoogleMap 中从两个不同的 SearchBox 中获取 formatted_data。 我正在使用 react-google-maps 库。我不知道该怎么做,也没有在整个互联网上找到任何有关它的信息。

我没有忘记更改我的 api 密钥。

我已将此代码从文档中复制到我的项目中。但这里是代码:

const _ = require("lodash");
        const { compose, withProps, lifecycle } = require("recompose");
        const {
        withScriptjs,
        withGoogleMap,
        GoogleMap,
        Marker,
        } = require("react-google-maps");
        const { SearchBox } = require("react-google-maps/lib/components/places/SearchBox");

        const MapWithASearchBox = compose(
        withProps({
            googleMapURL: "https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&v=3.exp&libraries=geometry,drawing,places",
            loadingElement: <div style={{ height: `100%` }} />,
            containerElement: <div style={{ height: `400px` }} />,
            mapElement: <div style={{ height: `100%` }} />,
        }),
        lifecycle({
            componentWillMount() {
            const refs = {}

            this.setState({
                bounds: null,
                center: {
                lat: 41.9, lng: -87.624
                },
                markers: [],
                onMapMounted: ref => {
                refs.map = ref;
                },
                onBoundsChanged: () => {
                this.setState({
                    bounds: refs.map.getBounds(),
                    center: refs.map.getCenter(),
                })
                },
                onSearchBoxMounted: ref => {
                refs.searchBox = ref;
                },
                onPlacesChanged: () => {
                const places = refs.searchBox.getPlaces();
                //this is the information that I need but I need it from the second SearchBox too
                console.log(places[0].formatted_address);
                const bounds = new window.google.maps.LatLngBounds();

                places.forEach(place => {
                    if (place.geometry.viewport) {
                    bounds.union(place.geometry.viewport)
                    } else {
                    bounds.extend(place.geometry.location)
                    }
                });
                const nextMarkers = places.map(place => ({
                    position: place.geometry.location,
                }));
                const nextCenter = _.get(nextMarkers, '0.position', this.state.center);

                this.setState({
                    center: nextCenter,
                    markers: nextMarkers,
                });
                // refs.map.fitBounds(bounds);
                },
            })
            },
        }),
        withScriptjs,
        withGoogleMap
        )(props =>
        <GoogleMap
            ref={props.onMapMounted}
            defaultZoom={15}
            center={props.center}
            onBoundsChanged={props.onBoundsChanged}
        >
            <SearchBox
            ref={props.onSearchBoxMounted}
            bounds={props.bounds}
            controlPosition={window.google.maps.ControlPosition.TOP_LEFT}
            onPlacesChanged={props.onPlacesChanged}
            >
            <input
                type="text"
                placeholder="Customized your placeholder"
                style={{
                boxSizing: `border-box`,
                border: `1px solid transparent`,
                width: `240px`,
                height: `32px`,
                marginTop: `27px`,
                padding: `0 12px`,
                borderRadius: `3px`,
                boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                fontSize: `14px`,
                outline: `none`,
                textOverflow: `ellipses`,
                }}
            />
            </SearchBox>
            <SearchBox
            ref={props.onSearchBoxMounted}
            bounds={props.bounds}
            controlPosition={window.google.maps.ControlPosition.TOP_LEFT}
            onPlacesChanged={props.onPlacesChanged}
            >
            <input
                type="text"
                placeholder="Customized your placeholder"
                style={{
                boxSizing: `border-box`,
                border: `1px solid transparent`,
                width: `240px`,
                height: `32px`,
                marginTop: `27px`,
                padding: `0 12px`,
                borderRadius: `3px`,
                boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                fontSize: `14px`,
                outline: `none`,
                textOverflow: `ellipses`,
                }}
            />
            </SearchBox>
            {props.markers.map((marker, index) =>
            <Marker key={index} position={marker.position} />
            )}
        </GoogleMap>
        );

      return (
        <MapWithASearchBox />
      );

【问题讨论】:

    标签: javascript reactjs google-maps react-google-maps


    【解决方案1】:

    您在这里覆盖了 SearchBox 引用:

        onSearchBoxMounted: ref => {
          refs.searchBox = ref;
        },
    

    这就是为什么您只能看到第二个 SearchBox。您可以做的是创建一个数组,如下所示:

        onSearchBoxMounted: ref => {
          if (!refs.searchBoxes || refs.searchBoxes.length === 0) {
            refs.searchBoxes = [];
          }
          refs.searchBoxes.push(ref);
        },
    

    这样你就可以这样做了:

        onPlacesChanged: () => {
          let places = [];
          for (let i = 0; i < refs.searchBoxes.length; i++) {
            places.push(refs.searchBoxes[i].getPlaces());
          }
          ...
        }
    

    现在,如果您登录 places,您将看到每个搜索框的地点信息。我刚刚对此进行了测试,它可以正常工作,所以我希望这对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2012-09-26
      相关资源
      最近更新 更多