首页 > 解决方案 > 使用 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 部分没有出现。这里出了什么问题?

标签: javascriptreactjsgoogle-maps

解决方案


在您的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()您现在正在做的方式使用它。


推荐阅读