Javascript function return function issue

I am trying to work with google maps API and I am having problems. I created a getPoint function that takes an address. It uses google api to turn this address into a GPoint object using the GClientGeocoder.getLatLng (address, callback) function. GetLatLng () passes the address and callback function, as you can see below. I want the getPoint () function that I wrote to return the dot variable passed to the callback function from the getLatLng () call. Am I struggling to figure out how to do this, or even if it can be done?

function getPoint(address) {
  var geocoder = new GClientGeocoder();

  return geocoder.getLatLng(
    address,
    function(point){
      return point;
    }
  );
}

Thanks in advance for your help!

+3
source share
3 answers

GClientGeocoder.getLatLng - , return getPoint , .

, , , :

function getPoint(address, callback) {
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
        address,
        function(point){
            /* asynch operation complete.
             * Call the callback with the results */
            callback(point)
        }
    );
}

( ):

function getPoint(address, callback) {
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
        address,
        callback // GClientGeocoder will call the callback for you
    );
}

:

, , , JavaScript, , , , :

var map = new GMap2(/*...*/);
var addresses = []; // list of address strings
for(var i=0; i < addresses.length; i++) {
    getPoint(addresses[i], function(point) { // pass the callback function
        map.addOverlay(/*...*/); // map variable is in scope
    })
}

.

+6

, . , , , - , - .

, :

var myPoint = getPoint(theAddress);
doSomethingWithPoint(myPoint);
doSomethingElseWithPoint(myPoint);

function getPoint(address, callback) {
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, callback);
}
getPoint(theAddress, function(myPoint) {
    doSomethingWithPoint(myPoint);
    doSomethingElseWithPoint(myPoint);
});
+2

You cannot do this. getLatLng()is an asynchronous function: it will send an HTTP request and call a callback after receiving a response. Meanwhile, your local script execution will continue, and getLatLng()will return before your call.

0
source

Source: https://habr.com/ru/post/1721513/


All Articles