Skip to content Skip to sidebar Skip to footer

Add Custom Icon By Category On Google Map Marker

In the following code there are two categories and I want to show custom icon instead of marker by category. Mean for the two categories I want to show two custom icon for each cat

Solution 1:

Create an array of icons for your categories:

var icons = ["",
"http://maps.google.com/mapfiles/ms/micons/blue.png",
"http://maps.google.com/mapfiles/ms/micons/green.png"];

use that to populate the icon property of the marker:

for (i = 0; i < beaches.length; i++) {
  newMarker = new google.maps.Marker({
  position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
  map: map,
  icon: icons[beaches[i][3]],
  title: beaches[i][0]
});

proof of concept fiddle

code snippet:

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 1], //category 1
  ['Coogee Beach', -33.923036, 151.259052, 1], //category 1
  ['Cronulla Beach', -34.028249, 151.157507, 2], //category 2
  ['Manly Beach', -33.800101, 151.287478, 2], //category 2 
  ['Maroubra Beach', -33.950198, 151.259302, 2] //category 2
];

var icons = ["",
  "http://maps.google.com/mapfiles/ms/micons/blue.png",
  "http://maps.google.com/mapfiles/ms/micons/green.png"
];

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

var markers = [];

var i, newMarker;

for (i = 0; i < beaches.length; i++) {
  newMarker = new google.maps.Marker({
    position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
    map: map,
    icon: icons[beaches[i][3]],
    title: beaches[i][0]
  });

  newMarker.category = beaches[i][3];
  newMarker.setVisible(false);

  markers.push(newMarker);
}

functiondisplayMarkers(obj, category) {
  var i;

  for (i = 0; i < markers.length; i++) {
    if (markers[i].category === category) {
      if ($(obj).is(":checked")) {

        markers[i].setVisible(true);
      } else {
        markers[i].setVisible(false);
      }
    }

  }


}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#map {
  height: 90%;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script><divid="map"></div><label>blue</label><inputtype="checkbox"value="Show Group 1"onclick="displayMarkers(this,1);"><label>green</label><inputtype="checkbox"value="Show Group 2"onclick="displayMarkers(this, 2);">

Post a Comment for "Add Custom Icon By Category On Google Map Marker"