2011-04-05 6 views
0

자바 스크립트 문제가 있습니다. 검색했지만 문제와 관련성이없는 것은 없습니다.자바 스크립트에서 값을 반환하는 중

기본적으로 나는 두 개의 다른 함수 (codeAddressLat 및 codeAddressLng)를 호출하는 함수 (addToGlobe)가 있습니다. 두 개의 호출 된 함수는 모두 첫 번째 함수에 float 값을 반환해야하며, 두 번째 함수는이를 사용합니다. 하위 함수는 정확하게 올바르게 작동합니다. print 문을 사용하여 각 변수의 "numfinal"변수에 값이 있는지 확인합니다.

그러나 코드에 주석으로 표시된 호출 함수에 print 문을 추가하면 'undefined'가 반환됩니다. 따라서 numfinal 값이 반환 될 때 문제가있는 것 같습니다.

감사합니다 :) 당신은 codeAddressLat에 return 문이없는

function addToGlobe(uname, uid, pmcity) { 
    // Get lat & long of city 
    var pmlat = codeAddressLat(pmcity); 
    var pmlong = codeAddressLng(pmcity); 

    log(pmlat); // PROBLEM! Prints 'undefined' 
    log(pmlong); // PROBLEM! Prints 'undefined' 

    // Rest of function removed to keep it simple 
} 

function codeAddressLat(inputcity) { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 

    geocoder.geocode({ 'address': inputcity}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var llsplit = new Array(); 

      bkresult = String(results[0].geometry.location); 
      bkresult = bkresult.replace(/[\(\)]/g, ""); 
      llsplit = bkresult.split(','); 

      numfinal = parseFloat(llsplit[0]); 
      return numfinal; 

     } else { 
     log('<b><font color="#C40031">Geocode was not successful:</b> ' + status); 
     } 
    }); 
} 

    function codeAddressLng(inputcity) { 
     // Basically the same function as above. Removed for simplicity 
    } 

답변

1

codeAddressLat은 실제로 아무것도 반환하지 않습니다. 익명 함수가 geocoder.geocode으로 전달됩니다.

geocoder.geocode가 비동기 적으로 실행 중이므로 codeAddressLat은 응답을 기다릴 수 없습니다. 따라서 codeAddressLat은 실제로 아무 것도 반환 할 수 없습니다. 대신 codeAddressLat도 비동기 적이어야합니다. 이것은 자바 스크립트에서 일반적인 패턴입니다.

function addToGlobe(uname, uid, pmcity) { 
    codeAddressLat(pmcity, function(pmlat) { 
     // do something with pmlat 
    }); 

    ... 
} 

function codeAddressLat(inputcity, callback) { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 

    geocoder.geocode({ 'address': inputcity}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var llsplit = new Array(); 

      bkresult = String(results[0].geometry.location); 
      bkresult = bkresult.replace(/[\(\)]/g, ""); 
      llsplit = bkresult.split(','); 

      numfinal = parseFloat(llsplit[0]); 

      // instead of returning, call the callback with the result 
      callback(numfinal); 

     } else { 
     log('<b><font color="#C40031">Geocode was not successful:</b> ' + status); 
     } 
    }); 
} 
+0

위대한 작품, 고마워요! :) –

0

, 당신은 codeAddressLat 내에 정의 콜백 함수 내부에 하나 있습니다.

0

함수 codeAddressLat은 실제로 값을 반환하지 않고 값을 반환하는 콜백 함수를 전달합니다. numfinal 값을 검색하기 위해 지오 코드 조작이 완료 될 때까지 기다려야합니다.

0

함수 codeAddressLat은 아무런 값도 반환하지 않으므로 출력으로 정의되지 않습니다.

+0

codeAddressLat은 아무것도 반환하지 않습니다. 즉, 기본적으로 정의되지 않은 값을 반환합니다. return 문은 codeAddressLat 자체에 없습니다. –

+0

@Matt - 맞습니다. 동봉 된 기능을보고 싶지 않습니다. 감사합니다 –

0

codeAddressLat 메서드 호출에서 geocode 요청이 호출자에게 값을 반환하지 않습니다. 귀하의 수익은 다른 범위입니다.

0

이 방법이 유용합니까? 이 비동기 인 것처럼 보인다 geocoder.geocode 함수

function codeAddressLat(inputcity) { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 

    return geocoder.geocode({ 'address': inputcity}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var llsplit = new Array(); 

      bkresult = String(results[0].geometry.location); 
      bkresult = bkresult.replace(/[\(\)]/g, ""); 
      llsplit = bkresult.split(','); 

      numfinal = parseFloat(llsplit[0]); 
      return numfinal; 

     } else { 
     log('<b><font color="#C40031">Geocode was not successful:</b> ' + status); 
     } 
    }); 
} 
0

있다. codeAddressLatcodeAddressLng 함수는 geocoder.geocode 함수에 서버에서 데이터가 반환되기 전에 void를 반환합니다.

주위를 둘러 쌀 방법은 geocoder.geocode으로 전화를 중첩하고 모든 범위에서 AJAX 호출이 반환되면 원하는 두 매개 변수를 전달하는 addToGlobe 함수를 호출 할 수 있도록 변수 범위 지정을 사용하는 것입니다. 이 같은

뭔가 : AJAX의 세계에

codeAddressLatAndLong(pmcity); 

function addToGlobe(pmlatlat, pmlatlong) { 
    log(pmlat); // PROBLEM! Prints 'undefined' 
    log(pmlong); // PROBLEM! Prints 'undefined' 

    // Rest of function removed to keep it simple 
} 

function codeAddressLatAndLong(inputcity) { 
    // stuff 

    geocoder.geocode({ 'address': inputcity}, function(results, status) { 
     // stuff goes here 
     pmlat = parseFloat(llsplit[0]); 
     geocoder.geocode({...}, function(results, status) { 
     // more stuff 
     pmlatlong = something; 
     addToGlobe(pmlatlat, pmlatlong); 
     }); 
    }); 
} 

에 오신 것을 환영합니다.

관련 문제