2013-06-10 3 views
0

내 청취자가지도에 사각형을 설정할 때만 서로를 취소하는 것처럼 보이지만 경보 또는 다른 것을 호출 할 때 어려움을 겪고 있습니다.한 번만 실행되는 Google지도 리스너

이 완벽하게 작동합니다 :

google.maps.event.addDomListener(document.getElementById("overlay" + me), 'click', function() { 
    displayMessage(me); //displays the current overlay index on screen (IE 1 of 30) 
}); 

위는 단순히지도 (30 IE 1)에 오버레이의 인덱스를 표시합니다. 적절한 오버레이 색인으로 클릭 한 모든 오버레이에서 작동합니다.

이 그다지는 :

google.maps.event.addDomListener(document.getElementById("overlay" + me), 'click', function() { 

    alert("Called"); 
    curOverlayRectangle.setOptions(overlayRectangleOptions); //defined by C# to js 
    curOverlayRectangle.setBounds(incomingOverlayBounds[me]); 
    curOverlayRectangle.setMap(map); 
    alert("Finished"); 

}); 

위의지도에 이미 오버레이를 통해 사각형을 추가 할 예정이다. 실제로는 클릭 한 첫 번째 오버레이에 직사각형을 추가하지만 다른 오버레이를 클릭하면 아무 것도 발생하지 않습니다.

일단 내가 첫 번째 오버레이를 클릭하면 통과하고 그려진 사각형으로 끝났기 때문에 리스너가 호출되지 않는 것처럼 보입니다. 그런 다음 다른 오버레이를 클릭하면 경고가 발생하지 않습니다 ...

저는 꽤 오랫동안이 작업을 해오 고 있습니다. 감사!

EDIT1 :

//get is simply the index 
function tempAddListener(get) { 

    //alert("adding: " + get); 
    if (document.getElementById("overlay" + get) != null) { //check to see if div is there 
     google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function() { 

      displayMessage("listener fired at overlay: " + get); //if enabled, works fine 
      //displayOverlayRectangle(incomingOverlayBounds[get]); //if enabled, listener fires but seems to delete all my other listeners for the overlays 

     }); 
    } else { 
     //could not find the div 
    } 

} 

Edit2가

//took out all defines 

//#region geoObjs 
var incomingOverlayBounds = []; 
var incomingOverlaySourceURL = []; 
var incomingOverlayRotation = []; 
var incomingOverlayRectangle = []; 
function initOverlays(){ 
    //most of these are taken out 
    incomingOverlayBounds[0] = new google.maps.LatLngBounds(new google.maps.LatLng(29.7883456702236,-82.384843759249), new 
    incomingOverlayRotation[16] = 0; 
    incomingOverlayBounds[17] = new google.maps.LatLngBounds(new google.maps.LatLng(29.4715356702236,-82.3839748493845), new google.maps.LatLng(29.51265,-82.33674)); 
    incomingOverlaySourceURL[17] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_20.jpg"; 
    incomingOverlayRotation[17] = 0; 
    incomingOverlayBounds[18] = new google.maps.LatLngBounds(new google.maps.LatLng(29.4584356702236,-82.3840587432067), new google.maps.LatLng(29.49955,-82.33683)); 
    incomingOverlaySourceURL[18] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_21.jpg"; 
    incomingOverlayRotation[18] = 0; 
    incomingOverlayBounds[19] = new google.maps.LatLngBounds(new google.maps.LatLng(29.4431556702236,-82.4158516259991), new google.maps.LatLng(29.48427,-82.36863)); 
    incomingOverlaySourceURL[19] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_022.jpg"; 
    incomingOverlayRotation[19] = 0; 
    incomingOverlayBounds[20] = new google.maps.LatLngBounds(new google.maps.LatLng(29.4593656702236,-82.4157191765652), new google.maps.LatLng(29.50048,-82.36849)); 
    incomingOverlaySourceURL[20] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_023.jpg"; 
    incomingOverlayRotation[20] = 0; 
    incomingOverlayBounds[21] = new google.maps.LatLngBounds(new google.maps.LatLng(29.4736856702236,-82.4151858519302), new google.maps.LatLng(29.5148,-82.36795)); 
    incomingOverlaySourceURL[21] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_024.jpg"; 
    incomingOverlayRotation[21] = 0; 
    incomingOverlaySourceURL[51] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_054.jpg"; 
    incomingOverlayRotation[51] = 0; 

    displayIncomingOverlays(); 

} 
//#endregion   


function initialize() { 
    //initialize google map objects 
    map = new google.maps.Map(document.getElementById(gmapPageDivId), gmapOptions);        //initialize map  
    initOverlays(); //initialize all the incoming overlays 
} 

var incomingOverlayBounds = []; 
var incomingOverlaySourceURL = []; 
var incomingOverlayRotation = []; 
var overlays = []; 
function displayIncomingOverlays() { 
    for (var i = 0; i < incomingOverlayBounds.length; i++) { 
     overlaysOnMap[i] = new CustomOverlay(incomingOverlayBounds[i], incomingOverlaySourceURL[i], map, incomingOverlaySourceURL[i]); 
     overlaysOnMap[i].setMap(map); 

     //displayOverlayRectangle(incomingOverlayBounds[i]); //add all the rectangles 
    } 
} 

function CustomOverlay(bounds, image, map, rotation) { 
    //iterate here 
    overlayCount++; 

    // Now initialize all properties. 
    this.bounds_ = bounds; 
    this.image_ = image; 
    this.map_ = map; 

    preservedRotation = rotation; 

    if (overlayPrevious != null) { 
     overlayPrevious.setMap(null); 
    } 

    // We define a property to hold the image's div. We'll 
    // actually create this div upon receipt of the onAdd() 
    // method so we'll leave it null for now. 
    this.div_ = null; 
} 
CustomOverlay.prototype.onAdd = function() { 

    if (overlayPrevious != null) { 
     overlayPrevious.setMap(null); 
    } 

    // Note: an overlay's receipt of onAdd() indicates that 
    // the map's panes are now available for attaching 
    // the overlay to the map via the DOM. 

    // Create the DIV and set some basic attributes. 
    var div = document.createElement("div"); 
    div.id = "overlay" + overlaysOnMap.indexOf(this); 
    div.style.borderStyle = 'none'; 
    div.style.borderWidth = '0px'; 
    div.style.position = 'absolute'; 
    div.style.opacity = preserveOpacity; 

    // Create an IMG element and attach it to the DIV. 
    var img = document.createElement('img'); 
    img.src = incomingOverlaySourceURL[overlaysOnMap.indexOf(this)]; //this.image 
    img.style.width = '100%'; 
    img.style.height = '100%'; 
    img.style.position = 'absolute'; 
    div.appendChild(img); 

    //get the index 
    var overlayIndex = overlaysOnMap.indexOf(this); 

    // Set the overlay's div_ property to this DIV 
    this.div_ = div; 

    // We add an overlay to a map via one of the map's panes. 
    // We'll add this overlay to the overlayLayer pane. 
    var panes = this.getPanes(); 
    panes.overlayLayer.appendChild(div); 

    //add the listener 
    tempAddListener(overlayIndex); 

}; 
CustomOverlay.prototype.draw = function() { 
    // Size and position the overlay. We use a southwest and northeast 
    // position of the overlay to peg it to the correct position and size. 
    // We need to retrieve the projection from this overlay to do this. 
    var overlayProjection = this.getProjection(); 

    // Retrieve the southwest and northeast coordinates of this overlay 
    // in latlngs and convert them to pixels coordinates. 
    // We'll use these coordinates to resize the DIV. 
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); 
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); 

    // Resize the image's DIV to fit the indicated dimensions. 
    var div = this.div_; 
    div.style.left = sw.x + 'px'; 
    div.style.top = ne.y + 'px'; 
    div.style.width = (ne.x - sw.x) + 'px'; 
    div.style.height = (sw.y - ne.y) + 'px'; 

    //for a preserved rotation 
    if (preservedRotation != 0) { 
     //keepRotate(preservedRotation); 
    } 
}; 
//CustomOverlay.prototype.onRemove = function() { 
// this.div_.parentNode.removeChild(this.div_); 
// this.div_ = null; 
//}; 
function tempAddListener(get) { 
    alert("div: "+document.getElementById("overlay" + get).innerHTML); 
    alert("adding with index: " + get); 
    if (document.getElementById("overlay" + get) != null) { //check to see if div is there 
     google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function() { 

      alert("listener fired at overlay: " + get); 

      displayOverlayRectangle(incomingOverlayBounds[get]); 
      //alert(incomingOverlayBounds[get]); 


      //overlayRectangles[get] = displayOverlayRectangle(incomingOverlayBounds[get]); 
      //overlayRectangles[get].setMap(map); 

     }); 
    } else { 
     //could not find the div 
    } 

} 

function displayOverlayRectangle(bounds) { 
    //2do: set drawing manager, set mode, match listeners of rectangle 
    var tempOverlayRectangle = new google.maps.Rectangle(); 
    var tempOverlayRectangleOptions = { 
     strokeColor: "#FF0000", 
     strokeOpacity: 0.8, 
     strokeWeight: 2, 
     fillColor: "#FF0000", 
     fillOpacity: 0.1, 
     editable: true, 
     draggable: true, 
     //strokeOpacity: 0.2, 
     //strokeWeight: 1, 
     //fillOpacity: 0.0, 
     zindex: 5 
    }; 

    tempOverlayRectangle.setOptions(tempOverlayRectangleOptions); 
    tempOverlayRectangle.setBounds(bounds); 
    tempOverlayRectangle.setMap(map); 

    google.maps.event.addListener(tempOverlayRectangle, "click", function() { 
     alert("can't touch this"); 
    }); 

    //return tempOverlayRectangle; 

    //tempOverlayRectangle.setOptions(tempOverlayRectangleOptions); 
    //tempOverlayRectangle.setBounds(bounds); 
    //tempOverlayRectangle.setMap(map); 
} 



//start this whole mess once 
google.maps.event.addDomListener(window, 'load', initialize); 

</script> 

<div id="googleMap"></div> 

UPDATE는

이 리스너에 어떤 맵 코드가 다른 청취자를 무효화 것으로 보인다. ,

  google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function() { 

      if (map.getMapTypeId() == 'TERRAIN') { 
       map.setMapTypeId(google.maps.MapTypeId.ROADMAP); 
      } else { 
       map.setMapTypeId(google.maps.MapTypeId.TERRAIN); 
      } 

     }); 
+0

당신은 콘솔을 확인 했습니까? 아마 리스너의 첫 번째 호출 중에 예외가 발생 했습니까? (정확히 위 코드에서) – gawi

+0

내 Visual Studio에서 오류가 없습니다. 나 또한 방화범이 끌 렸으며 에러가 없다. 내가 curOverlayRectangle.setMap (map)을 제거하면 매번 실행되기 때문에 당황 스럽지만, 거기에있을 때만 실행됩니다. – yoyo

+0

그래서 매번 curOverlayRectangle을 만들지 않으십니까? 아마도 이것이 문제입니다 (직사각형은지도에 "등록"되어 있으며 객체를 수정하는 데 문제가있을 수 있음). 직사각형을 관리하려면 어딘가에 저장해야합니다 (예 : 특정 시점에 숨기려고하는 경우). 첫 번째 경고 이후에 시도하여 처음부터 개체를 만듭니다. curOverlayRectangle = new google.maps.Rectangle(); 을 입력 한 다음 나머지 방법을 진행하십시오. – gawi

답변

0

결론 해결 나는 DOM에 의해 적절하게 액세스 할 수 없습니다 생성 된 오버레이 (IE 나는 다음과 같은 코드로 시도하고 그것은 여전히 ​​한 번만 실행). 따라서 액세스 할 수있는 오버레이 상단에 오버레이 할 보이지 않는 사각형을 만들었습니다.

니펫 :

var incomingOverlayBounds = [];   //defined in c# to js on page 
var incomingOverlaySourceURL = [];  //defined in c# to js on page 
var incomingOverlayRotation = [];  //defined in c# to js on page 
var ghostOverlayRectangle = [];   //holds ghost overlay rectangles (IE overlay hotspots) 
var ghostOverlayRectangleOptions = { //define options for ghost rectangle 
    strokeColor: "#FF0000",    //color doesnt matter 
    strokeOpacity: 0.0,     //make border invisible 
    strokeWeight: 1,     //should not matter? 
    fillColor: "#FF0000",    //color doesnt matter 
    fillOpacity: 0.0,     //make fill transparent 
    editable: false,     //just to be sure? 
    draggable: false,     //just to be sure? 
    zindex: 6       //perhaps higher? 
}; 
var visibleOverlayRectangleOptions = { //define options for visible rectangle 
    strokeColor: "#FF0000",    //for testing (red) 
    strokeOpacity: 0.8,     //for testing 
    strokeWeight: 2,     //for testing 
    fillColor: "#FF0000",    //for testing (red) 
    fillOpacity: 0.1,     //for testing 
    editable: true,      //sobek standard 
    draggable: true,     //sobek standard 
    //strokeOpacity: 0.2,    //sobek standard 
    //strokeWeight: 1,     //sobek standard 
    //fillOpacity: 0.0,     //sobek standard 
    zindex: 5       //sobek standard 
}; 
var visibleOverlayRectangle = new google.maps.Rectangle(); //init maybe move to array later 

//Displays all the overlays sent from the C# code. Also calls displayGhostOverlayRectangle. 
function displayIncomingOverlays() { 
    //go through and display overlays as long as there is an overlay to display 
    for (var i = 0; i < incomingOverlayBounds.length; i++) { 
     overlaysOnMap[i] = new CustomOverlay(incomingOverlayBounds[i], incomingOverlaySourceURL[i], map, incomingOverlayRotation[i]); 
     overlaysOnMap[i].setMap(map);            //set the overlay to the map 
     displayGhostOverlayRectangle(incomingOverlayBounds[i],i);     //add all the ghost rectangles 
    } 
} 

//Displays an invisible rectangle on top of the overlay div (creates a hotspot). This rectangle is used as a psuedo listener if the 'overlay div' is clicked. This solved issue of creating listener for overlay div directly. 
//Supporting URL: http://stackoverflow.com/questions/17025240/google-maps-listener-only-running-once 
function displayGhostOverlayRectangle(ghostBounds,ghostIndex) { 
    ghostOverlayRectangle[ghostIndex] = new google.maps.Rectangle();    //init rect 
    ghostOverlayRectangle[ghostIndex].setOptions(ghostOverlayRectangleOptions);  //set options 
    ghostOverlayRectangle[ghostIndex].setBounds(ghostBounds);      //set bounds 
    ghostOverlayRectangle[ghostIndex].setMap(map);         //set to map 
    //create the listener for this ghost rectangle 
    google.maps.event.addListener(ghostOverlayRectangle[ghostIndex], 'click', function() { 
     displayVisibleOverlayRectangle(ghostBounds, ghostIndex);     //add the visible rectangles 
    }); 
} 

//Displays the visible rectangle which is used to edit an overlay. Called by the ghost listener.  
function displayVisibleOverlayRectangle(bounds, overlayIndex) { 
    visibleOverlayRectangle.setOptions(visibleOverlayRectangleOptions); 
    visibleOverlayRectangle.setBounds(bounds); 
    visibleOverlayRectangle.setMap(map); 
} 

//Starts the creation of a custom overlay div which contains a rectangular image. 
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays 
function CustomOverlay(bounds, image, map, rotation) { 
    overlayCount++;     //iterate how many overlays have been drawn 
    this.bounds_ = bounds;   //set the bounds 
    this.image_ = image;   //set source url 
    this.map_ = map;    //set to map 
    preservedRotation = rotation; //set the rotation 
    this.div_ = null;    //defines a property to hold the image's div. We'll actually create this div upon receipt of the onAdd() method so we'll leave it null for now. 
} 

//Continues support for adding an custom overlay 
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays 
// Note: an overlay's receipt of onAdd() indicates that the map's panes are now available for attaching the overlay to the map via the DOM. 
CustomOverlay.prototype.onAdd = function() { 

    // Create the DIV and set some basic attributes. 
    var div = document.createElement("div"); 
    div.id = "overlay" + overlaysOnMap.indexOf(this); 
    div.style.borderStyle = 'none'; 
    div.style.borderWidth = '0px'; 
    div.style.position = 'absolute'; 
    div.style.opacity = preserveOpacity; 

    // Create an IMG element and attach it to the DIV. 
    var img = document.createElement('img'); 
    img.src = incomingOverlaySourceURL[overlaysOnMap.indexOf(this)]; //this.image 
    img.style.width = '100%'; 
    img.style.height = '100%'; 
    img.style.position = 'absolute'; 
    div.appendChild(img); 

    // Set the overlay's div_ property to this DIV 
    this.div_ = div; 

    // We add an overlay to a map via one of the map's panes. 
    // We'll add this overlay to the overlayLayer pane. 
    var panes = this.getPanes(); 
    panes.overlayLayer.appendChild(div);  
}; 

//Continues support for adding an custom overlay 
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays 
CustomOverlay.prototype.draw = function() { 
    // Size and position the overlay. We use a southwest and northeast 
    // position of the overlay to peg it to the correct position and size. 
    // We need to retrieve the projection from this overlay to do this. 
    var overlayProjection = this.getProjection(); 

    // Retrieve the southwest and northeast coordinates of this overlay 
    // in latlngs and convert them to pixels coordinates. 
    // We'll use these coordinates to resize the DIV. 
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); 
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); 

    // Resize the image's DIV to fit the indicated dimensions. 
    var div = this.div_; 
    div.style.left = sw.x + 'px'; 
    div.style.top = ne.y + 'px'; 
    div.style.width = (ne.x - sw.x) + 'px'; 
    div.style.height = (sw.y - ne.y) + 'px'; 

    //for a preserved rotation 
    if (preservedRotation != 0) { 
     keepRotate(preservedRotation); 
    } 
}; 

//Not currently used 
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays 
CustomOverlay.prototype.onRemove = function() { 
    this.div_.parentNode.removeChild(this.div_); 
    this.div_ = null; 
}; 
관련 문제