In may app I have to show a list of markers and markers that are already stored in sessionStorage, but I cant set markers, zoom and center of the map at first render of the page, I nees refresh the page to see data on it.
FIRST RENDER:
AFTER REFRESH:
Part of the code is justa above, I have a loadMap where I instaciate map with useLoadScript, I can post it here too if it's necessary!
import React, { useState, useEffect } from "react"
import { GoogleMap, Marker } from "#react-google-maps/api"
import { Trash } from "phosphor-react"
import { useNavigate } from "react-router-dom"
var tempMarker
function Map({
markers,
setMarkers,
wayPoints,
setWayPoints,
routeHead,
setRouteHead,
}) {
const [isMounted, setIsMounted] = useState(false)
const [reload, setReload] = useState(false)
const navigate = useNavigate()
let marker
function refreshPage() {
console.log("passei aqui refresh")
window.location.reload(false)
}
const onChangeMarkers = () => {
if (markers) {
if (markers.length > 0) {
setWayPoints(markers)
sessionStorage.removeItem("markers")
sessionStorage.setItem("markers", JSON.stringify(markers))
if (reload) {
refreshPage()
setReload(false)
}
}
}
}
useEffect(() => {
if (!isMounted) {
setIsMounted(true)
setReload(false)
onChangeMarkers()
}
}, [])
const handleOnLoad = (map) => {
onChangeMarkers()
const bounds = new window.google.maps.LatLngBounds()
if (markers) {
if (markers.length > 0) {
markers.forEach(({ latitude, longitude }) => {
let pos = new window.google.maps.LatLng(latitude, longitude)
bounds.extend(pos)
})
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
}
map.setZoom(13)
map.setCenter(pos)
},
(e) => {
console.log(e)
},
{ maximumAge: 15000, timeout: 60000, enableHighAccuracy: true }
)
} else {
let pos = new window.google.maps.latLng()
pos = { lat: -16.6446324, lng: -49.416115 }
map.setZoom(10)
map.setCenter(pos)
}
}
}
map.fitBounds(bounds)
map.addListener("click", function (e) {
placeMarker(e.latLng, map)
})
}
const handleSubmit = async (event) => {
navigate("/WayPointsTable", { replace: false })
}
function placeMarker(location, map) {
if (marker == null) {
marker = new window.google.maps.Marker({
position: location,
map: map,
})
} else {
marker.setPosition(location)
}
const markerId = markers.length
const markerQtde = markerId + 1
tempMarker = {
idRota: routeHead.idRota,
idVeiculo: routeHead.idVeiculo,
idFrota: routeHead.idFrota,
idMotorista: routeHead.idMotorista,
idAjudante1: routeHead.idAjudante1,
idAjudante2: routeHead.idAjudante2,
idAjudante3: routeHead.idAjudante3,
idCarga: routeHead.idCarga,
idPonto: markerQtde,
latitude: parseFloat(marker.getPosition().lat().toFixed(6)),
longitude: parseFloat(marker.getPosition().lng().toFixed(6)),
cpfCNPJ: "CPF/CNPJ",
nome: "PONTO " + markerQtde,
endereco: "informe o endereco",
distanciaMinima: "100",
horarioParada: "00:00",
dataHoraInicio: routeHead.dtHrInicio,
dataHoraFim: routeHead.dtHrFim,
observacao: "",
valorAReceber: 0,
custoPernoite: 0,
idSequencia: markerQtde,
distanciaEmKm: 1,
tipoRegistro: "2.ENTREGA",
}
console.log(tempMarker)
markers.push(tempMarker)
map.setZoom(14)
let pos = new window.google.maps.LatLng(
parseFloat(marker.getPosition().lat().toFixed(6)),
parseFloat(marker.getPosition().lng().toFixed(6))
)
map.setCenter(pos)
setReload(true)
onChangeMarkers()
}
const handleMarkerClick = (evt) => {
console.log(evt)
}
const handleMarkerDrag = (mk, index) => {
const newLat = parseFloat(mk.latLng.lat().toFixed(6))
const newLng = parseFloat(mk.latLng.lng().toFixed(6))
markers = markers.map((marker, i) => {
if (i === index) {
marker = { ...marker, latitude: newLat, longitude: newLng }
}
return marker
})
setMarkers(markers)
setReload(false)
onChangeMarkers()
}
const handleDeleteMarker = (index) => {
if (index !== undefined) {
markers = markers
.filter((marker, i) => i !== index)
.map((marker, i) => {
marker = { ...marker, id: i }
return marker
})
setMarkers(markers)
setReload(true)
onChangeMarkers()
}
}
return (
<div className="flex flex-row">
<div className="bg-zinc-300 w-1/4">
<h2 className="text-center text-black font-bold p-2">
PONTOS DE ENTREGA
</h2>
<div className="flex flex-col">
<div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="py-2 inline-block min-w-full sm:px-6 lg:px-8">
<div className="overflow-hidden">
<table className="min-w-full">
<tbody className="text-black font-semibold">
{isMounted &&
wayPoints &&
wayPoints.length > 0 &&
wayPoints.map(({ nome }, index) => {
return (
<tr key={index}>
<td>{index + 1} - </td>
<td>{nome.substr(0, 18)}</td>
<td>
<div
key={index}
className="inline-block align-middle w-4 bg-red-700 text-white rounded "
onClick={() => handleDeleteMarker(index)}
>
<Trash size={16} alt="Excluir" />
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div className="flex flex-col items-center">
<button
onClick={() => handleSubmit()}
className=" bg-red-500 hover:bg-red-700 py-2 px-4 mt-3 rounded text-zinc-100 font-bold "
>
Enviar
</button>
</div>
</div>
<GoogleMap
onLoad={handleOnLoad}
afterLoad={refreshPage}
mapContainerStyle={{ width: "100vw", height: "100vh" }}
>
{isMounted &&
wayPoints &&
wayPoints.length > 0 &&
wayPoints.map(({ nome, idSequencia, latitude, longitude }, index) => (
<Marker
key={index}
position={{ lat: latitude, lng: longitude }}
title={nome}
addListener
draggable
onClick={handleMarkerClick}
onDragEnd={(marker) => handleMarkerDrag(marker, index)}
icon={
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" +
idSequencia +
"|FF0000|000000"
}
></Marker>
))}
</GoogleMap>
</div>
)
}
export default Map
Related
I am using the GeoJSON layer to show markers
In MapComponent.js
<MapContainer
whenCreated={(mapInstance) => {
mapRef.current = mapInstance;
}}
center={center}
zoom={zoom}
style={{ width: '100%', height: '100%' }}
maxZoom={maxZoom}
maxNativeZoom={maxNativeZoom}
zoomControl={false}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
maxZoom={maxZoom}
maxNativeZoom={maxNativeZoom}
/>
TrackingResults &&
<Markers
TrackingResults={TrackingResults}
openPopupId={openPopupId}
setOpenPopupId={setOpenPopupId}
/>
</MapContainer>
In the Marker.js Custom component.
const Markers = ({ TrackingResults, openPopupId, setOpenPopupId }) => {
const { t } = useTranslation();
const layerRef = useRef();
const updateLayer = () => {
const layer = layerRef.current;
if (layer != null && layer.getLayers().length > 0) {
layer.eachLayer((marker) => {
const { feature } = marker;
if (feature != null && feature.geometry != null) {
const lat = feature.geometry.coordinates[0];
const lng = feature.geometry.coordinates[1];
if (
lat !== marker.getLatLng().lat ||
lng !== marker.getLatLng().lng
) {
marker.setLatLng([lat, lng]);
// console.log(marker);
}
}
});
}
};
useEffect(() => {
updateLayer();
}, [markers]);
return TrackingResults.map((m) => (
<GeoJSON
ref={layerRef}
key={m.id}
data={m.data}
pointToLayer={pointToTrackingResultLayer}
onEachFeature={(
feature,
layer,
currentPopupId = openPopupId,
changePopupId = setOpenPopupId
) => onEachTrackable(feature, layer, currentPopupId, changePopupId, t)}
/>
));
}
And pointToTrackingResultLayer looks like
import L from 'leaflet';
export const pointToTrackingResultLayer = (feature, latlng) =>
L.marker([latlng.lat, latlng.lng], {
icon: myicon(feature.id),
});
I want to move the marker to the new position that is being controlled by the updateLayer function in markers.js
I am trying to trigger the function reportPost() on the button onClick which is located in the infoWindow element. When I click on the marker icon and infoWindow starts to render, the function triggers itself and when the window is already loaded, the button does not work (can't trigger func). How can I prevent this and fix the button?
import { useState, useEffect, useCallback } from "react";
import {
GoogleMap,
useJsApiLoader,
Marker,
InfoWindow,
} from "#react-google-maps/api";
import Axios from "axios";
import markerIcon from "../images/markerIcon.png";
const containerStyle = {
width: "100%",
height: "100%",
};
const options = {
mapId: process.env.MAP_ID,
streetViewControl: false,
};
const center = {
lat: 52.22611704066942,
lng: 19.357910156250004,
};
function Map() {
const [markers, setMarkers] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3001/api/markers").then((response) => {
setMarkers(response.data);
});
}, []);
function reportPost(markerid) {
console.log(markerid);
}
const { isLoaded } = useJsApiLoader({
id: "google-map-script",
googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
});
const onLoad = useCallback(function callback(map) {
setMap(map);
}, []);
const onUnmount = useCallback(function callback(map) {
setMap(null);
}, []);
const [map, setMap] = useState(null);
const [activeMarker, setActiveMarker] = useState(null);
const handleActiveMarker = (marker) => {
setActiveMarker(marker);
};
return isLoaded ? (
<div className="w-100 h-hero flex">
<GoogleMap
mapContainerStyle={containerStyle}
options={options}
center={center}
zoom={6}
onLoad={onLoad}
onUnmount={onUnmount}
>
{markers.map(
(
{ markerid, latitude, longitude, description },
i,
arr
) => {
const position = {
lat: latitude,
lng: longitude,
};
return (
<Marker
key={markerid}
icon={markerIcon}
position={position}
onClick={() => handleActiveMarker(markerid)}
>
{activeMarker === markerid ? (
<InfoWindow
onCloseClick={() => setActiveMarker(null)}
>
<div>
<div>
{description}
</div>
<div>
<button
onClick={reportPost(markerid)}
>
Report Post
</button>
</div>
</div>
</InfoWindow>
) : null}
</Marker>
);
}
)}
</GoogleMap>
</div>
) : null;
}
export default Map;
I think the onclick needs a callback, you can try doing it this way:
<button onClick={() => reportPost(markerid)}>
Report Post
</button>
I'm trying to put a map from google maps API and a combobox popover from #reach/combobox inside a MUI dialog component. But I have found a problem, the combobox popover is not being shown. I realized that it is shown if it is not inside the MUI dialog component.
This is the code snippet for the google maps and combobox parts:
const libraries = ['places'];
const mapContainerStyle = {
height: '100%',
width: '100%',
};
const options = {
mapId: 'c43de04e5c01e012',
scaleControl: true,
scrollwheel: true,
mapTypeControl: false,
keyboardShortcuts: false,
zoomControl: true,
};
const center = {
lat: 43.653225,
lng: -79.383186,
};
const MapsLocation = () => {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
libraries,
});
const [markers, setMarkers] = useState({});
const [selected, setSelected] = useState(null);
const onMapClick = useCallback((e) => {
setMarkers({
lat: e.latLng.lat(),
lng: e.latLng.lng(),
time: new Date(),
});
}, []);
const mapRef = useRef();
const onMapLoad = useCallback((map) => {
mapRef.current = map;
}, []);
const panTo = useCallback(({ lat, lng }) => {
mapRef.current.panTo({ lat, lng });
mapRef.current.setZoom(14);
}, []);
if (loadError) return 'Error';
if (!isLoaded) return 'Loading ...';
return (
<>
<GoogleMap
id="map"
mapContainerStyle={mapContainerStyle}
zoom={9}
center={center}
options={options}
onClick={onMapClick}
onLoad={onMapLoad}
>
<Search panTo={panTo} setMarker={setMarkers}
<Locate panTo={panTo} />
<Marker
key={uuid()}
position={{ lat: parseFloat(markers.lat), lng: parseFloat(markers.lng) }}
onClick={() => {
setSelected(markers);
}}
icon={{
url: '/static/illustrations/retailer.svg',
origin: new window.google.maps.Point(0, 0),
anchor: new window.google.maps.Point(30, 30),
scaledSize: new window.google.maps.Size(55, 55),
}}
/>
{selected ? (
<InfoWindow
position={{ lat: selected.lat, lng: selected.lng }}
onCloseClick={() => {
setSelected(null);
}}
>
<div>
<h2>
Alert
</h2>
<p>Spotted {formatRelative(selected.time, new Date())}</p>
</div>
</InfoWindow>
) : null}
</GoogleMap>
</>
);
};
function Locate({ panTo }) {
return (
<IconButton
aria-label="compass"
onClick={() => {
navigator.geolocation.getCurrentPosition((position) => {
panTo({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
});
}}
>
<ExploreIcon />
</IconButton>
);
}
function Search({ panTo, setMarker }) {
const {
ready,
value,
suggestions: { status, data },
setValue,
clearSuggestions,
} = usePlacesAutocomplete({
requestOptions: {
location: {
lat: () => 43.6532,
lng: () => -79.3832,
},
radius: 100 * 1000,
},
});
const handleInput = (e) => {
setValue(e.target.value);
};
const handleSelect = async (address) => {
setValue(address, false);
clearSuggestions();
try {
const results = await getGeocode({ address });
const { lat, lng } = await getLatLng(results[0]);
setMarker({ lat, lng, time: new Date() });
panTo({ lat, lng });
} catch (error) {
console.log('Error: ', error);
}
};
console.log('data: ', data,'status: ', status);
return (
<div className="search">
<Combobox onSelect={handleSelect}>
<ComboboxInput value={value} onChange={handleInput} disabled={!ready} placeholder="Search your location" />
<ComboboxPopover>
<ComboboxList>
{status === 'OK' && data.map(({ id, description }) => <ComboboxOption key={uuid()} value={description} />)}
</ComboboxList>
</ComboboxPopover>
</Combobox>
</div>
);
}
Then, this component is called in the MUI dialogContent component as follow:
<DialogContent dividers>
<MapsLocation />
</DialogContent>
Now it looks like this (the poopover is not being shown)
I would like to know how I can make the poopover show when it is inside the MUI dialog component.
Give zIndex style to <Combobox/> component. Like:
<Combobox style={{zIndex: 9999999999}}>
...
</Combobox>
I am having trouble using setStates. I stored an array of markers for my Google Map in my state and I am using a for loop to iterate through each marker in order to change the position state of the marker using Google's Geocode API.
Here is my state:
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
markers: [
{
name: "Costco Wholesale",
address: "9151 Bridgeport Rd, Richmond, BC V6X 3L9",
position: { lat: 0, lng: 0 },
placeID: 'ChIJWc2NzuF0hlQRDu0NNhdQCjM'
} //just trying to get this one to work first before I add in the others
],
busy: []
};
Here is the function(declared inside the class):
findLatLong(){
for(let i = 0; i < this.state.markers.length; i++){
Geocode.fromAddress(this.state.markers[i].address).then(
response => {
const { lati, lngi } = response.results[0].geometry.location;
this.state.markers[i].position.setState({lat: lati, lng: lngi})
}
);
}
}
As you can see, I am passing the address contained in the same array element into the .fromAddress function and then using setState to set the lat and lng to the returned value.
I later call the function after the map renders but before the markers do:
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{ lat: 49.166590, lng: -123.133569 }}
>
{this.findLatLong}
{this.state.markers.map((marker, index) => (
<Marker
key={index}
onClick={this.onMarkerClick}
name={marker.name}
position={marker.position}
/>
))}
However marker's position state is not changing and is instead remaining as the filler values I passed during the initial state declaration.
Full code if it helps:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';
import Geocode from 'react-geocode';
const key = '';
Geocode.setApiKey(key);
const mapStyles = {
width: '100%',
height: '100%'
};
export class MapContainer extends Component {
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
markers: [
{
name: "Costco Wholesale",
address: "9151 Bridgeport Rd, Richmond, BC V6X 3L9",
position: { lat: 0, lng: 0 },
placeID: 'ChIJWc2NzuF0hlQRDu0NNhdQCjM'
}
],
busy: []
};
findLatLong(){
for(let i = 0; i < this.state.markers.length; i++){
Geocode.fromAddress(this.state.markers[i].address).then(
response => {
const { lati, lngi } = response.results[0].geometry.location;
this.state.markers[i].position.setState({lat: lati, lng: lngi})
}
);
}
}
componentDidMount() {
this.getList();
}
getList = () => {
fetch('/api/getList')
.then(res => res.json())
.then(percent => this.setState({ busy: percent }))
}
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
onClose = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
render() {
return (
<Map
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={{ lat: 49.166590, lng: -123.133569 }}
>
{this.findLatLong}
{this.state.markers.map((marker, index) => (
<Marker
key={index}
onClick={this.onMarkerClick}
name={marker.name}
position={marker.position}
/>
))}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div>
<h4>{this.state.selectedPlace.name}</h4>
<h4>{this.state.busy}</h4>
</div>
</InfoWindow>
</Map>
);
}
}
Thank you in advance!
Attempt to fix #1
.then(
response => {
const { lati, lngi } = response.results[0].geometry.location;
this.setState(oldState => {
const newMarkers = [oldState.markers];
const modifiedMarker = newMarkers[i];
modifiedMarker.lat = lati;
modifiedMarker.lng = lngi;
return {oldState, markers: [newMarkers]};
//How do i implement the modifiedMarkers?
})
UPDATE
Actually it is better if you mutate the state just once and not inside the loop
findLatLong(){
const newMarkers = [...this.state.markers]
for(let i = 0; i < this.state.markers.length; i++){
Geocode.fromAddress(this.state.markers[i].address).then(
response => {
const { lati, lngi } = response.results[0].geometry.location;
newMarkers[i].position.lat = lati;
newMarkers[i].position.lng = lngi;
}
);
}
this.setState(oldState => {
return { ...oldState, markers: [...newMakers] };
});
}
That's no how you mutate the state, it should be something like this:
this.setState(oldState => {
const newMakers = [...oldState.makers];
const modifiedElement = newMakers[i];
modifiedElement.lat = lati;
modifiedElement.lng = lngi;
return { ...oldState, makers: [...newMakers] };
});
I have read the other questions related to this and tried implementing what the answers were on there.
They recommended adding /*global google */ - did not work
Next was to add const google = window.google; - did not work
I will post the code below and the error.
The error is happening where new google.maps is being called
Map.js:
/* global google */
import { default as React, Component } from 'react';
import raf from 'raf';
import canUseDOM from 'can-use-dom';
const google = window.google;
import { withGoogleMap, GoogleMap, Circle, InfoWindow, Marker } from 'react-google-maps';
import withScriptjs from 'react-google-maps/lib/async/withScriptjs';
const googleMapURL =
'https://maps.googleapis.com/maps/api/js?v=3.27&libraries=places,geometry&key=AIzaSyA7XEFRxE4Lm28tAh44M_568fCLOP_On3k';
const geolocation =
canUseDOM && navigator.geolocation
? navigator.geolocation
: {
getCurrentPosition(success, failure) {
failure("Your browser doesn't support geolocation.");
},
};
const GeolocationExampleGoogleMap = withScriptjs(
withGoogleMap(props =>
<GoogleMap defaultZoom={8} center={props.center}>
{props.center &&
<InfoWindow position={props.center}>
<div>User's Location</div>
</InfoWindow>}
{props.center &&
<Circle
center={props.center}
radius={props.radius}
options={{
fillColor: 'red',
fillOpacity: 0.2,
strokeColor: 'red',
strokeOpacity: 1,
strokeWeight: 1,
}}
/>}
>
{props.markers.map((marker, index) => {
const onClick = () => props.onMarkerClick(marker);
const onCloseClick = () => props.onCloseClick(marker);
return (
<Marker
key={index}
position={marker.position}
title={(index + 1).toString()}
onClick={onClick}
>
{marker.showInfo &&
<InfoWindow onCloseClick={onCloseClick}>
<div>
<strong>
{marker.content}
</strong>
<br />
<em>The contents of this InfoWindow are actually ReactElements.</em>
</div>
</InfoWindow>}
</Marker>
);
})}
</GoogleMap>,
),
);
function generateInitialMarkers() {
const southWest = new google.maps.LatLng(-31.203405, 125.244141);
const northEast = new google.maps.LatLng(-25.363882, 131.044922);
const lngSpan = northEast.lng() - southWest.lng();
const latSpan = northEast.lat() - southWest.lat();
const markers = [];
for (let i = 0; i < 5; i++) {
const position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random(),
);
markers.push({
position,
content: 'This is the secret message'.split(' ')[i],
showInfo: false,
});
}
return markers;
}
export default class GeolocationExample extends Component {
constructor(props) {
super(props);
super(props);
this.state = {
center: null,
content: null,
radius: 6000,
markers: generateInitialMarkers(),
};
const isUnmounted = false;
handleMarkerClick = this.handleMarkerClick.bind(this);
handleCloseClick = this.handleCloseClick.bind(this);
}
handleMarkerClick(targetMarker) {
this.setState({
markers: this.state.markers.map((marker) => {
if (marker === targetMarker) {
return {
...marker,
showInfo: true,
};
}
return marker;
}),
});
}
handleCloseClick(targetMarker) {
this.setState({
markers: this.state.markers.map((marker) => {
if (marker === targetMarker) {
return {
...marker,
showInfo: false,
};
}
return marker;
}),
});
}
componentDidMount() {
const tick = () => {
if (this.isUnmounted) {
return;
}
this.setState({ radius: Math.max(this.state.radius - 20, 0) });
if (this.state.radius > 200) {
raf(tick);
}
};
geolocation.getCurrentPosition(
(position) => {
if (this.isUnmounted) {
return;
}
this.setState({
center: {
lat: position.coords.latitude,
lng: position.coords.longitude,
},
content: 'Location found using HTML5.',
});
raf(tick);
},
(reason) => {
if (this.isUnmounted) {
return;
}
this.setState({
center: {
lat: 60,
lng: 105,
},
content: `Error: The Geolocation service failed (${reason}).`,
});
},
);
}
componentWillUnmount() {
this.isUnmounted = true;
}
render() {
return (
<GeolocationExampleGoogleMap
googleMapURL={googleMapURL}
loadingElement={<div style={{ height: '100%' }}>loading...</div>}
containerElement={<div style={{ height: '100%' }} />}
mapElement={<div style={{ height: '100%' }} />}
center={this.state.center}
content={this.state.content}
radius={this.state.radius}
onMarkerClick={this.handleMarkerClick}
onCloseClick={this.handleCloseClick}
markers={this.state.markers}
/>
);
}
}
You are loading async script. When you initialize google constant there is no google object. You can solve this by using 'ref' for map component. Ref callback fired when google object exists. For example:
<GoogleMap defaultZoom={8} center={props.center} ref={()=>{props.onMapLoad}}>...</GoogleMap>
...
constructor(props) {
...
this.onMapLoad = this.onMapLoad.bind(this)
}
...
onMapLoad() {
/*init markers and all objects with "google" here*/
}
...
<GeolocationExampleGoogleMap
onMapLoad={this.onMapLoad}
...
/>
and, of course, do not init google const, use just google object instead,