简体   繁体   中英

Value for variable in callback function - Google Maps

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;

        }

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.

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