Why is this variable undefined or not returned?

前端 未结 2 696
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 03:33

I have the following code:

/*
 * converts a string to geolocation and returns it
 */

function stringToLatLng(string){
    if(typeof string == \"string\"){
              


        
2条回答
  •  無奈伤痛
    2021-01-26 03:54

    Something like this:

    function stringToLatLng(strloc, callback){
        if(typeof string == "string"){
            geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': strloc}, function(results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                  callback.call({}, results[0].geometry.location);
               } else {
                  console.log("Geocode was not successful for the following reason: " + status);
               }
            });
       }
    }
    
    stringToLatLng('New York', function(pos){
        console.log(pos);
    });
    

    In your code, when you return, you are actually returning from the function(results, status){..} function, not the stringToLatLng function, as said in the comments its an asynchronous call, so you must use a callback.

提交回复
热议问题