|
| 1 | +import {useEffect} from 'react'; |
| 2 | + |
| 3 | +import { |
| 4 | + useGoogleMap, |
| 5 | + usePlacesService |
| 6 | +} from '@ubilabs/google-maps-react-hooks'; |
| 7 | + |
| 8 | +const PlacesExample = () => { |
| 9 | + const {map} = useGoogleMap(); |
| 10 | + |
| 11 | + // Get the places service from the usePlacesService hook |
| 12 | + const service = usePlacesService(); |
| 13 | + |
| 14 | + useEffect(() => { |
| 15 | + if (!map || !service) { |
| 16 | + return; |
| 17 | + } |
| 18 | + |
| 19 | + const bounds = new google.maps.LatLngBounds(); |
| 20 | + |
| 21 | + const request = { |
| 22 | + location: {lat: 53.550481787761306, lng: 9.992336490896136}, |
| 23 | + radius: 500, |
| 24 | + type: 'cafe' |
| 25 | + }; |
| 26 | + |
| 27 | + function callback( |
| 28 | + results: google.maps.places.PlaceResult[], |
| 29 | + status: google.maps.places.PlacesServiceStatus |
| 30 | + ) { |
| 31 | + if (status === google.maps.places.PlacesServiceStatus.OK) { |
| 32 | + for (let index = 0; index < results.length; index++) { |
| 33 | + const name = results[index].name; |
| 34 | + const position = results[index].geometry?.location; |
| 35 | + const openingHours = results[index].opening_hours; |
| 36 | + |
| 37 | + const isOpenStatus = openingHours ? 'Is open' : 'Closed'; |
| 38 | + |
| 39 | + if (!position) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + const marker = new google.maps.Marker({ |
| 44 | + map, |
| 45 | + position |
| 46 | + }); |
| 47 | + |
| 48 | + map?.fitBounds(bounds.extend(position)); |
| 49 | + |
| 50 | + const infowindow = new google.maps.InfoWindow({ |
| 51 | + position, |
| 52 | + content: `<b>${name}</b> is ${isOpenStatus}` |
| 53 | + }); |
| 54 | + |
| 55 | + infowindow.open(map, marker); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + service.nearbySearch(request, callback); |
| 61 | + }, [map]); |
| 62 | + |
| 63 | + return null; |
| 64 | +}; |
| 65 | + |
| 66 | +export default PlacesExample; |
0 commit comments