2

I am trying to use places library, It requires map instance to call the library but map instance is only available inside onLoad, I am trying to use the places library whenever the center change(inside onCenterChange).

import React, { useEffect, useState, useCallback } from 'react';
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';

import GoogleMapReact from 'google-map-react';
import List from './List'

export default function Nearby(){
    const { isLoaded, loadError } = useJsApiLoader({
        googleMapsApiKey: "My_Key" 
      })


      const onLoad = useCallback(
        function onLoad (map) {
          var loc= new window.google.maps.LatLng(6.9270786, 79.861243);
          var request = {
            location: loc,
            radius: '500',
            type: ['hospital'],
          };
          function callback(results, status) {
              if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                  console.log(results)
              } 
          }

          let service = new window.google.maps.places.PlacesService(map);
          service.nearbySearch(request,callback)

        }
      )

    function onCenterChanged(){
        //Need to use service.nearbySearch(request,callback) here
    }    


    return(
        <div className='map-container'>
            <div className = 'google-map'>
            <GoogleMap mapContainerStyle={{ height: '91vh', width: '75vw' }}
                zoom={14}
                onLoad={onLoad}
                center= { currentPos}
                onCenterChanged={onCenterChanged()}
                
                >

            </GoogleMap>
            </div>
        </div>
 
    )
}
Fenaz
  • 23
  • 4

1 Answers1

0

So, for anyone looking for the answers, here is how you can make use of the Map instance outside onLoad method.

Step 1

Create a Ref to hold the instance

import React from 'react'

// ... component declaration here
const mapRef= React.useRef(null)


// then in your return function
<GoogleMap
// ...other props
onLoad={(map) => map.current = map}
/>

This allows you to use the map instance methods like

pan to

e.g

mapRef.current.panTo({lat:'some latitude', lng:'some longitude'})