adding sound to an array of markers - google map javascript

亡梦爱人 提交于 2019-12-04 16:22:46

Suppose you have an array of URLs:

var sounds = ["http://mm1.ellieirons.com/wp-content/uploads/2012/03/beeps_bubbles.mp3",
              "http://mm1.ellieirons.com/wp-content/uploads/2012/03/beeps_bubbles2.mp3"];

Then you could try something like this:

 for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
       position: myLatLng,
       map: map,
       icon: image,
       shape: shape,
       title: beach[0],
       zIndex: beach[3]
    });
    marker.sound = sounds[i];  //Storing associated sound in marker
    google.maps.event.addListener(marker, 'click', markerClick);
 }

And modify the handler to this:

function markerClick() {
   var playing = sm2.toggle(this.sound, true);
   if (playing) {
       this.setIcon(newimage);
   } else {
       this.setIcon(image);
   }
}

Something like this..

var beaches = [
 ['Devotion', 40.710431,-73.948432, 0, 'sound1.mp3'],
 ['Tester', 40.711223,-73.958416, 1, 'sound2.mp3'],
];

// ...

  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3],

    });
    google.maps.event.addListener(marker, 'click', function() {
       playSound(beach[4]);
    });
  }

Because you define an anonymous function inside your loop, it has access to the loop's variables (it is a "closure"). You add the name of your sound to the data associated with the beaches, then pass it from the closure to the function (I call it playSound) which actually causes it to play.

Hope this helps, it's not a complete recipe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!