Reputation: 397
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?
Upvotes: 0
Views: 115
Reputation: 6031
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.
Upvotes: 1