Mohammadrez Taheri
Mohammadrez Taheri

Reputation: 53

React google maps ,Update Markers OnIdle

I want to get map container corners and convert to google maps coordinates after that onIdle event I want to update markers and my list component, using React-google-maps https://github.com/istarkov/google-map-react Please Help , thanks

import _ from "lodash";

import React , {Component , PropTypes} from 'react';
import {Col} from 'antd';

import { withGoogleMap, GoogleMap, Marker , Polygon } from "react-google-maps";
import MarkerClusterer from "react-google-maps/lib/addons/MarkerClusterer";
import withScriptjs from 'react-google-maps/lib/async/withScriptjs';

const AsyncGoogleMap = _.flowRight(
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    ref={props.onMapLoad }
    onIdle={props.onMapIdle}
    defaultZoom={14}
    defaultCenter={{ lat: 35.7206037, lng: 51.38875 }}
  >
    <MarkerClusterer
      averageCenter
      enableRetinaIcons
      gridSize={2}
    >
    {/*imagePath={'./styles/images/blue-pin'}*/}
    {props.markers.map(marker => (
      <Marker
        icon={{
          url: './styles/images/blue-pin.png'
        }}
        position={{ lat: marker.lat, lng: marker.lon }}
        key={marker.id}
      />
    ))}
    </MarkerClusterer>
    {/*<Polygon path={path} /> */}
  </GoogleMap>
));
export default class AsyncGoogleMapComponent extends Component {
  constructor(props){
    super(props)
    this.state = {
      markers: [],
    };

  }
  componentWillReceiveProps(newProps){
    {/*console.log(newProps.projects); */}
    this.setState({
      markers: newProps.projects
    })
  }
  componentDidMount(){

  }
  render() {
    {/*console.log(this.state.markers); */}
    return (
      <Col span={12} className="gutter-row card_group" ref="child">
        <AsyncGoogleMap
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyBebpbsHU358P8sfvxfn7fFmsQIB2UNk94"
          loadingElement={
            <div style={{ height: `100%` }}>

            </div>
          }
          containerElement={
            <div style={{ height: `100%` }} />
          }
          mapElement={
            <div id='googlemap' ref="targetDiv" style={{ height: `100%` }} />
          }
          onMapIdle={ ()=> { console.log('map is ready') } }
          markers={this.state.markers}

        />
      </Col>
    );
  }
}

Upvotes: 0

Views: 2537

Answers (1)

Sumuray Petrovich
Sumuray Petrovich

Reputation: 76

First, you can define onChange map handler:

<GoogleMap
 onChange={props.onMapChange}
/>

next add to your component

<AsyncGoogleMap 
 onMapChange={this.handleMapChange}
/>

and in your AsyncGoogleMapComponent you will receive new parameters of map

  handleMapChange = ({ center, zoom, bounds }) => {
    ....
    this.updateMarkers();
  };

Upvotes: 1

Related Questions