Overview

This lesson teaches you to:

  • Customize map markers.
  • Customize marker icons for different markers.

Description

Custom icons display a different image in place of the default Google map marker pin. In this lesson, you’ll replace the default marker image with one that represents the map feature it’s placed on.

Try it out

Untitled 2

Customize a map marker

Specify the icon option on MarkerOptions to change the marker’s icon, and the shadow property to add the marker’s shadow. Both the icon and shadow options can be either a string (the URL to the marker icon), or an Icon object.

var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: iconBase + 'schools_maps.png',
  shadow: iconBase + 'schools_maps.shadow.png'
});

Untitleaad 2
Unfortunately, the shadow on this marker isn’t in the correct location. By creating and using an Icon object for the shadow, we can reposition it (in this case, by anchoring it to a new point 16px to the right, and 34px up from the marker’s location):

var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var schoolShadow = {
  url: iconBase + 'schools_maps.shadow.png',
  anchor: new google.maps.Point(16, 34)
};

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: iconBase + 'schools_maps.png',
  shadow: schoolShadow
});

Untitleaad 2

Customize marker icons for different markers

We can also change the marker icon, depending on the type of feature the marker’s being added to. Each point of interest in the list of campus features has a type attribute. We’ll use this to change the icon and shadow accordingly.

var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
  parking: {
    icon: iconBase + 'parking_lot_maps.png',
    shadow: iconBase + 'parking_lot_maps.shadow.png'
  },
  library: {
    icon: iconBase + 'library_maps.png',
    shadow: iconBase + 'library_maps.shadow.png'
  },
  info: {
    icon: iconBase + 'info-i_maps.png',
    shadow: iconBase + 'info-i_maps.shadow.png'
  }
};

function addMarker(feature) {
  var marker = new google.maps.Marker({
    position: feature.position,
    icon: icons[feature.type].icon,
    shadow: {
      url: icons[feature.type].shadow,
      anchor: new google.maps.Point(16, 34)
    },
    map: map
  });
}
Enhanced by Zemanta

Leave a Reply

Your email address will not be published. Required fields are marked *