标记谷歌地图的动态图标更改

时间:2016-01-14 21:39:26

标签: javascript google-maps

我研究了Google的地图类,并指出了我能够在我想要的位置设置标记的地方。我想在“鼠标事件”上动态更新图标

    var neighborhoods = [
    [54.50266744485844,  18.540940856933616],
    [54.49848076437959,  18.540254211425804],
    [54.49190082846816, 18.518968200683616],
    [54.4040671009359,  18.608918762207054],
    ];

    var markers = [];
    var map;

为了放置标记,我使用如下函数。

     function setMarkers(map) {

      var image = {
      url: '/images/icon1.png',
   anchor: new google.maps.Point(0, 32)
   };
    var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };


    for (var i = 0; i < neighborhoods.length; i++) 
       {
        var neighborhood = neighborhoods[i];
        var marker_temp = new google.maps.Marker
        ({
        position: {lat: neighborhood[0], lng: neighborhood[1]},
        map: map,
        icon: image,
        shape: shape,
        title: "",
        visible:true,
        zIndex: 3
        });
        marker_temp.addListener('mouseover', function() 
        { 
        marker_temp.setOptions({icon: "/images/icon1.png"});
        });

        marker_temp.addListener('mouseout',  function() 
        { 
        marker_temp.setOptions({icon: "/images/icon2.png"});    
        });

        marker_temp.addListener('click',  function() 
        { 
        marker_temp.setOptions({icon: "/images/icon1.png"});
        });


    markers.push(marker_temp);
}// end of for loop ----------------------------------------------------

     }// --- end of set markers function --------------------------------

放置标记工作正常,所有这些标记都按预期触发,但只有图标从icon1.png更改为icon2.png才能在最后一个标记上使用与其相关的事件。谁能告诉我我的想法出错在哪里?

2 个答案:

答案 0 :(得分:1)

Javascript没有块范围,但功能范围。例如:

function setMarkers(map) {
....
   for (var i = 0; i < neighborhoods.length; i++) 
   {
    ....
    var marker_temp = new google.maps.Marker
    ....
   }
}

变量marker_temp的范围限定为函数setMarkers,而不是其他编程语言中常见的for循环。

以上功能与此相同(该过程称为hoisting):

function setMarkers(map) {
    var marker_temp;
    ....
    for (var i = 0; i < neighborhoods.length; i++) 
    {
     ....
     marker_temp = new google.maps.Marker
     ....
   }
}

这意味着当你这样做时:

marker_temp.addListener('click',  function() 
{ 
    marker_temp.setOptions({icon: "/images/icon1.png"});
});

当您致电setOptions时,marker_temp变量将是循环中最后设置的值。

为避免此问题,您可以使用IIFE(中间调用的函数表达式),以便在该时间点捕获标记变量的值:

 marker_temp.addListener('click',  (function(theMarker) 
 { 
    return function(){
        theMarker.setOptions({icon: "/images/icon1.png"});
    }
 })(marker_temp));

有关范围和悬挂的更多信息,您可以阅读我撰写的关于此内容的博文:https://www.kenneth-truyers.net/2013/04/20/javascript-hoisting-explained/

答案 1 :(得分:0)

如果要设置多个事件侦听器,我发现编写createMarker函数以便在事件侦听器的标记上保持函数闭包更简单。然后从循环内部调用它。 createMarker函数的一个示例:

function createMarker(neighborhood, idx, bounds, map) {
  var image = {
    url: 'http://maps.google.com/mapfiles/ms/micons/blue.png',
    anchor: new google.maps.Point(16, 32)
  };
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };

  var marker_temp = new google.maps.Marker({
    position: {
      lat: neighborhood[0],
      lng: neighborhood[1]
    },
    map: map,
    icon: image,
    shape: shape,
    title: "" + idx,
    visible: true,
    // zIndex: 3
  });
  bounds.extend(marker_temp.getPosition());

  marker_temp.addListener('mouseover', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/yellow.png",
      anchor: new google.maps.Point(16, 32)
    });
  });

  marker_temp.addListener('mouseout', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/green.png",
      anchor: new google.maps.Point(16, 32)
    });
  });

  marker_temp.addListener('click', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/orange.png",
      anchor: new google.maps.Point(16, 32)
    });
  });
  markers.push(marker_temp);
}

proof of concept fiddle

代码段

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  setMarkers(map);
}
google.maps.event.addDomListener(window, "load", initialize);

function setMarkers(map) {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < neighborhoods.length; i++) {
      var neighborhood = neighborhoods[i];
      createMarker(neighborhood, i, bounds, map);
    } // end of for loop --------------------------------------
    map.fitBounds(bounds);
  } // --- end of set markers function ------------------------

function createMarker(neighborhood, idx, bounds, map) {
  var image = {
    url: 'http://maps.google.com/mapfiles/ms/micons/blue.png',
    anchor: new google.maps.Point(16, 32)
  };
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };

  var marker_temp = new google.maps.Marker({
    position: {
      lat: neighborhood[0],
      lng: neighborhood[1]
    },
    map: map,
    icon: image,
    shape: shape,
    title: "" + idx,
    visible: true,
    // zIndex: 3
  });
  bounds.extend(marker_temp.getPosition());

  marker_temp.addListener('mouseover', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/yellow.png",
      anchor: new google.maps.Point(16, 32)
    });
  });

  marker_temp.addListener('mouseout', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/green.png",
      anchor: new google.maps.Point(16, 32)
    });
  });

  marker_temp.addListener('click', function() {
    marker_temp.setOptions({
      icon: "http://maps.google.com/mapfiles/ms/micons/orange.png",
      anchor: new google.maps.Point(16, 32)
    });
  });
  markers.push(marker_temp);
}
var neighborhoods = [
  [54.50266744485844, 18.540940856933616],
  [54.49848076437959, 18.540254211425804],
  [54.49190082846816, 18.518968200683616],
  [54.4040671009359, 18.608918762207054],
];
var markers = [];
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>