Search code examples
javascriptreactjsgoogle-mapsreact-google-maps

Marker not shown in google-maps-react


I want to show a simple map with a marker in it.

This is my code:

import React, { Component } from 'react';
import {Map, Marker, GoogleApiWrapper} from 'google-maps-react';
import demoFancyMapStyles from "./MapStyle.json";

export class MapContainer extends Component {
  propTypes: {
      currentPosLat: React.PropTypes.string.isRequired,
      currentPosLon: React.PropTypes.string.isrequired
  }

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Map google={this.props.google}
                zoom={14}
                options={{ styles: demoFancyMapStyles }}
                center={{ lat: this.props.currentPosLat, lng: this.props.currentPosLon }}>

        <Marker position={{lat: this.props.currentPosLat, lon: this.props.currentPosLon}} />

      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: ("[myApiKey]")
}) (MapContainer)

The map renders fine and even sets the center to my current position. However, the marker is not shown on the map. I tried setting a custom icon for the marker but this changed nothing.

And whenever I try to use this approach in step 1 like this:

import {GoogleMap, Marker, GoogleApiWrapper} from 'google-maps-react';
[...]
<GoogleMap
        defaultZoom={14}
        defaultOptions={{ styles: demoFancyMapStyles }}
        defaultCenter={{ lat: this.props.currentPosLat, lng: this.props.currentPosLon }}>

  <Marker position={{lat: this.props.currentPosLat, lon: this.props.currentPosLon}} />

</GoogleMap>
[...]

I get this error:

Error: Element type is invalid: expected a string (for built-in 
components) or a class/function (for composite components) but got: 
undefined. You likely forgot to export your component from the file 
it's defined in, or you might have mixed up default and named imports.

Check the render method of `MapContainer`.

Which approach is the better one, and where am I doing wrong?


Solution

  • I think you confused 2 packages. The google-maps-react which you are referring to, does not have GoogleMap component, but you are trying to import it:

    import {GoogleMap, Marker, GoogleApiWrapper} from 'google-maps-react';
    

    Also, the link to example you provided refers to react-google-maps package. So, I feel you definitely must ave confused the two.