简体   繁体   中英

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.

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. I can see the map on my page with map centre located at the defined coordinate. For the targetedCityMarker , console.log('testing') can be seen, but somehow the Marker part is not showing up. 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.

Try to return the map instance you initialized from that function:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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