2012-04-27 2 views
0

이전 자바 스크립트 경험이 없습니다.콜백에서 값을 반환

가 나는 값이 위도와 LNG 반환 사용하려면 다음과 같은 기능을 구현하기 위해 노력하고있어 :

function get_address() { 
    var geocoder = new google.maps.Geocoder() 

    geocoder.geocode({ address: "SE-17270 Sverige"}, 
    function(locResult) { 

    var lat = locResult[0].geometry.location.lat(); 
    var lng = locResult[0].geometry.location.lng(); 
    alert(lat); 
    alert(lng); 
    }) 
} 

내가 이걸 어떻게해야합니까?

 function get_address(postcode) 
     { 
     var geocoder = new google.maps.Geocoder() 
     var lat 
     var lng 

     geocoder.geocode({ address: "SE-"+postcode+"Sverige"}, 
     function(locResult) { 

      lat = locResult[0].geometry.location.lat(); 
      lng = locResult[0].geometry.location.lng(); 
     }) 
     return lat,lng 
     } 

답변

0

변수를 선언 latlng 외부 콜백 기능 :

그래서 내가하고 싶은 것을이 같은 것입니다.

+0

'지오 코더. geocode'는 async입니다 ... –

3

지오 코딩 결과를 처리하는 콜백을 사용

function myCallback(lat, lng) { 
    // Process lat and lng. 
} 

function get_address(callback) { 
    var geocoder = new google.maps.Geocoder() 

    geocoder.geocode({ address: "SE-17270 Sverige"}, 
     function(locResult) { 
      var lat = locResult[0].geometry.location.lat(); 
      var lng = locResult[0].geometry.location.lng(); 
      callback(lat, lng); 
     } 
    ); 
} 
.... 
get_address(myCallback); 
1

전역 변수를 사용하거나 예를 들어 배열의 값을 반환 할 수 :

전역 변수 방법 :

lat = ""; 
lng = ""; 

function get_address() { 
    var geocoder = new google.maps.Geocoder() 

    geocoder.geocode({ address: "SE-17270 Sverige"}, 
    function(locResult) { 

    lat = locResult[0].geometry.location.lat(); 
    lng = locResult[0].geometry.location.lng(); 
    alert(lat); 
    alert(lng); 
    }) 
} 

배열 방법 :

DEMO

CODE (JQuery와 온로드 포함) :

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> 

정확한 구문 오류를 다음 기능을 시작 :210

function get_address() { 
    var geocoder = new google.maps.Geocoder() 

    geocoder.geocode({ address: "SE-17270 Sverige"}, 
    function(locResult) { 

    var lat = locResult[0].geometry.location.lat(); 
    var lng = locResult[0].geometry.location.lng(); 

    thearray = []; 
    thearray.push(lat); 
    thearray.push(lng); 
    return thearray; 
    }) 
} 
+0

그래서'geocoder.geocode'는 비동기식입니다. –

1

헤더 섹션 구글 라이브러리를 추가

var lat = ""; 
var lng = ""; 

function getLatLng(callback) { 
    lat = callback.lat(); 
    lng = callback.lng(); 
    alert(lat +" "+lng); 
} 

$(function() { 
    var geocoder = new google.maps.Geocoder() 

    geocoder.geocode({ 
     address: "SE-17270 Sverige" 
    }, function(locResult) { 
     getLatLng(locResult[0].geometry.location); 
    }); 
}); 
관련 문제