Я пытаюсь загрузить карту Google, которая сразу же выберет рестораны поблизости в зависимости от местоположения пользователя. Прямо сейчас я использую навигатор, чтобы определить его, но он не работает в моем компоненте Map с параметром onReady. Это означает, что я не передаю местоположение этому компоненту, и если я немного подожду, он получит места. Проблема в том, что мне нужно сделать это при загрузке компонента Map. Мне нужно изменить свою логику работы компонента, но у меня возникают проблемы с попыткой понять, как убедиться, что местоположение правильно передается компоненту Map с параметром onReady.
Вот код, с которым у меня возникают проблемы:
import React, { Component } from 'react'
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react'
import { Consumer } from '../context'
import Spinner from '../Layout/Spinner'
const mapStyles = {
width: '100%',
height: '500px'
}
export class MapContainer extends Component {
state = {
showingInfoWindow: false, //Hides or the shows the infoWindow
activeMarker: {}, //Shows the active marker upon click
selectedPlace: {}, //Shows the infoWindow to the selected place upon a marker,
userLocation: {
lat: '',
lng: ''
},
markers: [],
places: []
}
getCurrentLocation = () => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(position => {
this.setState({
...this.state,
userLocation: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
})
})
} else {
this.setState({
...this.state,
userLocation: {
lat: 0,
lng: 0
}
})
}
}
onMarkerClick = (props, marker, e) => {
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
})
}
fetchPlaces = (mapProps, map) => {
console.log(mapProps, map)
const bounds = map.getBounds()
const service = new mapProps.google.maps.places.PlacesService(map)
const request = {
bounds: bounds,
type: ['restaurant']
}
service.nearbySearch(request, (results, status) => {
if (status == mapProps.google.maps.places.PlacesServiceStatus.OK) {
console.log(results)
this.setState({
...this.state,
places: results
})
}
})
}
mapClicked = (mapProps, map, c) => {
this.fetchPlaces(mapProps, map)
}
onClose = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
}
componentWillMount() {
this.getCurrentLocation()
}
render() {
// console.log(this.props)
// console.log(this.state)
const bounds = new this.props.google.maps.LatLngBounds()
console.log(bounds)
return (
<Consumer>
{value => (
<React.Fragment>
{this.state.userLocation.lat && this.state.userLocation.lng ? (
<Map
google={this.props.google}
zoom={13}
style={mapStyles}
initialCenter={this.state.userLocation}
onClick={(mapProps, map, c) =>
this.mapClicked(mapProps, map, c)
}
onReady={(mapProps, map) => this.fetchPlaces(mapProps, map)}
>
<Marker
key={1}
onClick={this.onMarkerClick}
name={'You are here!'}
/>
{this.state.places.map(place => {
return (
<Marker
key={place.id}
position={{
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng()
}}
/>
)
})}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
</Map>
) : (
<Spinner />
)}
</React.Fragment>
)}
</Consumer>
)
}
}
export default GoogleApiWrapper({
apiKey: 'XXX',
libraries: ['places']
})(MapContainer)
Дело в том, что функция fetchPlaces работает при нажатии, но не работает при загрузке карты, что мне кажется странным. Логика этого компонента может показаться странной, но она находится в разработке.
Я открыт для любых предложений. Спасибо!