如何为不同类别的标记显示不同的图标?

时间:2012-05-03 13:06:58

标签: google-maps-api-3 google-maps-markers

我正在尝试创建一个Google地图,允许用户检查某个类别并显示这些特定位置。我有那部分工作:

http://thedenvillehub.com/test-hs/adv/scripts/test.html

我想要做的是为每个类别设置一个不同的图标,这样一个是红色的,一个是蓝色的等等。我在网上找到了几个例子,但似乎没有什么对我有用。这是我的参考代码:

var markers = new Array();
var locations = [
    ['Boonton Town', '402-9410', 'Dial-a-Ride', 40.902, -74.407, 1 ],
    ['Boonton Township', '331-3336', 'Dial-a-Ride', 40.933, -74.425, 2 ],
    ['Butler Borough', '835-8885', 'Dial-a-Ride', 40.999497, -74.346326, 3 ]
    //other locations and categories
];

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(40.7967667, -74.4815438),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();
var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][3], locations[i][4]),
      map: map,
      icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
  });

  markers.push(marker);
  google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
          infowindow.setContent(locations[i][0] +
              "<br />"+locations[i][2]+"<br />"+locations[i][1]);
          infowindow.open(map, marker);
      }
  })(marker, i));
}

// shows all markers of a particular category,
// and ensures the checkbox is checked

function show(category) {
    for (var i=0; i<locations.length; i++) {
        if (locations[i][2] == category) {
            markers[i].setVisible(true);
        }
    }
}

// hides all markers of a particular category,
// and ensures the checkbox is cleared

function hide(category) {
    for (var i=0; i<locations.length; i++) {
        if (locations[i][2] == category) {
            markers[i].setVisible(false);
        }
    }
}

// == show or hide the categories initially ==

hide("Dial-a-Ride");
hide("American Legion");
hide("Veterans of Foreign Wars");
hide("Nutrition");

$(".checkbox").click(function(){
    var cat = $(this).attr("value");

    // If checked
    if ($(this).is(":checked")) {
        show(cat);
    }
    else {
        hide(cat);
    }
});

1 个答案:

答案 0 :(得分:6)

制作一个对象var iconSrc = {}

然后,将类别与图标图像匹配。

iconSrc['Dial-a-ride'] = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconSrc['American Legion'] = 'http://labs.google.com/ridefinder/images/mm_20_green.png';
...

添加标记时,将图标图像源替换为新变量:

icon: iconSrc[locations[i][2]]

这是一个jsfiddle,小窗格中的导航很难,所以我将复选框移到了顶部。 http://jsfiddle.net/DA92S/1/