javascript - 使用 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 部分没有出现。这里出了什么问题?
解决方案
在您的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()
您现在正在做的方式使用它。
推荐阅读
- applescript - 不允许脚本调试器发送击键
- c# - Nuget Library - 将库的 DLL 复制到当前项目的输出目录
- tensorflow - CNN Keras 对象定位 - 错误的预测
- android - Android SQLite 数据库检查查询是否存在?
- spring - 通过 JMS 与外部系统集成。集群环境
- nginx - 使用 proxy_pass 时,如何让 nginx 为与 index.html 相邻的资产提供服务?
- c# - 当继承类的模型也有验证时,如何对其进行验证?
- angular - RxJS 将 Observable 配置为多播
- java - 在多线程程序中没有得到预期的结果
- javascript - VBA - 将创建的 HTML 元素附加到 HEAD 元素的问题