1

我正在尝试根据我的反应谷歌地图组件中的标记坐标更新视口边界。

但是,当我在 componentWillMount() 中调用以下行时

const bounds = new google.maps.LatLngBounds();

我收到一条错误消息,提示未定义 google。

为了解决这个问题,我尝试过

(1)在index.html中添加google maps script标签

(2) 添加行

/* eslint-disable no-undef */

到我文件的顶部。

(3) 在我的 compose() 中添加 withScriptjs, withGoogleMap 但它会产生一个错误,指出 googleMapUrl 和未定义加载元素。为了解决这个问题,我尝试做

    <MapSearchBox
        googleMapURL="https://maps.googleapis.com/maps/api/js?key=APIKEY&v=3.exp&libraries=geometry,drawing,places"
        loadingElement={<div style={{ height: `100%` }} />}
        isMarkerShown={this.state.isMarkerShown}
        onMarkerClick={this.handleMarkerClick}
    />

但这没有用。

(4) 在我的文件顶部添加 /* global google */

还有一些其他的小变化,但没有任何影响。

请给一些建议!

MapWithASearchBox.js

/* global google */
import React from 'react';
import { get } from 'lodash';
import { compose, withProps, lifecycle, defaultProps } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
import PropTypes from 'prop-types';
const { SearchBox } = require('react-google-maps/lib/components/places/SearchBox');
import { buildMarkerObj } from '../../../imports/helpers/DataHelpers';

const MapSearchBox = compose(
    withProps(props => ({
        googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=APIKEY=3.exp&libraries=geometry,drawing,places',
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `450px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    })),
    withScriptjs,
    withGoogleMap,
    defaultProps({
        externalMarkers: [],
    }),
    lifecycle({
        componentWillMount() {
            const refs = {};
            const { lat, lng } = this.props.coords || (this.props.place && this.props.place.coords) || {};
            const initialMarker = lat !== undefined && lng !== undefined ? [buildMarkerObj({ lat, lng })] : [];
            console.log('THIS PROPS');
            console.log(this.props);
            console.log('PROPS');

            this.setState({
                bounds: null,
                center: {
                    lat: lat || 41.9,
                    lng: lng || -87.624,
                },
                markers: initialMarker,
                injectedMarkers: this.props.markers || [],
                onMapMounted: ref => {
                    refs.map = ref;
                },
                onBoundsChanged: () => {

                },
                onSearchBoxMounted: ref => {
                    refs.searchBox = ref;
                },
                onPlacesChanged: () => {
                    const places = refs.searchBox.getPlaces();

                    places.map(({ address_components, geometry: { location } }) => {
                        this.props.onSetLocation({
                            lat: location.lat(),
                            lng: location.lng(),
                        });
                    });

                    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);
                },
            })
            //ERROR HERE
            const bounds = new google.maps.LatLngBounds();
            this.props.markers.map((marker, index) => {
                bounds.extend(new google.maps.LatLng(
                    marker.coords.lat,
                    marker.coords.lng
                ));
            })

            refs.map.fitBounds(bounds);
            refs.map.panToBounds(bounds);
        },
    }),
)
((props) =>
    <GoogleMap
        ref={props.onMapMounted}
        defaultZoom={15}
        center={props.center}
        onBoundsChanged={props.onBoundsChanged}
    >
        <SearchBox
            ref={props.onSearchBoxMounted}
            bounds={props.bounds}
            controlPosition={google.maps.ControlPosition.TOP_LEFT}
            onPlacesChanged={props.onPlacesChanged}
        >
            <input
                type="text"
                placeholder="Enter your area"
                style={{
                    boxSizing: 'border-box',
                    border: '1px solid white',
                    width: '240px',
                    height: '32px',
                    marginTop: '12px',
                    padding: '0 12px',
                    borderRadius: '3px',
                    boxShadow: '0 2px 6px rgba(0, 0, 0, 0.3)',
                    fontSize: '14px',
                    outline: 'none',
                    textOverflow: 'ellipses',
                    backgroundColor: 'white',
                }}
            />
        </SearchBox>
        {props.markers.map((marker, index) =>
            <Marker key={`map-marker-${index}`} position={marker.position} />
        )}
        {props.externalMarkers.map((marker, index) =>
            <Marker key={`external-marker-${index}`} position={marker.coords} />
        )}
    </GoogleMap>
    )

class MapComponent extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = { isMarkerShown: false };
    }

    componentDidMount() {
        this.delayedShowMarker();
    }

    componentDidUpdate() {
        console.log('COMPONENT DID UPDATE');
        const bounds = new window.google.maps.LatLngBounds();
        this.props.markers.map((marker, index) => {
            bounds.extend(new window.google.maps.LatLng(
                marker.coords.lat,
                marker.coords.lng
            ));
        })
        refs.map.fitBounds(bounds);
        refs.map.panToBounds(bounds);
    }

    delayedShowMarker = () => {
        setTimeout(() => {
            this.setState({ isMarkerShown: true });
        }, 3000);
    }

    handleMarkerClick = () => {
        this.setState({ isMarkerShown: false });
        this.delayedShowMarker();
    }

    render() {
        return (
            <MapSearchBox
                isMarkerShown={this.state.isMarkerShown}
                onMarkerClick={this.handleMarkerClick}
            />
        );
    }
}

MapComponent.propTypes = {
    className: PropTypes.string,
    latitude: PropTypes.string,
    longitude: PropTypes.string,
    externalMarkers: PropTypes.array,
};

MapComponent.defaultProps = {
    className: '',
    externalMarkers: [],
};

export default MapSearchBox;
4

1 回答 1

2

在中添加 Google Map url 脚本index.html

<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY=3.exp&libraries=geometry,drawing,places></script>
于 2018-01-21T03:52:14.543 回答