【问题标题】:Issues with adding markers with Google Maps Javascript API using React.js使用 React.js 使用 Google Maps Javascript API 添加标记的问题
【发布时间】:2020-07-05 17:37:54
【问题描述】:

所以,我正在尝试在 Google 地图上添加一个标记,这是我正在开发的 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()works。我可以在我的页面上看到地图,地图中心位于定义的坐标处。对于targetedCityMarker,可以看到console.log('testing'),但不知何故,标记部分没有出现。这里出了什么问题?

【问题讨论】:

    标签: javascript reactjs google-maps


    【解决方案1】:

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

    【讨论】:

    • 你是唯一的人! HOLY COWWW ..It WORRRKED...[我平静下来后]我会检查你稍后回答。我确实点击了它,但它说我需要等一下。
    • 嘿,我可以再问你一个与 Google 地图相关的问题吗?
    • @LearnerSamuelX 当然可以,但是如果您认为这是一个很好的 StavkOverflow 材料,请创建一个新问题...否则我们可能会在聊天或其他内容中进行...
    • 我确实创建了一个,但似乎没有人能回答它,这就是我向您寻求帮助的原因
    • 啊,对了!我现在正在四处旅行,但稍后会找到它并看看它! ;)
    猜你喜欢
    • 2022-11-26
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多