Reactjs 谷歌地图url未定义

Reactjs 谷歌地图url未定义,reactjs,google-maps,react-google-maps,Reactjs,Google Maps,React Google Maps,我正在尝试根据react google maps组件中的标记坐标更新视口边界 但是,当我调用componentWillMount()中的以下行时 const bounds=new google.maps.LatLngBounds() 我得到一个错误,说谷歌没有定义 为了解决这个问题,我已经尝试过了 (1) 将google maps脚本标记添加到index.html (2) 添加行 /*eslint禁用无未定义*/ 到我的文件的顶部 (3) 在my compose()中添加withScriptjs

我正在尝试根据react google maps组件中的标记坐标更新视口边界

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

const bounds=new google.maps.LatLngBounds()

我得到一个错误,说谷歌没有定义

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

(1) 将google maps脚本标记添加到index.html

(2) 添加行

/*eslint禁用无未定义*/

到我的文件的顶部

(3) 在my 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;
/*全球谷歌*/
从“React”导入React;
从“lodash”导入{get};
从“重新组合”导入{compose,withProps,lifecycle,defaultProps};
从“react GoogleMaps”导入{withScriptjs,withGoogleMap,GoogleMap,Marker};
从“道具类型”导入道具类型;
const{SearchBox}=require('react-google-maps/lib/components/places/SearchBox');
从“../../../imports/helpers/DataHelpers”导入{buildMarkerObj};
const MapSearchBox=compose(
带道具(道具=>({
谷歌网址:'https://maps.googleapis.com/maps/api/js?key=APIKEY=3.exp&libraries=geometry,图纸,位置,
加载元素:,
集装箱运输:,
mapElement:,
})),
用ScriptJS,
用谷歌地图,
默认道具({
外部标记:[],
}),
生命周期({
组件willmount(){
常量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(“这个道具”);
console.log(this.props);
console.log('PROPS');
这是我的国家({
界限:空,
中心:{
lat:lat | | 41.9,
液化天然气:液化天然气| |-87.624,
},
标记:initialMarker,
injectedMarkers:this.props.markers | |[],
onMapMounted:ref=>{
refs.map=ref;
},
onBoundsChanged:()=>{
},
onSearchBoxMounted:ref=>{
refs.searchBox=ref;
},
onPlacesChanged:()=>{
const places=refs.searchBox.getPlaces();
map({address\u components,geometry:{location}})=>{
这个.props.onSetLocation({
lat:location.lat(),
lng:location.lng(),
});
});
const nextMarkers=places.map(place=>({
位置:place.geometry.location,
}));
const nextCenter=get(nextMarkers'0.position',this.state.center);
这是我的国家({
中心:nextCenter,
markers:nextMarkers,
});
//参考地图fitBounds(bounds);
},
})
//这里出错
const bounds=new google.maps.LatLngBounds();
this.props.markers.map((marker,index)=>{
扩展(新的google.maps.LatLng)(
marker.coords.lat,
marker.coords.lng
));
})
参考地图fitBounds(bounds);
参考地图panToBounds(边界);
},
}),
)
((道具)=>
{props.markers.map((marker,index)=>
)}
{props.externalMarkers.map((标记,索引)=>
)}
)
类MapComponent扩展了React.PureComponent{
建造师(道具){
超级(道具);
this.state={isMarkerShown:false};
}
componentDidMount(){
this.delayedShowMarker();
}
componentDidUpdate(){
log('COMPONENT DID UPDATE');
const bounds=new window.google.maps.LatLngBounds();
this.props.markers.map((marker,index)=>{
扩展(new window.google.maps.LatLng(
marker.coords.lat,
marker.coords.lng
));
})
参考地图fitBounds(bounds);
参考地图panToBounds(边界);
}
delayedShowMarker=()=>{
设置超时(()=>{
this.setState({ismarkersown:true});
}, 3000);
}
handleMarkerClick=()=>{
this.setState({isMarkerShown:false});
this.delayedShowMarker();
}
render(){
返回(
);
}
}
MapComponent.propTypes={
类名:PropTypes.string,
纬度:PropTypes.string,
经度:PropTypes.string,
外部标记:PropTypes.array,
};
MapComponent.defaultProps={
类名:“”,
外部标记:[],
};
导出默认地图搜索框;

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY=3.exp&libraries=geometry,drawing,places></script>

在修复了一个重复的地图引用并删除了搜索组件中的googleMapURL之后,这一切都起了作用。竖起大拇指!如果我删除组件中的
googleMapURL
,它会给我一个错误。文档中有什么我遗漏的吗?@rohan patel你能分享一些狙击手吗。你好。与组件一起使用