Reputation: 185
I am trying to load a marker on the google map but I'm not sure how to do it. In the documentation it shows the next example:
const MyMapComponent = compose(
withProps({
googleMapURL: "api key",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
{props.isMarkerShown && (
<Marker position={{ lat: -34.397, lng: 150.644 }} />
)}
</GoogleMap>
));
ReactDOM.render(<MyMapComponent isMarkerShown />, document.getElementById("root"));
But what I am actually trying to do is to create the map component and call it in another component. The map loads fine when I call it but my question is: how do I pass the marker to the component where I call my map?
This is my map component:
import React from "react";
import ReactDOM from "react-dom";
import { compose, withProps } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker
} from "react-google-maps";
const MyMapComponent = compose(
withProps({
googleMapURL:
"api key",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={15} defaultCenter={{ lat: 46.802681, lng: 23.764006 }}>
{props.isMarkerShown && (
<Marker position={{ lat: 46.802681, lng: 23.764006 }} />
)}
</GoogleMap>
));
export default MyMapComponent;
And then I call it in another component like this:
import MyMapComponent from './myMap';
const Contact = () => {
return (
<div class="contact">
<MyMapComponent />
</div>
)
}
Upvotes: 0
Views: 390
Reputation: 93
In your Contact
component while returning the MyMapComponent
pass the prop isMarkerShown
as the way you have defined it in your Map Component as it requires the prop isMarkerShown
to render the Marker and if you want to pass dynamic coordinates to it you could write something like this in your Contact Component:
import MyMapComponent from './myMap';
const Contact = () => {
return (
<div class="contact">
<MyMapComponent isMarkerShown lat={49.076} lng={42.8777} />
</div>
)
}
And in your Map Component:
import React from "react";
.
.
const MyMapComponent = compose(
withProps({
googleMapURL:"API Key",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
)},
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={15}
defaultCenter={{ lat: props.lat, lng: props.lng }}>
{props.isMarkerShown && (
<Marker position={{ lat: props.lat, lng: props.lng }} />
)}
</GoogleMap>
));
export default MyMapComponent;
Upvotes: 1