【问题标题】:google map with search in react js谷歌地图在 React js 中搜索
【发布时间】:2022-08-03 06:33:37
【问题描述】:

我在我的 react 应用程序中使用google-maps-react 库作为地图,并且我在我的应用程序中添加了搜索地址功能并面临 CORS 错误。

错误:

自动完成.js

import React, { Component } from \'react\';
import styled from \'styled-components\';

const Wrapper = styled.div`
  position: relative;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20px;
  text-align:center;
`;

class AutoComplete extends Component {
    constructor(props) {
        super(props);
        this.clearSearchBox = this.clearSearchBox.bind(this);
    }

    componentDidMount({ map, mapApi } = this.props) {
        const options = {
            // restrict your search to a specific type of result
            types: [\'address\'],
            // restrict your search to a specific country, or an array of countries
            // componentRestrictions: { country: [\'gb\', \'us\'] },
        };
        this.autoComplete = new mapApi.places.Autocomplete(
            this.searchInput,
            options,
        );
        this.autoComplete.addListener(\'place_changed\', this.onPlaceChanged);
        this.autoComplete.bindTo(\'bounds\', map);
    }

    componentWillUnmount({ mapApi } = this.props) {
        mapApi.event.clearInstanceListeners(this.searchInput);
    }

    onPlaceChanged = ({ map, addplace } = this.props) => {
        const place = this.autoComplete.getPlace();

        if (!place.geometry) return;
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }

        addplace(place);
        this.searchInput.blur();
    };

    clearSearchBox() {
        this.searchInput.value = \'\';
    }

    render() {
        return (
            <Wrapper>
                <input
                    className=\"search-input\"
                    ref={(ref) => {
                        this.searchInput = ref;
                    }}
                    type=\"text\"
                    onFocus={this.clearSearchBox}
                    placeholder=\"Enter a location\"
                />
            </Wrapper>
        );
    }
}

export default AutoComplete;

谷歌地图组件:

const MyGoogleMap = () => {
    const [apiReady, setApiReady] = useState(false);
    const [map, setMap] = useState(null);
    const [mapApi, setMapApi] = useState(null);
    const [address, setAddress] = useState();
    const [zoom, setZoom] = useState();
    const [center, setCenter] = useState([]);
    const [lat, setLat] = useState();
    const [lng, setLng] = useState();
    const [places, setPlaces] = useState();
    const [draggable, setDraggable] = useState();

    const setCurrentLocation = () => {
        if (\'geolocation\' in navigator) {
            navigator.geolocation.getCurrentPosition(position => {
                console.log(\'position.coords: \', position.coords.longitude);
                console.log(\"[position.coords.latitude, position.coords.longitude]: \", [position.coords.latitude, position.coords.longitude])
                setCenter([position.coords.latitude, position.coords.longitude]);
                setLat(position.coords.latitude);
                setLng(position.coords.longitude);
            });
        }
    };

    useEffect(() => {
        setCurrentLocation();
    }, []);

    const handleApiLoaded = (map, maps) => {
        console.log(\'map, maps: \', map, maps);
        // use map and maps objects
        if (map && maps) {
            setApiReady(true);
            setMap(map);
            setMapApi(maps);
        }
    };
    const _generateAddress = () => {
        const geocoder = new mapApi.Geocoder();

        geocoder.geocode({ location: { lat: lat, lng: lng } }, (results, status) => {
            console.log(results);
            console.log(status);
            if (status === \'OK\') {
                if (results[0]) {
                    setZoom(12);
                    setAddress(results[0].formatted_address);
                } else {
                    window.alert(\'No results found\');
                }
            } else {
                window.alert(\'Geocoder failed due to: \' + status);
            }
        });
    };

    const onMarkerInteraction = (childKey, childProps, mouse) => {
        setDraggable(true);
        setLat(mouse.lat);
        setLng(mouse.lng);
    };

    const onMarkerInteractionMouseUp = (childKey, childProps, mouse) => {
        setDraggable(true);
        _generateAddress();
    };

    const _onChange = ({ center, zoom }) => {
        setZoom(zoom);
        setCenter(center);
    };

    const _onClick = value => {
        setLat(value.lat);
        setLng(value.lng);
    };

    const addPlace = place => {
        setPlaces([place]);
        setLat(place.geometry.location.lat());
        setLng(place.geometry.location.lng());
        _generateAddress();
    };

    return (
        <div style={{ height: \'442px\', width: \'100%\' }}>
            {apiReady && <Autocomplete map={map} mapApi={mapApi} addplace={addPlace} />}
            <GoogleMapReact
                zoom={4}
                center={center}
                bootstrapURLKeys={{
                    key: \'API_KEY\',
                    libraries: [\'places\', \'geometry\'],
                }}
                yesIWantToUseGoogleMapApiInternals
                onGoogleApiLoaded={({ map, maps }) =>
                    handleApiLoaded(map, maps)
                }
            ></GoogleMapReact>
        </div>
    );
}

我正在关注此article 以将 Google 地图与搜索集成

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


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 2015-07-01
  • 2011-09-18
相关资源
最近更新 更多