0

내지도에 마커를 놓은 다음 해당 마커의 위치를 ​​사용하여 일부 다각형을 그립니다. 그러나 marker.getPosition()은 처음에는 값을 반환하지 않는 것 같습니다. 이전 마커 위치를 얻으려면 함수를 다시 호출해야합니다. 사람이 구글지도 콜백을 사용지도 마커 getPosition()은 처음 함수 호출시 Google지도에서 작동하지 않습니다.

function codeAddress() { 
    var address = fubar; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     map.setCenter(results[0].geometry.location); 
     map.setZoom(1); 
     if (marker == null){ 
     marker = new google.maps.Marker({ 
      map: map, 
     }); 
     } 
     marker.setPosition(results[0].geometry.location); 
    }); 
    document.write(marker.getPosition()); //this displays nothing 
} 

답변

4

(see parameter 2 in the documentation) 인 이유에 대한 어떤 제안이 그 not synchronous 때문에 않습니다. function(results,status) 비트는 마법이 일어나는 곳입니다. Google에서 주소를 지오 코딩 한 경우 실행됩니다. 그때까지는 아무 것도 표시 할 수 없습니다.

function codeAddress() { 
    var address = fubar; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     map.setCenter(results[0].geometry.location); 
     map.setZoom(1); 
     if (marker == null){ 
      marker = new google.maps.Marker({ 
       map: map, 
      }); 
     } 
     marker.setPosition(results[0].geometry.location); 
     alert("Alert 1"); 
     alert(marker.getPosition()); 
    }); 
    alert("Alert 2"); 
} 

그리고 당신은 alert("Alert 1")

+0

모든 권고를 활용할 수 있기 전에 alert("Alert 2")가 나타납니다 표시됩니다

이 시도 이 문제를 해결하려면? – user1330217

+0

당신은 그 주위를 감당할 수 있습니다, 당신은 (경고처럼) 귀하의 논리 콜백 안에 넣어해야합니다. 웹 사이트에 텍스트를 삽입/편집해야한다면 [jQuery] (http://www.jquery.com) –

1

당신은 무엇을 최선의 방법에 $ .Deferred()

function codeAddress() { 
    var address = fubar; 
    var d = $.Deferred(); 
    var marker; 

    geocoder.geocode({ 'address': address}, function(results, status) { 
     map.setCenter(results[0].geometry.location); 
     map.setZoom(1); 
     if (marker == null){ 
     marker = new google.maps.Marker({ 
      map: map, 
     }); 
     } 
     marker.setPosition(results[0].geometry.location); 
     d.resolve(); 
    }); 
    d.done(function(){ 
     document.write(marker.getPosition()); 
    }); 
} 
관련 문제