1

I am using google.maps.geocoder to get a location request in my angular app. In a request I provide a callback function with results. now if I want to call my other function which displays the marker on map the code breaks unexpectedly. I also can not set any variables defined on my component, it looks like every global variable/function is undefined when the code in the Geocoder callback function is happening.

How can I fix this and get data from my callback function in my app?

googleMapsFindLocation() {
        var address = this.locationName;

        this.geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == 'OK') {
                var mapCustomObj = new MapCustomObj();
                var marker = {
                    position: { lat: 46, lng: 16 },
                    info:
                        '<h2>' + "tekst" + '</h2></br>' +
                        '<p>' + "" + '</p>' +
                        '<p>' + "this.raceDto.seasonName" + '</p>' +
                        '<p>' + "this.raceDto.lat" + ' - ' + "this.raceDto.long" + '</p>'
                };
                mapCustomObj.marker = marker;

                //HERE IS THE PROBLEM. If i call showMap the code breaks, and the code in my showMap doesnt even get hit in debug
                this.showOnMap(mapCustomObj);

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }

1 Answer 1

4

change your callback to an arrow function: from function (results, status) { } to (results, status) => { } . the issue is when the callback will be called this will be the global object, not the component. but arrow functions bind this to its current context where it's declared.

Tip: don't declare variables with var. prefer const first, let second.

Tip2: since the object { 'address': address } has the same key and variable naming you can pass as { address }

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

Comments

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.