reactjs - google.maps.places.PlacesService(map) 总是返回 null

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

我正在尝试使用带有 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=几何、绘图、地点

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

请帮忙。

最佳答案

你的例子至少有两个问题

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

map 这里的对象对应Map component的实例而 google.maps.places.PlacesService 类需要 Google Maps 对象。在 react-google-maps 库的情况下,PlacesService 可以像这样实例化:

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 Service使用 react-google-maps 库。

关于reactjs - google.maps.places.PlacesService(map) 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53663689/

相关文章:

reactjs - react typescript : Object is possibly 'undefined'

ios - Swift - 如何将自定义字段添加到 Google Maps SDK 中的标记?

javascript - 在 JavaScript 中生成随机 Google map 街景坐标

javascript - 如何使用带钩子(Hook)的 react 功能组件测试句柄函数调用

javascript - 当聚焦位于模式内部的输入时防止页面滚动

google-maps-api-3 - Google Maps API basemap 可以用作自定义 map 图层上方的叠加层吗?

javascript - 从 MySQL 数据库加载热图 LatLng 坐标 Google map API

java - 无法将 Google map V3 与 GWT 一起使用

reactjs - 如何在react js中添加动态CSS

android - 为 MapFragment 子类设置 GoogleMapOptions