-1

我是新來的JavaScript,希望你會原諒我我不好,如果我做錯了什麼。谷歌地圖API - 彈跳標記問題2

事實上,我已經找到了我的問題的解決方案,但我沒有得到如何把它放入我自己的代碼中。

Google Maps API - bouncing marker issue

不幸的是我不能只是發表評論,因爲我是在計算器新。

我的問題:

我的工作與地圖上的就可以了幾個標記。如果我點擊一個標記,我希望它彈跳並通過我設置的另一個圖標切換它的顏色。一切都很好,直到這一點,但目前我點擊的所有標記不會停止反彈。我想要標記彈起,直到我點擊另一個標記。此時,「舊」標記應該停止反彈,只是新的標記開始。

// track marker that is currently bouncing 
var currentMarker = null; 

function bindInfoWindow(marker, map, infoWindow, html) { 
    google.maps.event.addListener(marker, 'click', function() { 
     document.getElementById('loc-info').innerHTML = html; 
     // remove the bounce from the "old" marker 
     if (currentMarker) currentMarker.setAnimation(null); 
     // set this marker to the currentMarker 
     currentMarker = marker; 
     // add a bounce to this marker 
     marker.setAnimation(google.maps.Animation.BOUNCE); 

    }); 
} 

我不知道如何在我的OWM代碼來實現這一點:

//Marker Icons 
var unvisitedMarker = 'img/m1.svg'; 
var activeMarker = 'img/m2.svg'; 
var visitedMarker = 'img/m3.svg'; 



//Add Marker Function 
function addMarker(props) { 
    marker = new google.maps.Marker({ 
     position: props.coords, 
     map: map, 
     icon: unvisitedMarker 
    }); 

    //Opens marker information 
    var marker.addListener('click', function() { 
     document.getElementById("paperContainer").style.top = '40vh'; 
     document.getElementById("locationBar").style.top = 'calc(40vh - 2em)'; 
     map.panTo(marker.getPosition()); 
     //Panby the map-position 
     map.panBy(0, 350); 
     //Set active Marker Icon 
     marker.setIcon(activeMarker); 
     //Set Marker Animation 
     marker.setAnimation(google.maps.Animation.BOUNCE); 
    }); 
} 

所以我從另一個線程我從用戶「doublesharp」鏈接得到這個代碼。還有 - 我怎麼才能意識到在它停止彈跳到「visitedMarker」之後切換圖標?

非常感謝您提前!

回答

0

該解決方案的想法是保持對單擊標記的引用,並在單擊新標記時修改該標記。

這就是我的意思是:

var currentMarker = null; // Define this variable preferably in the global context. 
.... 
marker.addListener('click', function() { 
    if(currentMarker){ // Check if there is already an active marker 
     currentMarker.setAnimation(null); 
     currentMarker.setIcon(visitedMarker); 
    } 
    currentMarker = marker;// Keep a reference to this marker because it will became active. 
    document.getElementById("paperContainer").style.top = '40vh'; 
    document.getElementById("locationBar").style.top = 'calc(40vh - 2em)'; 
    map.panTo(marker.getPosition()); 
    //Panby the map-position 
    map.panBy(0, 350); 
    //Set active Marker Icon 
    marker.setIcon(activeMarker); 
    //Set Marker Animation 
    marker.setAnimation(google.maps.Animation.BOUNCE); 
}); 
+0

它的工作像彈跳魅力,現在,它是如何工作的我明白了!但該圖標不會切換到「已訪問」的圖標。該圖像是在正確的目錄中,但你的代碼似乎也沒關係。你有什麼想法可以解決問題嗎? – Flo

+0

看起來是因爲代碼中的定位。即使標記圖標get被設置爲「visitedMarker」,線marker.setIcon(activeMarker)也會出現並重新覆蓋訪問。我對嗎? – Flo

+0

@Flo我的例子中犯了一個錯誤。現在已經修復了。我使用'marker.setIcon(visitedMarker)'而不是'currentMarker.setIcon(visitedMarker)'。 – Titus