I’m trying to build a similar map on Airbnb where you can see place markers as you drag the map. I want to display the “hotel” markers from the Google Places API on the map.
Using the following JS code in Google Maps I can show hotels on Google Maps, but I want to use React Google Maps using React.
// This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: //
1> Tiago Alves..:You can pass a reference to your
GoogleMap
, create a service withnew google.maps.places.PlacesService()
, then with that service you can usenearbySearch()
to search for hotels, restaurants, etc. as Google Where the Nearby Search API documentation says:With "Nearby Search" you can search for locations within a specified area by keyword or type.
To initiate the
fetchPlaces()
method, you can use theonTilesLoaded
prop from the GoogleMap component orcomponentDidMount()
. In the example below , I'm also passingfetchPlaces
toonBoundChanged
because I'm searching based onbounds
so every time I move the map it will give me new positions , please note:const bounds = refs.map.getBounds(); 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'] };This is my example
recompose
:/*global google*/ import React from "react" import { compose, withProps, withHandlers, withState } from "recompose" import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps" const MyMapCompOnent= compose( withProps({ googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places", loadingElement: , containerElement: , mapElement: , }), withScriptjs, withGoogleMap, withState('places', 'updatePlaces', ''), withHandlers(() => { const refs = { map: undefined, } return { onMapMounted: () => ref => { refs.map = ref }, fetchPlaces: ({ updatePlaces }) => { let places; const bounds = refs.map.getBounds(); 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 ( {props.places && props.places.map((place, i) => )} ) }) export default class MyFancyComponent extends React.PureComponent { render() { return ( ) } }