I have an existing map that relies on using the setPosition
function on a single instance of Marker
in the v3 Google Maps API. I don't see an obvious way to invoke that function from the Marker
component exported by @react-google-maps/api
.
I want to use the onMouseOver
and onMouseOut
events to show a marker with (summary) information about whatever feature the user is mousing over in a live Google map. The existing javascript site works fine -- it uses the loadGeoJson
method to add about 3,500 features to the map.
The documentation and examples show how to pass a position
prop to the Marker instance in the render
method, but that provides only a static marker location.
In my current javascript
code, I do the following while handling an onMouseOver
event:
function mouseInToRegion(e) {
//...
dataMarker.setLabel({'text': 'some informative string'});
dataMarker.setPosition(e.latLng);
dataMarker.setVisible(true);
}
In the above fragment, dataMarker
is a reference to a single marker instance creating during map initialization (at load time).
Not surprisingly, the onMouseOut
handler does little more than call dataMarker.setVisible(false)
.
How do I accomplish the analogous behavior using @react-google-maps/api
?
You can set the position of the Marker component of @react-google-maps/api by using use state to pass the value of your position in the Marker's position parameter
. Changing the value of this will move the current marker instance to the new coordinate.
I created a sample code wherein I have place data from the json file. I first iterate and get each data putting each on a paragraph. Then everytime you hover on each paragraph, it will pass the data of the place. You will then use the data and change the state variables markerposition
and place
. It will then update the marker and infowindow to show the details of that specific place.
Here's a code snippet and the sample working code:
/*global google*/
import ReactDOM from "react-dom";
import React from "react";
import { GoogleMap, Marker, InfoWindow } from "@react-google-maps/api";
import data from "./data.json";
const defaultLocation = { lat: 40.712775, lng: -74.005973 };
class Map extends React.Component {
state = {
markerposition: defaultLocation,
place: "Default Position - New York"
};
onMouseOverEvent = place => {
this.setState({
markerposition: { lat: place.lat, lng: place.lng },
place: place.name
});
};
render() {
return (
<div>
<GoogleMap
center={defaultLocation}
zoom={8}
mapContainerStyle={{ height: "400px", width: "800px" }}
>
<Marker
//onLoad={onLoad}
position={this.state.markerposition}
>
<InfoWindow options={{ maxWidth: 100 }}>
<span>{this.state.place}</span>
</InfoWindow>
</Marker>
</GoogleMap>
{data.map((place, index) => (
<p key={index} onMouseOver={() => this.onMouseOverEvent(place)}>
{place.name}
</p>
))}
</div>
);
}
}
export default Map;