在google-map-react中将标记添加到Google Maps [英] Adding Marker to Google Maps in google-map-react

查看:169
本文介绍了在google-map-react中将标记添加到Google Maps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 google-map-react NPM程序包创建Google Map和一些标记.

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

问题:如何将默认的Google Maps标记添加到地图?

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

此Github问题,看来我们需要访问内部Google Maps API,使用 onGoogleApiLoaded 函数.

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

请参考 Google Maps JS API文档中的示例,我们可以使用以下代码来呈现标记,但是如何定义对map的引用?

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!'
});

当前代码:

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>
    );
}

推荐答案

根据自述文件中的描述,这可能并不完全清楚,但是maps参数实际上是maps API对象(和map当然是当前的Google Map实例).因此,您应该将两者都传递给您的方法:

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)}

并使用它们:

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

这篇关于在google-map-react中将标记添加到Google Maps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆