0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

YOUUUUUU ARE THE ONEEE! HOLY COWWW..IT WORRRKED...[after i calmed down] i will check-mark you answer later. i did click it but it says I have to wait a bit.
Heyy, can I ask you another a Google Maps related issue?
@LearnerSamuelX Sure, but create a new question if you think it’s a good StavkOverflow material... Otherwise we can probably do it on some chat or something...
I did create one, but no one seems can answer it, and that is why I am looking to you for help
Ah, right! I’m traveling around at the moment, but will find it and take a look at it later! ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.