2012-01-31 2 views
2

내가 읽은 것에서는 가능하지 않다고 생각하지만 다음 코드에서 내지도 표식이 null인지 확인하기 위해 멀리 떨어져 있습니까? 프로토 타입에 대해 읽었지만, 필자가 사용해야하는 것인지 확실하지 않습니다. 다음은 코드입니다.표현식 내부 객체 - 자바 스크립트

this.currentLocation = function(latitude, longitude) { 
    if (loc_marker != null) { 
     loc_marker.setPosition(new google.maps.LatLng(latitude, longitude); 
    } 
    else { 
     var loc_marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(latitude, longitude), 
      title: "Here" 
     }); 
     loc_marker.setMap(map); 
    }   
}; 

위치가 변경 될 때마다 Google지도에서 마커를 이동하려고합니다. 마커가 설정되어 있는지 확인하고 싶으면 setPosition()을 사용하여 위치를 변경합니다.

의견을 보내 주시면 감사하겠습니다. 대신

if (loc_marker != null) { 

답변

2

어디 loc_marker 실제로 정의했다

if (loc_marker != null) { //Tests for null and for undefined 
if (loc_marker === null) { //Tests for null 
if (typeof loc_marker === 'object' && loc_marker === null) { //Another null test, albeit redundant 
if (typeof loc_marker === 'undefined') { //Tests for undefined 
if (loc_marker) { //Test for a defined non-null value 

? else 블록 ( although JavaScript doesn't work that way)에서 정의하려는 것처럼 보입니다.

loc_marker을 선언하면 저장해야합니다. 코드는 잘 작동해야합니다. 마커가 정의이 도움이

희망,

피트

+0

내 가장 큰 문제가 될 것으로 보인다. 나는 그것을 선언 할 곳이 확실하지 않습니다. 표현의 범위를 벗어나면 매번 새로운 마커가 생성됩니다. 하나의 마커를 만든 다음 위치가 바뀔 때마다 위치를 변경해야합니다. 이 일을 마무리 짓는 데는 가까운 사이라고 생각합니다. 그것을 선언하는 방법/장소에 대한 제안? – mkyong

+0

하나의 마커 만 필요하면'this'의 일부로 만들 것이므로'this.currentLocation'과 같은 범위에'this.loc_marker = {};'를 추가하십시오. 그렇게하면 함수에서'loc_marker' 대신'this.loc_marker'를 참조 할 수 있습니다. – pete

+0

그것은 작동합니다! 당신의 도움을 주셔서 감사합니다! – mkyong

0

당신은 loc_marker는 "글로벌"변수를해야 할 것이다

if (typeof loc_marker != 'undefined') { 
2

을 시도 즉, 그 함수가 호출 될 때 동일한 개체에 변수가 가리키는마다. 위의 코드에서 함수의 범위에 다른 지역 변수 만 만듭니다. 같은보십시오 : 당신이 ... 무엇을 찾고있어 할 것 다음의 모두

var loc_marker = null; 
this.currentLocation = function(latitude, longitude) { 
    if (loc_marker != null) { 
     loc_marker.setPosition(new google.maps.LatLng(latitude, longitude); 
    } 
    else { 
     loc_marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(latitude, longitude), 
      title: "Here" 
     }); 
     loc_marker.setMap(map); 
    }   
};