0

I'm trying to get return values for placing a google maps marker on land (continent) or on water (oceans). When I try console log, I should get true for placing the marker on land, and false for placing it on water. However, the marker's value seems to lag behind by one move: For example, placing it on water will return true, then placing it on land will return false, but placing it on land again will return true again.

How can obtain the right value of the "result" variable inside the geocoder callback function?

Why am I getting lagging results and how can it be fixed?

Thank you.

  var result = true;
        function checkMarkerOnLand(event) {

            var geocoder = new google.maps.Geocoder();

            geocoder.geocode({

                "latLng" : event.latLng

            }, function(results, status) {

                if (status !== google.maps.GeocoderStatus.OK) {

                    result = false;
                    //return result;

                } else {

                    result = true;
                    //return result;

                }

            });

            return result;

        }

1 Answer 1

1

The point of a callback is this: - you send a request to a service (that service might be on a different server).
- when the service is ready, it will trigger a callback (= a function you wrote your self) of your choosing.

(It's the equivalent of calling somebody on the phone to ask for a friend's phone number. He doesn't know right now, but he'll call you back when he does)

Right after sending the request, the code just continues. So directly after sending geocoder.geocode(), it will execute return result, long before the service is ready.

So no, you can't use checkMarkerOnLand() as a function that returns a result. Change your logic, so that what ever you were planning with that result, you just handle it in the callback.

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

1 Comment

Can I just ask the Stackoverflow community what happened for this half year old post to suddenly get extra points? Just curious about the mechanics

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.