0

I am using google-map-react and want to be able to dynamically change position and radius. Currently the chosen radius is stored in a database and is fetched using the getRadius() function, but I don't know how and when to call it, therefore the radius is always displayed at 1000 meters.

I've tried using the setRadius method but I don't know how to access it from outside the apiIsLoaded function. Please help!

import React, { useRef } from 'react';
import GoogleMapReact from 'google-map-react';
import Marker from './MapMarker';
import {getUserInfo} from '../firebaseConfig'

class SimpleMap extends React.Component {

  constructor(props){
    super(props);
    this.googleMapCircle = React.createRef();
    this.state = {
      lat: "",
      lng: "",
      userPos: "",
      radius: 1000,
    };
  }
  
  static defaultProps = {
    center: {
      lat: 59.8,
      lng: 17.63889
    },
    zoom: 11
  };

  componentDidMount = () => {
    if (navigator.geolocation){
    navigator.geolocation.watchPosition(this.currentCoords)
    this.getRadius();
  }
  };

  currentCoords = (position) => {
    const latitude = position.coords.latitude
    const longitude = position.coords.longitude
    this.setState(prevState => ({
      userPos: {...prevState.userPos,
        lat: latitude, lng: longitude
      }
    }) 
    )
  };

  getRadius = () => {
    getUserInfo().then((result) => {
      this.setState({
        radius: result.radius
      })  
      }); 
  };

  componentDidUpdate = (prevState) => {
    if (prevState.radius !== this.state.radius) {
      //This is where I want to update radius
      }
    };

     apiIsLoaded = (map, maps, setUserPos, setUserRadius) => {
        var circle = new maps.Circle({
        ref:this.googleMapCircle,
        strokeColor: "001e57",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#bbd0ff",
        fillOpacity: 0.3,
        map:map,
        center: setUserPos,
        radius: setUserRadius
      });
    };
 
  render() {
    
    const setCenter = this.state.userPos;
    const setUserPos = this.state.userPos;
    const setUserRadius = this.state.radius;


    return (

      <div style={{ height: '100%', width: '100%' }}>

        <GoogleMapReact
          bootstrapURLKeys={{ key: 'API_KEY' }}
          defaultCenter={this.props.center}
          center={setCenter}
          defaultZoom={this.props.zoom}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps}) => this.apiIsLoaded(map, maps, setUserPos, setUserRadius)}
        > 

          <Marker
            lat={setUserPos.lat}
            lng={setUserPos.lng}
            color="blue"
          />

        </GoogleMapReact>
      </div>
    );
  }
}
 
export default SimpleMap;
Pagemag
  • 2,779
  • 1
  • 7
  • 17
Siri
  • 1
  • 1

1 Answers1

1

You can check this working code sample and code snippet below where I am calling a changeRadius function everytime my input radius changes the value. It will then change the radius of the circle.

import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import "./style.css";

let circle;
class GoogleMaps extends Component {
  constructor(props) {
    super(props);

    this.state = {
      center: { lat: 40.756795, lng: -73.954298 },
      inputRad: 100
    };
  }

  onChange = e => {
    this.setState({
      inputRad: e.target.value
    });
  };
  changeRadius = () => {
    console.log(Number(this.state.inputRad));
    circle.setRadius(Number(this.state.inputRad));
  };

  render() {
    console.log(this.state.inputRad)
    const apiIsLoaded = (map, maps) => {
      circle = new maps.Circle({
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.3,
        map,
        center: this.state.center,
        radius: this.state.inputRad
      });
    };
    return (
      <div>
        <div style={{ height: "400px", width: "100%" }}>
          <input
            placeholder="Enter radius"
            type="number"
            min="100"
            name="inputRad"
            onChange={this.onChange}
          />
          <input
            value="Change circle radius"
            type="submit"
            onClick={this.changeRadius}
          />
          <GoogleMapReact
            bootstrapURLKeys={{
              key: "API_KEY",
              libraries: ["places"]
            }}
            defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
            defaultZoom={15}
            center={this.state.center}
            yesIWantToUseGoogleMapApiInternals
            onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps)}
          />
        </div>
      </div>
    );
  }
}
export default GoogleMaps;
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Pagemag
  • 2,779
  • 1
  • 7
  • 17