使用 React.js 使用 Google Maps Javascript API 添加标记的问题



所以,我正在尝试在谷歌地图上添加一个标记,这是我正在开发的 react.js 应用程序功能的一部分。

const MapCode = document.createElement('script')
MapCode.src =`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}`
window.document.body.appendChild(MapCode)
MapCode.addEventListener('load', ()=>{
this.initMap()
this.targetedCityMarker()
})
}
initMap(){
new window.google.maps.Map(this.googleMap.current,{
zoom: 7.5,
center:{ lat: this.state.cityCoordinates[1], lng:this.state.cityCoordinates[0] },
disableDefaultUI: true,
})
}
targetedCityMarker(){
console.log('testing')
new window.google.maps.Marker({
position: { lat: this.state.cityCoordinates[1], lng:this.state.cityCoordinates[0] },
map:this.initMap(),
})
}

问题是,当我运行代码时,initMap()工作.我可以在我的页面上看到地图,地图中心位于定义的坐标处。对于targetedCityMarker,可以看到console.log('testing'),但不知何故标记部分没有显示。这里出了什么问题?

Marker()初始化中,您尝试将this.initMap()用作映射实例,但是,该函数不返回任何内容。

尝试返回从该函数初始化的映射实例:

initMap(){
return new window.google.maps.Map(this.googleMap.current,{
zoom: 7.5,
center:{ lat: this.state.cityCoordinates[1], lng:this.state.cityCoordinates[0] },
disableDefaultUI: true,
})
}

然后,您将能够以现在的方式在Marker()中使用它。

最新更新