How to add Google Maps Waypoints in react.js? - reactjs

I am trying to implement Google Maps Directions Waypoints using #react-google-maps/api library to show the directions between starting and ending points.
With mock data coordinates it seems to work, but not with the data coming from the api/json file.
Here is the Codesandbox link
And the code below
import React, { useState } from "react";
import {
DirectionsRenderer,
DirectionsService,
GoogleMap,
LoadScript,
Marker
} from "#react-google-maps/api";
const containerStyle = {
width: "100%",
height: "900px"
};
const center = {
lat: 51.4332,
lng: 7.6616
};
const options = {
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
maxZoom: 17
};
export default function App({ parks }) {
const [directions, setDirections] = useState();
const directionsCallback = React.useCallback((response) => {
console.log(response);
if (response !== null) {
if (response.status === "OK") {
console.log("response", response);
setDirections(response);
} else {
console.log("response: ", response);
}
}
}, []);
//destination
const destinationPark = parks.features.find(
(park) => park.properties.id === 28007
);
//origin
const originPark = parks.features.find(
(park) => park.properties.id === 35299
);
const google = window.google;
// data to add as waypoints
const waypointsParks = parks.features.filter(
(park) => park.properties.id !== 28007 && park.properties.id !== 35299
);
return (
<div style={{ width: "100%", height: "100%" }}>
<LoadScript googleMapsApiKey={google_api_key}>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={6}
options={options}
>
<Marker
position={{
lat: parseFloat("52.50920109083271"),
lng: parseFloat("13.416411897460808")
}}
/>
)
<DirectionsService
callback={directionsCallback}
options={{
destination: `${destinationPark.properties.coordinates[1]}, ${destinationPark.properties.coordinates[0]}`,
origin: `${originPark.properties.coordinates[1]}, ${originPark.properties.coordinates[0]}`,
travelMode: "DRIVING"
// waypoints: [
// {
// location: new google.maps.LatLng(
// 52.596714626379296,
// 14.70278827986568
// )
// },
// {
// location: new google.maps.LatLng(
// 52.56193313494678,
// 11.52648542963747
// )
// }
// ]
}}
/>
<DirectionsRenderer
options={{
directions: directions
}}
/>
</GoogleMap>
</LoadScript>
</div>
);
}
Any help will be appreciated.

Assuming the failure is the following based upon codesandbox log.
Directions request returned no results.
Your application must handle the case where no results are found.
If you feel like this is a mistake, please provide a simplified example with just the origin, destination, waypoints, etc that you believe should return a result.

Related

InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama #react-google-maps/api

I am using #react-google-maps/api and loading the script from cdn to my public directory index.html file.
I get InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama and the markers do not appear on my map. Weird thing is that it is totally random to get this error. Sometimes it works without any problem. That is what I do not understand in the first place.
import React, { useEffect } from 'react';
import { GoogleMap, Marker } from '#react-google-maps/api';
import mapStyles from './mapStyles';
//google map height 100
import './MapDisplay.css';
import { connect } from 'react-redux';
const mapContainerStyle = {
height: '100%',
width: '100%',
};
const options = {
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
};
const MapDisplay = ({
userLocation,
mouseHoverIdR,
selectedInfoR,
searchedResults,
unAuthNoSearchResults,
selectedLocationInfoWindowS,
}) => {
const onClickMarker = (e) => {
selectedLocationInfoWindowS({
selectedInfoR: e,
type: 'infoWindowLocations',
});
};
const onClickMap = () => {
selectedLocationInfoWindowS({
type: '',
selectedInfoR: {
_id: '',
},
});
};
return (
<div id='map'>
<GoogleMap
id='map_canvas'
mapContainerStyle={mapContainerStyle}
zoom={12}
center={userLocation}
options={options}
onClick={() => onClickMap()}
>
{!unAuthNoSearchResults &&
searchedResults.map((searchedResult) => {
if (
mouseHoverIdR === searchedResult._id ||
selectedInfoR._id === searchedResult._id
) {
var a = window.google.maps.Animation.BOUNCE;
}
return (
<Marker
position={searchedResult.coordinates}
key={searchedResult._id}
clickable
onClick={() => onClickMarker(searchedResult)}
animation={a}
id={'hello'}
/>
);
})}
</GoogleMap>
</div>
);
};
How can I fix the error that I get when I try to display the marker on the map?

react and google Directions API without map

I need the results from .route() in my internal app, not going into any map. I need the duration and distance between the origin and destination for further calculations in my app.
So far I tried it with a callback func:
function getTravelTime(origin, destination, cb) {
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: "DRIVING"
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
cb(null, {
duration: moment.utc(moment.duration(result.routes[0].legs[0].duration.value, 'seconds').as('milliseconds')).format('HH:mm'),
distance: result.routes[0].legs[0].distance.value
});
} else {
cb('error');
console.log(result);
}
}
);
};
and I tried to read it like this:
let tInfo = getTravelTime(origin, destination, function (err, dist) {
if (!err) {
let distanceBetweenLocations = dist.distance;
let durationBetweenLocations = dist.duration;
// Or with saving to a state
setTravelInformation(prevState => ({
distance: dist.distance,
duration: dist.duration
}));
}
});
Is there any possibility to calculate distance and travel time without needing to render the map?
So far I got this, heavily shortened as I got much more logic for other components in the same file:
import {
withGoogleMap,
GoogleMap,
withScriptjs,
Marker,
DirectionsRenderer
} from "react-google-maps";
const getTravelTime = (origin, destination) => {
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
},
(result, status) => {
console.log(result)
if (status === google.maps.DirectionsStatus.OK) {
setDirections(result);
} else {
setError(result);
}
}
);
}
Do I need to use HoC withScriptjs and wrap my component around this?
You could use useState and useEffect, see https://reactjs.org/docs/hooks-effect.html
const [distance, setDistance] = useState(0);
const [duration, setDuration] = useState(0);
useEffect(() => {
if (distance && duration) {
console.log("Distance & Duration have updated", distance, duration);
}
}, [distance, duration]);
When you receive Directions results, update the distance and duration with whatever value you need:
directionsService.route({
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
setDistance(result.routes[0].legs[0].distance.value);
setDuration(result.routes[0].legs[0].duration.value);
} else {
console.error("error fetching directions", result, status);
}
}
);
Here is a working snippet using #react-google-maps/api
https://codesandbox.io/s/react-google-mapsapi-directions-service-m7qif
You need to use a valid API key in case it doesn't work.
import React, { Component } from "react";
import { withGoogleMap, GoogleMap, withScriptjs, DirectionsRenderer, Marker } from "react-google-maps";
import { compose, withProps } from "recompose";
import PropTypes from "prop-types";
class MapDirectionsRenderer extends Component {
static propTypes = {
waypoints: PropTypes.array,
places: PropTypes.array
};
state = {
directionsRef: '',
directions: null,
error: null
};
componentDidMount() {
const { places, origDest } = this.props;
const waypointsArray = places.map(p => ({
location: p.geocode,
stopover: true
}));
const origin = origDest.origin_geocode;
const destination = origDest.destination_geocode;
const directionsService = new window.google.maps.DirectionsService();
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: window.google.maps.TravelMode.DRIVING,
waypoints: waypointsArray.length >= 1 ? waypointsArray : [],
},
(result, status) => {
if (status === window.google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
}
}
);
}
render() {
return (
this.state.directions && (
<DirectionsRenderer
directions={this.state.directions}
/>
)
);
}
}
const MapView = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&v=3.exp",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `300px`, width: '100%' }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap
key={props.travelMode}
defaultZoom={12}
center={{ lat: 0, lng: 0 }}
>
<MapDirectionsRenderer
places={props.wayPoints}
origDest={props.originDestination}
/>
</GoogleMap >
));
export default MapView;

How to display the route on ReactGoogleMap?

Describe the bug 🐛
Using the Google Maps API I'm getting the directions and I'm creating DirectionsRenderer all looks correct, the map is displayed but the route is not displayed, not sure if this option is not available on GoogleMapReact
To Reproduce 🔍
Steps to reproduce the behavior:
Add the request to get the directions in the constructor
constructor(props: any){
super(props)
const DirectionsService = new google.maps.DirectionsService();
this.state = {};
DirectionsService.route(
{
origin: new google.maps.LatLng(19.5682414, -99.0436029),
destination: new google.maps.LatLng(19.7682414, -99.0436029),
travelMode: window.google.maps.TravelMode.DRIVING,
},
(result, status) => {
// console.log("status", status);
if (status === window.google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
console.log(result);
} else {
console.error(`error fetching directions ${result}`);
}
}
);
At this point, the directions are set in the state so let's try to render it.
render() {
return (
// Important! Always set the container height explicitly
<div id="BrainMap" className="schedulerMap justify-content-md-left">
<GoogleMapReact
bootstrapURLKeys={{ key: process.env.REACT_APP_MAPS_API_KEY }}
defaultCenter={this.initialPosition.center}
defaultZoom={this.initialPosition.zoom}
>
{this.state.directions && (
<DirectionsRenderer
directions={this.state.directions}
options={{
polylineOptions: {
strokeOpacity: 0.4,
strokeWeight: 4,
},
preserveViewport: true,
suppressMarkers: true,
}}
/>
)}
</GoogleMapReact>
</div>
);
}
Expected behavior 💭
I expect to see the route displayed on the map.
Other Context
In other examples looks like they are using other GoogleMap Component and other functions with composing, I will like to avoid this.
Code
import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import { DirectionsRenderer } from "react-google-maps";
import MapCard from "../commons/MapCard";
import "./Scheduler.css";
type BrainMapState = {
directions?: any;
}
class BrainMap extends Component {
state: BrainMapState;
initialPosition = {
center: {
lat: 19.4978,
lng: -99.1269,
},
zoom: 12,
};
constructor(props: any){
super(props)
const DirectionsService = new google.maps.DirectionsService();
this.state = {};
DirectionsService.route(
{
origin: new google.maps.LatLng(19.5682414, -99.0436029),
destination: new google.maps.LatLng(19.7682414, -99.0436029),
travelMode: window.google.maps.TravelMode.DRIVING,
},
(result, status) => {
// console.log("status", status);
if (status === window.google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
console.log(result);
} else {
console.error(`error fetching directions ${result}`);
}
}
);
//const directionsRenderer = new google.maps.DirectionsRenderer();
}
render() {
return (
// Important! Always set the container height explicitly
<div id="BrainMap" className="schedulerMap justify-content-md-left">
<GoogleMapReact
bootstrapURLKeys={{ key: process.env.REACT_APP_MAPS_API_KEY }}
defaultCenter={this.initialPosition.center}
defaultZoom={this.initialPosition.zoom}
>
{this.state.directions && (
<DirectionsRenderer
directions={this.state.directions}
options={{
polylineOptions: {
strokeOpacity: 0.4,
strokeWeight: 4,
},
preserveViewport: true,
suppressMarkers: true,
}}
/>
)}
</GoogleMapReact>
</div>
);
}
}
export default BrainMap;
Since GoogleMapReact library does not support Directions Service API, the following component could be introduced to render directions:
function DirectionsRenderer(props: {
map: google.maps.Map | null;
origin: google.maps.LatLngLiteral;
destination: google.maps.LatLngLiteral;
}) {
async function getRoute(
origin: google.maps.LatLngLiteral,
destination: google.maps.LatLngLiteral
): Promise<google.maps.DirectionsResult> {
const directionsService = new google.maps.DirectionsService();
return new Promise(function (resolve, reject) {
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
},
(result: any, status: google.maps.DirectionsStatus) => {
if (status === google.maps.DirectionsStatus.OK) {
resolve(result);
} else {
reject(result);
}
}
);
});
}
async function renderRoute() {
const directions = await getRoute(props.origin, props.destination);
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(props.map);
directionsRenderer.setDirections(directions);
}
useEffect(() => {
renderRoute().catch((err) => {
console.log(err);
});
}, []);
return null;
}
Usage
function MapWithADirectionsRenderer(props: {
center: google.maps.LatLngLiteral;
zoom: number;
}) {
const [map, setMap] = useState<google.maps.Map | null>(null);
function handleApiLoaded(mapInstance: google.maps.Map, google: any) {
setMap(mapInstance);
}
return (
<div style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "--Google Maps Key goes here--" }}
defaultCenter={props.center}
defaultZoom={props.zoom}
onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
>
{map && (
<DirectionsRenderer
map={map}
origin={{ lat: 40.756795, lng: -73.954298 }}
destination={{ lat: 41.756795, lng: -78.954298 }}
/>
)}
</GoogleMapReact>
</div>
);
}
Demo
Note: Google Maps Key needs to be specified
Result

google.maps.places.PlacesService(map) always returns null

Am trying to fetch nearby restaurants using google maps API with react-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;
here HOME_MAP = https://maps.googleapis.com/maps/api/js?key=${KEY}&v=3.exp&libraries=geometry,drawing,places
Inside fetchplaces method, new window.google.maps.places.PlacesService(map) always returns null and service.nearBySearch throws not a function error.
Please help.
There are at least two issues with your example
const map = refs.map;
const service = new window.google.maps.places.PlacesService(map);
^^^
map object here corresponds to the instance of Map component while google.maps.places.PlacesService class expects Google Maps object instead. In case of react-google-maps library PlacesService could be instantiated like this:
mapMounted(element) {
const mapObject = element.context[MAP];
const service = new google.maps.places.PlacesService(map);
//...
}
where
<GoogleMap
ref={this.mapMounted}
defaultZoom={this.props.zoom}
defaultCenter={this.props.center}/>
There is also a typo at line:
service.nearBySearch(request, (results, status) => {
^^^^^^^^^^^^
function should be renamed to nearbySearch
Here is a demo that demonstrates how to utilize Places Service with react-google-maps library.

Center AND zoom by prop in react-google-maps?

I am building a Zillow-like map with real estate property points in page body, and filters in page header.
What I need is to center AND zoom react-google-maps map, when selecting Google place from external Google places filter. Currently I am able to center map on place select, but not zoom in (that is because i need to refetch data on every zoom in/out, so need to control zoom, see code below).
I tried to use fitBounds from here, but ref in my code is always undefined.
I have API that fetches points, based on filters, with params like this:
viewPort: {
northEast: { lat: 57.04834755670983, lng: 24.3255340332031 },
southWest: { lat: 56.83635114109457, lng: 23.93826596679685 }
},
priceMin: 0,
priceMax: 500,
propType: "RENT",
numRooms: 3,
...
In header section there is also address filter input, that has Google places autocomplete. When selected, Google provides info about place:
"geometry" : {
...
"viewport" : {
"northeast" : {
"lat" : 56.95662478029149,
"lng" : 24.2054917802915
},
"southwest" : {
"lat" : 56.9539268197085,
"lng" : 24.2027938197085
}
}
...
Here is my Map component:
import React, { Component } from 'react';
import { compose, withProps, withState, withHandlers } from "recompose";
import {
withGoogleMap,
GoogleMap,
Marker,
} from "react-google-maps";
import { MarkerClusterer } from "react-google-maps/lib/components/addons/MarkerClusterer";
const defaultMapOptions = {
fullscreenControl: false,
streetViewControl: false,
};
const PropertyMap = compose(
withProps({
loadingElement: <div>Loading...</div>,
containerElement: <div style={{ height: "500px" }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withState('zoom', 'onZoomChange', 11),
withHandlers(() => {
const refs = {
map: undefined,
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onZoomChanged: ({ onZoomChange, onMapBoundsChange }) => () => {
onZoomChange(refs.map.getZoom())
onMapBoundsChange(refs.map.getBounds());
},
onDragEnd: ({ onMapBoundsChange }) => () => {
onMapBoundsChange(refs.map.getBounds());
},
onMarkerClustererClick: () => (markerClusterer) => {
const clickedMarkers = markerClusterer.getMarkers()
console.log(`Current clicked markers length: ${clickedMarkers.length}`)
console.log(clickedMarkers)
}
}
}),
withGoogleMap
)(props =>
<GoogleMap
defaultCenter={props.defaultCenter ? props.defaultCenter : { lat: 56.9425, lng: 24.1319 }}
zoom={props.zoom}
ref={props.onMapMounted}
onZoomChanged={props.onZoomChanged}
onDragEnd={props.onDragEnd}
defaultOptions={defaultMapOptions}
>
<MarkerClusterer
onClick={props.onMarkerClustererClick}
averageCenter
enableRetinaIcons
gridSize={60}
key={props.mapUid}
>
{props.features !== null && props.features.map(feature => {
const coord = { lng: feature.geometry.coordinates[0], lat: feature.geometry.coordinates[1] };
return <Marker key={feature.id} position={coord} />;
})}
</MarkerClusterer>
</GoogleMap>
);
export default PropertyMap;
So I think I would like to make it possible to pass zoom param in props, like this:
<PropertyMap
mapUid={this.state.mapUid}
features={this.state.features}
key={this.state.defaultCenter ? `${this.state.defaultCenter.lat}` : '1'}
defaultCenter={this.state.defaultCenter}
defaultZoom={calculateZoomFromViewPort(this.state.viewPort)}
onMapBoundsChange={this.handleMapBoundsChange}
/>
This way I could calculateZoomFromViewPort(this.state.viewPort), but then I need to somehow set it to withState zoom default value.
So what I need is some how pass default zoom value to withState('zoom', 'onZoomChange', 11), (11 is hardcoded, currently). But I am new to recompose package, but is it heavily used in react-google-maps package examples.
If you have other ideas, how to zoom and center map based on viewport & center params from Google place, please share!
fitbounds() is the recommended way to achieve auto zoom. Remember refs always created after first render of the component. I have made changes in your code by adding fitBounds. There might be few syntax errors as I prefer to use react-google-maps like class based utility wrapper. It's easier to manage with redux and component lifecycles. Below is the latest code:
import React, { Component } from 'react';
import { compose, withProps, withState, withHandlers } from "recompose";
import {
withGoogleMap,
GoogleMap,
Marker,
} from "react-google-maps";
import { MarkerClusterer } from "react-google-maps/lib/components/addons/MarkerClusterer";
const defaultMapOptions = {
fullscreenControl: false,
streetViewControl: false,
};
const PropertyMap = compose(
withProps({
loadingElement: <div>Loading...</div>,
containerElement: <div style={{ height: "500px" }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withState('zoom', 'onZoomChange', 11),
withHandlers(() => {
const refs = {
map: undefined,
}
return {
onMarkersUpdate: ()=> () => {
if(refs.map){
const mapBounds = new google.maps.LatLngBounds();
//just add markers position into mapBounds
markers.forEach((marker)=>{
mapBounds.extend(marker.position)
});
this.refs.map.fitBounds(mapBbounds);
}
},
onZoomChanged: ({ onZoomChange, onMapBoundsChange }) => () => {
onZoomChange(refs.map.getZoom())
onMapBoundsChange(refs.map.getBounds());
},
onDragEnd: ({ onMapBoundsChange }) => () => {
onMapBoundsChange(refs.map.getBounds());
},
onMarkerClustererClick: () => (markerClusterer) => {
const clickedMarkers = markerClusterer.getMarkers()
console.log(`Current clicked markers length: ${clickedMarkers.length}`)
console.log(clickedMarkers)
}
}
}),
withGoogleMap
)(props =>
<GoogleMap
defaultCenter={props.defaultCenter ? props.defaultCenter : { lat: 56.9425, lng: 24.1319 }}
zoom={props.zoom}
ref='map'
onZoomChanged={props.onZoomChanged}
onDragEnd={props.onDragEnd}
defaultOptions={defaultMapOptions}
>
{props.onMarkersUpdate()}
<MarkerClusterer
onClick={props.onMarkerClustererClick}
averageCenter
enableRetinaIcons
gridSize={60}
key={props.mapUid}
>
{props.features !== null && props.features.map(feature => {
const coord = { lng: feature.geometry.coordinates[0], lat: feature.geometry.coordinates[1] };
return <Marker key={feature.id} position={coord} />;
})}
</MarkerClusterer>
</GoogleMap>
);
export default PropertyMap;
Please feel free to react out me. If you make a codesandbox for this. It will be easier to fix syntax errors. And Don't miss out fitbounds(). It makes things easier for us.

Resources