ПОСТАНОВИЛИ.Google Maps API, ReactJS.Мне нужно рисовать ближайшие маркеры на карте с выбранными объектами - PullRequest
0 голосов
/ 18 июня 2019

Мне нужно рисовать маркеры на карте с ближайшими выбранными объектами, используя ReactJS и Google Maps API. Я нашел некоторые решения, но они не работают в React. Я надеюсь найти ответ от людей, которые сталкиваются с этим.

Я пытался использовать код из https://developers.google.com/maps/documentation/javascript/places и до сих пор думаю, что решение здесь скрывается.

UPDATE

Это код, с которым я работаю:

import React from 'react'
import { compose, withProps, withHandlers, withState } from 'recompose'
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps'
import { google } from 'google-maps'

const MyMapComponent = compose(
    withProps({
        googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=AIzaSyC4un_JQsqJQTH7rDez7k9SJw7-zDyZ3YA&v=3.exp&libraries=geometry,drawing,places',
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
    withState('places', 'updatePlaces', ''),
    //@ts-ignore
    withHandlers(() => {
        const refs = {
            map: undefined,
        };

        return {

            onMapMounted: () => (ref: any) => {
                refs.map = ref
            },
            fetchPlaces: ({ updatePlaces }) => {
                let places;
                //@ts-ignore
                const bounds = refs.map.getBounds();
                //@ts-ignore
                const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
                const request = {
                    bounds: bounds,
                    type: 'hotel'
                };
                service.nearbySearch(request, (results, status) => {
                    if (status === google.maps.places.PlacesServiceStatus.OK) {
                        console.log(results);
                        updatePlaces(results);
                    }
                })
            }
        }
    }),
)((props) => {
    return (
        <GoogleMap
            //@ts-ignore
            onTilesLoaded={props.fetchPlaces}
            //@ts-ignore
            ref={props.onMapMounted}
            //@ts-ignore
            onBoundsChanged={props.fetchPlaces}
            defaultZoom={8}
            defaultCenter={{lat: 46.446904, lng: 30.749284}}
        >
            {
                //@ts-ignore
                props.places && props.map((place, i) =>
                <Marker key={i} position={{ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }} />
            )}
        </GoogleMap>
    )
});

export default class MyFancyComponent extends React.PureComponent {
    render() {
        return (
            <MyMapComponent />
        )
    }
}

И вот что я получаю:

Моя ошибка

ОБНОВЛЕНИЕ 2

К счастью, я решил эту проблему и делюсь решением с сообществом. Вам необходимо добавить Google Places API

Ссылка на мой репозиторий: Репозиторий

Часть кода с решением проблемы:

map.component.tsx

placeMarkerLoad(){
        /*global google*/
        let center = new google.maps.LatLng(46.446904,30.749284);
        let map = new google.maps.Map(document.getElementById('map'), {
            center: center,
            zoom: 15
        });
        let options: google.maps.places.PlaceSearchRequest = {
            location: center,
            radius: 1500,
            type: this.state.selectedValue
        };
        let service = new google.maps.places.PlacesService(map);
        service.nearbySearch(options, this.callback);
        console.log('GOT IT', options);
    }

    callback(results: google.maps.places.PlaceResult[], status: google.maps.places.PlacesServiceStatus) {
        store.dispatch(clearMarkers());
        if (status === google.maps.places.PlacesServiceStatus.OK && !this.state.isPlacedMarkersShowed) {
            for (let i = 1; i < results.length; i++) {
                store.dispatch(setMarker({id: i, coordinates: {lat: results[i].geometry!.location.lat(), lng: results[i].geometry!.location.lng()}}));
            }
            this.setState(
                {
                    isPlacedMarkersShowed: true,
                    isMarkersShowed: false
                }
            );
        } else {
            this.setState(
                {
                    isMarkersShowed: false,
                    isPlacedMarkersShowed: false
                }
            );
            store.dispatch(clearMarkers());
            console.log('MARKERS', this.props.markerList);
        }
        console.log('RESULTS', results);
    }

Надеюсь, это кому-нибудь поможет.

...