简体   繁体   English

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

[英]Issues with adding markers with Google Maps Javascript API using React.js

So, I am trying to add a marker on the Google Maps which is part of the functionality of the react.js app I am developing.所以,我试图在谷歌地图上添加一个标记,这是我正在开发的 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(),
    })
}

The issue is, when I run the code, initMap() works.问题是,当我运行代码时, initMap()有效。 I can see the map on my page with map centre located at the defined coordinate.我可以在我的页面上看到 map,map 中心位于定义的坐标处。 For the targetedCityMarker , console.log('testing') can be seen, but somehow the Marker part is not showing up.对于targetedCityMarker ,可以看到console.log('testing') ,但不知何故,Marker 部分没有出现。 What has gone wrong here?这里出了什么问题?

In your Marker() initialization, you are trying to use this.initMap() as a map instance, however, that function does not return anything.在您的Marker()初始化中,您尝试使用this.initMap()作为 map 实例,但是,function 不返回任何内容。

Try to return the map instance you initialized from that function:尝试返回从 function 初始化的 map 实例:

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

and then you'll be able to use it in your Marker() in a way you are doing it now.然后你就可以在你的Marker()中以你现在正在做的方式使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM