google.maps.places.PlacesService (map) всегда возвращает ноль - PullRequest
0 голосов
/ 07 декабря 2018

Пытаюсь найти близлежащие рестораны, используя API карт Google с реакцией google-maps.

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, новое window.google.maps.places.PlacesService (map) всегда возвращает null, а service.nearBySearch не выдает ошибку функции.

Пожалуйста, помогите.

1 Ответ

0 голосов
/ 11 декабря 2018

Есть как минимум две проблемы с вашим примером

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

map здесь здесь соответствует экземпляру Map компонента , в то время как класс 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

Вот демонстрационная версия , демонстрирующая, как использовать Places Service с библиотекой react-google-maps.

...