Dynamically Adding Markers on google-map-react

11,098

You may try:

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({  img_src }) => <div><img src={img_src} className="YOUR-CLASS-NAME" style={{}} /></div>;

class MyClass extends Component {
  constructor(props){
    super(props);
    this.state = {
        markers: [],
    }
  }

  componentDidMount(){
    // or you can set markers list somewhere else
    // please also set your correct lat & lng
    // you may only use 1 image for all markers, if then, remove the img_src attribute ^^
    this.setState({
      markers: [{lat: xxxx, lng: xxxx, img_src: 'YOUR-IMG-SRC'},{lat: xxxx, lng: xxxx, img_src: 'YOUR-IMG-SRC' },{lat: xxxx, lng: xxxx,  img_src: 'YOUR-IMG-SRC'}],
    });
  }

  render() {
    return (
      <GoogleMapReact
        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}
        style={{height: '300px'}}
      >
            {this.state.markers.map((marker, i) =>{
              return(
                <AnyReactComponent
                  lat={marker.lat}
                  lng={marker.lng}
                  img_src={marker.img_src}
                />

              )
            })}      
      </GoogleMapReact>
    );
  }
}
MyClass.defaultProps = {
  center: {lat: 59.95, lng: 30.33},
  zoom: 11
};

If this has error, please show here too, then we can fix it later

===========

ADDED EXAMPLE FOR CLICK-EVENT ON MARKERS

 markerClicked(marker) {
   console.log("The marker that was clicked is", marker);
   // you may do many things with the "marker" object, please see more on tutorial of the library's author:
  // https://github.com/istarkov/google-map-react/blob/master/API.md#onchildclick-func 
  // Look at their examples and you may have some ideas, you can also have the hover effect on markers, but it's a bit more complicated I think 
 }

 render() {
    return (
      <GoogleMapReact
        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}
        style={{height: '300px'}}
      >
            {this.state.markers.map((marker, i) =>{
              return(
                <AnyReactComponent
                  lat={marker.lat}
                  lng={marker.lng}
                  img_src={marker.img_src}
                  onChildClick={this.markerClicked.bind(this, marker)}
                />

              )
            })}      

      </GoogleMapReact>
    );
  }

Once again, post here some errors if any ^^ !

Share:
11,098
Gayan Kavirathne
Author by

Gayan Kavirathne

I'm a Graduate at Department Of Computer Science and Engineering University Of Moratuwa-Sri Lanka. Currently working as a Post Graduate Student and Research Assistant at DataSEARCH center the University Of Moratuwa.

Updated on June 16, 2022

Comments

  • Gayan Kavirathne
    Gayan Kavirathne almost 2 years

    What I wan't to do is to show the location picked from some mobile devices on the Map. Data about the locations are there..

    What I need here is to add Markers on the map depending on the data received from the server.

    Assume I have set the location data ({Lat,Lang}) to the state markers Then How can I add this to show in Map.

    My Map Code is as follows!

    import React, { Component } from 'react';
    import GoogleMapReact from 'google-map-react';
    
    const AnyReactComponent = ({ text }) => <div>{text}</div>;
    
    class MyClass extends Component {
      constructor(props){
        super(props);
    
      }
    
      render() {
        return (
          <GoogleMapReact
            defaultCenter={this.props.center}
            defaultZoom={this.props.zoom}
            style={{height: '300px'}}
          >
            <AnyReactComponent
              lat={59.955413}
              lng={30.337844}
              text={'Google Map'}
            />
          </GoogleMapReact>
        );
      }
    }
    MyClass.defaultProps = {
      center: {lat: 59.95, lng: 30.33},
      zoom: 11
    };
    
    export default MyClass;

    This Code is from the answer Implementing google maps with react

    Used npm package :- google-map-react

  • Gayan Kavirathne
    Gayan Kavirathne about 7 years
    No Error It Works! But, Image Doesn't appear! Just a square. In the Image property class I should enter as png/jpg/ico am I Right?
  • thinhvo0108
    thinhvo0108 about 7 years
    Did you inspect those "square" images to check their url, maybe their src is invalid ^^ ? Besides, please just use img's valid url, don't add png/ico or anything ^^ className here in jsx just means their CSS class (you may just leave it blank like className="") thanks
  • Gayan Kavirathne
    Gayan Kavirathne about 7 years
    Yes! It was problem with source!!.. Can you give me one last help?
  • Gayan Kavirathne
    Gayan Kavirathne about 7 years
    If I wan't to get the onTap event of the marker! How should I proceed? Thanks a lot Buddy! You saved me days of work!
  • thinhvo0108
    thinhvo0108 about 7 years
    You're welcome ^^ ! Actually, the above answer is just a very simple example of GoogleMap for react. The library we're using is used for rendering react-component on the map, which is useful for server-side rendering, therefore, the tap-event for marker will be a bit more complicated. I will show you some demo on how to implement tap-event now, but if you truly want to have full features with more "natural" googlemap (markers + events, polylines, directions etc.), you may consider using another powerful library: github.com/tomchentw/react-google-maps
  • Gayan Kavirathne
    Gayan Kavirathne about 7 years
    Thanks a lot Buddy, you save my day!! :)
  • Gayan Kavirathne
    Gayan Kavirathne about 7 years
    I tried to use that library, But I can.t understand the way it's example code is written. But Your one is straight forward( You have written it with classes & example in the tomchentw uses const)
  • thinhvo0108
    thinhvo0108 about 7 years
    You're welcome, I'm glad you had it working. However, the click or hover function for the current library on Markers should be implemented more ^^ Try your best!
  • Gayan Kavirathne
    Gayan Kavirathne over 6 years
    Link does not work for me. Gives a 404. Maybe it's a private repository. :)
  • Debasish
    Debasish almost 5 years
    I am not able to trigger the click event on click of marker. Please suggest
  • Red Baron
    Red Baron almost 4 years
    @thinhvo0108 if you get chance to look at this: stackoverflow.com/questions/62644430/… I need some help here, can't seem to get it to work
  • thinhvo0108
    thinhvo0108 almost 4 years
    @RedBaron I answered