Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

javascript - Adding Marker to Google Maps in google-map-react

I am using the google-map-react NPM package to create a Google Map and several markers.

Question: How can we add the default Google Maps markers to the map?

From this Github issue, it seems that we need to access the internal Google Maps API using the onGoogleApiLoaded function.

Referring to an example from the Google Maps JS API docs, we can use the following code to render the marker, but how do we define the references to map?

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
});

Current Code:

renderMarkers() {
    ...
}

render() {
    return (
        <div style={{'width':800,'height':800}}>
            <GoogleMap
                bootstrapURLKeys={{key: settings.googleMapApiKey}}
                defaultZoom={13}
                defaultCenter={{ 
                    lat: this.props.user.profile.location.coordinates[1], 
                    lng: this.props.user.profile.location.coordinates[0]
                }}
                onGoogleApiLoaded={({map, maps}) => this.renderMarkers()}
                yesIWantToUseGoogleMapApiInternals
            >
            </GoogleMap>
        </div>
    );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit:
Since this answer was posted the docs (and likely, the API) of the GoogleMapReact element was changed to support children. Any child with lat and lng would be rendered at the corresponding location on the map, as also indicated by @Jobsamuel's answer.

The onGoogleApiLoaded callback should not be used for this purpose, as it is inferior to the declarative style and would not be re-run if changes are made to the map.


Original answer (outdated):

This may not be entirely clear from the description in the Readme, but the maps argument is, in fact, the maps API object (and map is, of course, the current Google Map instance). Therefore, you should pass both to your method:

onGoogleApiLoaded={({map, maps}) => this.renderMarkers(map, maps)}

and use them:

renderMarkers(map, maps) {
  let marker = new maps.Marker({
    position: myLatLng,
    map,
    title: 'Hello World!'
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...