简体   繁体   English

如何使用 react-google-maps 从两个不同的 SearchBox 中获取 formatted_address?

[英]How to get formatted_address out of two different SearchBoxes with react-google-maps?

I want to get the formatted_data out of two different SearchBoxes in the same GoogleMap in React.我想从 React 中同一个 GoogleMap 中的两个不同 SearchBox 中获取 formatted_data。 I am using the react-google-maps library.我正在使用 react-google-maps 库。 I have no clue how to go about it and I haven't found any information about it on the entire internet.我不知道如何去做,我还没有在整个互联网上找到任何关于它的信息。

I didn't forget to change my api key.我没有忘记更改我的 api 密钥。

I have copied this code to my project from the documentation.我已将此代码从文档复制到我的项目中。 But here is the code:但这里是代码:

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 />
      );

You are overriding the SearchBox reference here:您正在此处覆盖 SearchBox 参考:

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

That's why you only see the second SearchBox.这就是为什么您只能看到第二个 SearchBox。 What you can do is create an array, like this:您可以做的是创建一个数组,如下所示:

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

So that you can then do this:这样你就可以做到这一点:

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

Now if you log places you'll see place information for each searchbox.现在,如果您记录places您将看到每个搜索框的地点信息。 I just tested this on my end and it works without problem so I hope this helps you!我刚刚对此进行了测试,它可以正常工作,所以我希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM