【问题标题】:google.maps.places.PlacesService(map) always returns nullgoogle.maps.places.PlacesService(map) 总是返回 null
【发布时间】:2019-05-08 21:00:22
【问题描述】:

我正在尝试使用带有 react-google-maps 的 google maps API 来获取附近的餐馆。

import React from 'react';
import { compose, withState, withProps, withStateHandlers, lifecycle } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps';
import dotenv from 'dotenv';
import { HOME_MAP } from './MapNavigationConstants';
import MapSearch from './MapSearch';

dotenv.config();

const MapWithInfoWindow = compose(
    withProps({
        googleMapURL: HOME_MAP,
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement:<div style={{ height: `720px` }} />,
        mapElement:<div style={{ height: `100%` }} />,
    }),
    withState('mapUrl', 'setMapUrl', ''),
    withState('bounds', 'setBounds', null),
    withState('center', 'setCenter', {
      lat: 53.3498, lng: -6.2603
    }),
    withState('markers', 'setMarkers', [
      {
        position: {
          lat: () => 53.3498,
          lng: () => -6.2603
        }
      }
    ]),
    withState('places', 'updatePlaces', ''),
    withStateHandlers(() => ({
        isOpen: false,
        isExploreOn: false,
      }), {
        onToggleOpen: ({ isOpen }) => () => ({
          isOpen: !isOpen,
        })
      }
    ),
    lifecycle({
      componentWillMount() {
        const refs = {}

        this.setState({
          onMapMounted: ref => {
            refs.map = ref;
          },
          onBoundsChanged: (bounds, center, markers) => {
            this.props.setBounds(!bounds ? this.props.bounds : bounds);
            this.props.setCenter(!center ? this.props.center : center);
            this.props.setMarkers(!markers ? this.props.markers : markers);
          },
          fetchPlaces: () => {
            this.props.setMapUrl('places');
            const bounds = refs.map.getBounds();
            const map = refs.map;      
            const service = new window.google.maps.places.PlacesService(map);
            console.log(service);
            const request = {
              bounds,
              type: ['restaurants', 'cafe','bars']
            };
            service.nearBySearch(request, (results, status) => {
              if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                this.props.updatePlaces(results);
              }
            });
          }
        })
      },
    }),
    withScriptjs, 
    withGoogleMap)((props) => 
    <GoogleMap
        ref={props.onMapMounted}
        defaultCenter = {props.center}
        defaultZoom = { 13 }
        center={props.center}
        bounds={props.bounds}
        options={{gestureHandling: 'cooperative', 
        scrollwheel: false,
        disableDefaultUI: true,
    }}
        bootstrapURLKeys={{libraries: props.mapUrl}}
        onBoundsChanged={props.onBoundsChanged}
    >
    <MapSearch 
      onBoundsChanged={(bounds, center, markers) => props.onBoundsChanged(bounds, center, markers)} 
      fetchPlaces={props.fetchPlaces}
    />
        {
          props.markers && props.markers.length > 0 && props.markers.map((marker, index) => (
            <Marker
              key={index}
              position={{ lat: marker.position.lat(), lng:marker.position.lng() }}
            onClick={props.onToggleOpen}
        >
            {props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
            {props.children}
        </InfoWindow>}
        </Marker>
          ))
        }{
          props.places && props.places.length > 0 && props.places.map((place, index) => (
            <Marker
              key={index}
              position={{ lat: place.location.lat(), lng:place.location.lng() }}
            onClick={props.onToggleOpen}
        >
            {props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
            {props.children}
        </InfoWindow>}
        </Marker>
          ))
        }
    </GoogleMap>
)

export default MapWithInfoWindow;

这里 HOME_MAP = https://maps.googleapis.com/maps/api/js?key=${KEY}&v=3.exp&libraries=geometry,drawing,places

在 fetchplaces 方法中,new window.google.maps.places.PlacesService(map) 总是返回 null 并且 service.nearBySearch 不会抛出函数错误。

请帮忙。

【问题讨论】:

    标签: reactjs google-maps google-maps-api-3 google-places-api react-google-maps


    【解决方案1】:

    你的例子至少有两个问题

    const map = refs.map;      
    const service = new window.google.maps.places.PlacesService(map);
                                                                ^^^
    

    map 对象在这里对应于Map component 的实例,而google.maps.places.PlacesService 类则需要 Google Maps 对象。如果react-google-mapsPlacesService 可以这样实例化:

    mapMounted(element) {
       const mapObject = element.context[MAP];
       const service = new google.maps.places.PlacesService(map);
       //...
    }    
    

    在哪里

    <GoogleMap
        ref={this.mapMounted}
        defaultZoom={this.props.zoom}
        defaultCenter={this.props.center}/>
    

    还有一行错字:

    service.nearBySearch(request, (results, status) => {
            ^^^^^^^^^^^^
    

    函数应该重命名为nearbySearch

    这里是a demo,它演示了如何将Places Servicereact-google-maps 库一起使用。

    【讨论】:

    • 从“react-google-maps/lib/constants”导入 { MAP };改变了一切。在文档中找不到它。非常感谢:) 成功了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2016-11-02
    • 2014-05-06
    • 2012-06-05
    • 2014-05-30
    • 2014-02-23
    • 2017-10-12
    相关资源
    最近更新 更多