Objects on the map

Geographical objects in the real world are matched to program objects known as geo objects. Geo objects include placemarks, circles, polylines, rectangles, polygons, and their collections.

Each geo object is described in a geometry, which is defined by a geometric type and coordinates.

The base class implementing a geo object is GeoObject.

The map instance stores geo objects in its own storage, implemented as a collection, which is referenced from the geoObjects field. Adding a geo object to the map, modifying it and removing it are all done by accessing this collection.

var myMap = new ymaps.Map("map", {
        center: [55.76, 37.64],
        zoom: 10
    }),
    myGeoObject = new ymaps.GeoObject({
      geometry: {
        type: "Point", // geometry type - point
        coordinates: [55.8, 37.8] // координаты точки
      }
    });
myMap.geoObjects.add(myGeoObject); // Placing a geo object on the map.

For each geometry type, an auxiliary class is defined that provides abbreviated syntax for creating a geo object.

// Auxiliary class that can be used
// instead of GeoObject with the «Point» geometry type (see the previous example)
var myPlacemark = new ymaps.Placemark([55.8, 37.6]);
myMap.geoObjects.add(myPlacemark);

Geo object geometry

The following table provides a list of geometries, their IDs that are used in the GeoObject class, and the corresponding auxiliary classes.

Geometry type / ID / Auxiliary class

Example

Point / Point / Placemark

Creating a placemark using the GeoObject class:

var myPlacemark = new ymaps.GeoObject({
      geometry: {
        type: "Point",
        coordinates: [55.76, 37.56]
      }
    });

Creating a placemark using the auxiliary class Placemark:

var myPlacemark = new ymaps.Placemark([55.8, 37.6]);

Polyline / LineString / Polyline

Creating a polyline using the GeoObject class:

var myPolyline = new ymaps.GeoObject({
      geometry: {
        type: "LineString",
        coordinates: [[...]]
      }
    });

Creating a polyline using the Polyline auxiliary class:

var myPolyline = new ymaps.Polyline(
      [[55.80, 37.30],[55.80, 37.40],[55.70, 37.30],[55.70, 37.40]]
    );

Rectangle / Rectangle / Rectangle

Creating a rectangle using the GeoObject class:

var myRectangle = new ymaps.GeoObject({
      geometry: {
        type: "Rectangle",
        coordinates: [[...]]
      }
    });

Creating a rectangle using the Rectangle auxiliary class:

var myRectangle = new ymaps.Rectangle(
      [[55.70, 37.30],[55.80, 37.40]]
    );

Polygon / Polygon / Polygon

Creating a polygon using the GeoObject class:

var myPolygon = new ymaps.GeoObject({
      geometry: {
        type: "Polygon",
        coordinates: [
          [[...]],
          [[...]]
        ]
      }
    });

Creating a polygon using the Polygon auxiliary class:

var myPolygon = new ymaps.Polygon([
      [[55.75, 37.50],[55.75, 37.71],[55.70, 37.70]],
        [[55.73, 37.58],[55.72, 37.70],[55.70, 37.70]]
    ]);

Circle / Circle / Circle

Creating a circle using the GeoObject class:

var myCircle = new ymaps.GeoObject({
      geometry: {
        type: "Circle",
        coordinates: [55.76, 37.64],
        radius: 10000
      }
    });

Creating a circle using the Circle auxiliary class:

var myCircle = new ymaps.Circle([[55.76, 37.64], 10000]);

The geometry type is assigned to a geo object when it is created, and cannot be changed later. However, the geometry's coordinates can be changed either programmatically, or using the visual editor.

var myPlacemark = new ymaps.Placemark([55.754952, 37.615319], {}, {
        draggable: true, // The placemark is draggable.
        preset: 'islands#whiteStretchyIcon'
    });
myPlacemark.events.add('dragend', function(e) {
   // Getting a reference to an object that was dragged.
   var thisPlacemark = e.get('target');
   // Determining the placemark coordinates
   var coords = thisPlacemark.geometry.getCoordinates();
   // and outputting them when the placemark is clicked
   thisPlacemark.properties.set('balloonContent', coords);
});

If a geo object was initialized without specifying a geometry, it will not be displayed on the map. It will also be impossible to assign a geometry type to such a geo object.

Visual editing

A geo object's geographical properties can be modified by the user in visible mode. The API provides two ways to do this: moving a geo object in its entirety, and the visual editor.

The ability to drag a geo object is controlled by the draggable option, which can take the values true and false.

The visual editor is available for geo objects with the point, polyline, or polygon geometry type. The reference to the editor is in the editor field of the instance of the corresponding class.


var myPolyline = new ymaps.Polyline(
  [[55.86, 37.84], [55.70, 37.55], [55.8, 37.4]],
  {},
  {
    strokeWidth: 6,
    strokeColor: '#0000FF',
    draggable: true
  }
);

myPolyline.editor.startEditing();

Setting the placemark style

You can select the style for placemark icons from a set of preset styles. The style sets the color of the placemark icon, as well as its type (such as an icon without content, or an icon that stretches to fit the content).

Each style from the set is assigned a unique key. To set a desired style, specify the corresponding key as the value of the preset option:

var myPlacemark = new ymaps.Placemark([55.8, 37.6], {}, {
        preset: 'islands#redIcon'
    });

Note

The default style is 'islands#blueIcon'.

Setting a custom placemark image

You can use your own image for a placemark icon. To do this, set the following options:

  • iconLayout — The 'default#image' or 'default#imageWithContent' value, for placemarks without text and with text on top of the picture, respectively.
  • iconImageHref — URL of the icon's image file.
  • iconImageSize — Icon size, in pixels.
  • iconImageOffset — Number of pixels to offset the icon from its anchor point (set if the icon is not anchored at the upper-left corner of the image).
  • iconContentOffset — For placemarks with text, the offset of the text relative to the placemark's anchor point.

var myPlacemark = new ymaps.Placemark([55.76, 37.56], {}, {
        iconLayout: 'default#image',
        iconImageHref: '/maps/doc/jsapi/2.1/examples/_images/myIcon.gif',
        iconImageSize: [30, 42],
        iconImageOffset: [-3, -42]
    });

Using CSS sprites

When adding a large number of placemarks to the map with different custom icons, it makes sense to use CSS sprites technology. The idea behind the technology is that all the images are combined in a single graphics file, the sprite. Using CSS, the appropriate image is extracted from the sprite and set as the icon for a specific placemark.

An example of a sprite containing three images is shown below:

In order to set the desired image as the placemark icon, this placemark must have the following options set:

  • iconLayout — Icon layout. This option must have the 'default#image' value set.
  • iconImageCliptRect — Position of the desired image in the sprite. It is defined by the pixel coordinates of the upper-left and lower-right corners of the rectangle the image is placed in.
  • iconImageHref — URL of the sprite.
  • iconImageSize — Icon size, in pixels.
  • iconImageOffset — Number of pixels to offset the icon from its anchor point (set if the icon is not anchored at the upper-left corner of the image).


var myPlacemark1 = new ymaps.Placemark([55.85, 60.64], {}, {
        iconLayout: 'default#image',
        iconImageClipRect: [[0,0], [26, 46]],
        iconImageHref: 'images/sprite.png',
        iconImageSize: [15, 27],
        iconImageOffset: [-15, -27]
    });

var myPlacemark2 = new ymaps.Placemark([55.85, 32.64], {}, {
        iconLayout: 'default#image',
        iconImageClipRect: [[34,0], [62, 46]],
        iconImageHref: 'images/sprite.png',
        iconImageSize: [26, 46],
        iconImageOffset: [-26, -46]
    });

var myPlacemark3 = new ymaps.Placemark([55.85, 1.0], {}, {
        iconLayout: 'default#image',
        iconImageClipRect: [[69,0], [97, 46]],
        iconImageHref: 'images/sprite.png',
        iconImageSize: [35, 63],
        iconImageOffset: [-35, -63]
    });

Using sprite technology reduces the number of HTTP requests to the server, since only a single image is loaded in place of a large number of images.

For more information about setting styles for placemark icons, see the example.

Placemarks with glyphs

The API lets you add placemarks to the map that contain glyphs (Glyphicons).

Alert

To use Glyphicons, you need to enable the Bootstrap CSS styles:

 <link rel="stylesheet" type="text/css" href="https://yastatic.net/bootstrap/3.3.4/css/bootstrap.min.css">

To create a placemark with a glyph, set the following options in the placemark designer:

  • preset — The type of placemark. Specified with the 'glyph' prefix. For example, 'islands#glyphCircleIcon' (a circle placemark) or 'islands#glyphIcon' (a placemark with a tail). You can also use this option to set the placemark color. For example, 'islands#redGlyphIcon'.
  • iconGlyph — The name of the glyph. For a list of available glyphs and their names, see the Glyphicons page. Note that the name is set without the 'glyph' prefix. For example, 'asterisk' or 'plus'.
  • iconGlyphColor (optional) — The color of the glyph. There are three ways to set the color: using a keyword, in Hex format, or RGB. If this option is omitted, a black glyph is used by default.
  • iconColor (optional) — The color of the placemark. There are three ways to set the color: using a keyword, in Hex format, or RGB. A blue placemark is used by default.

An example of using glyphs is shown below.


var glyphIcon1 = new ymaps.Placemark([55.684, 37.738], {}, {
      preset: 'islands#redGlyphIcon',            
      iconGlyph: 'music',
      iconGlyphColor: 'red',
    }),

    glyphIcon2 = new ymaps.Placemark([55.684, 37.7383], {}, {
      preset: 'islands#glyphIcon', 
      iconGlyph: 'home',
      iconGlyphColor: 'blue'
    }), 

    glyphIcon3 = new ymaps.Placemark([55.684, 37.7383], {}, {
      preset: 'islands#yellowGlyphCircleIcon',
      iconGlyph: 'glass',
    });

myMap.geoObjects
  .add(glyphIcon1)
  .add(glyphIcon2)
  .add(glyphIcon3);

Geo object collections

Geo objects can be combined in collections, which lets you define properties for all of their members at once and perform group operations with them.

A geo object can only belong to one collection. If you add a geo object to a collection when it already belongs to a different collection, it will be deleted from the first collection.


var coords = [
    [55.75, 37.50], [55.75, 37.71], [55.70, 37.70]
],
    myCollection = new ymaps.GeoObjectCollection({}, {
       preset: 'islands#redIcon', //all placemarks are red
       draggable: true // and draggable
    });

for (var i = 0; i < coords.length; i++) {
    myCollection.add(new ymaps.Placemark(coords[i]));
}

myMap.geoObjects.add(myCollection);

// All placemarks will be deleted when the map is clicked.
myCollection.getMap().events.add('click', function() {
    myCollection.removeAll();
});

You can implement your own class of collections that can be placed on the map; to do this, implement the IMapObjectCollection interface.

Clusters

Point geo objects can be located so close to each other that at some zoom level their placemarks will start to overlap each other. In this case, the user must «aim» carefully in order to get the mouse cursor on a visible part of the desired placemark. There is even a special term used to describe this effect: pixel hunting.


var coords = [
    [56.023, 36.988],
    [56.025, 36.981],
    [56.020, 36.981],
    [56.021, 36.983],
    [56.027, 36.987]
];

var myCollection = new ymaps.GeoObjectCollection();

for (var i = 0; i<coords.length; i++) {
    myCollection.add(new ymaps.Placemark(coords[i]));
}

myMap.geoObjects.add(myCollection);

If multiple placemarks are located at the same point and the size of their icons is the same, it is actually impossible to point at a placemark that is covered up by another one.

The standard way to solve this problem is by combining neighboring objects in a group (cluster) and using a special cluster icon for the group. The cluster icon often shows the number of items that are in it.

The Clusterer class is used for clustering objects in the Yandex Maps API.


var myGeoObjects = [];

for (var i = 0; i<coords.length; i++) {
  myGeoObjects[i] = new ymaps.GeoObject({
    geometry: {
      type: "Point",
      coordinates: coords[i]
    }
  });
}

var myClusterer = new ymaps.Clusterer();
myClusterer.add(myGeoObjects);
myMap.geoObjects.add(myClusterer);

When the zoom is increased, the cluster visually separates into individual placemarks and/or other clusters.

When the cluster icon is clicked, either the zoom increases or a balloon opens that displays the list of geo objects in the cluster. This behavior is controlled using the clusterDisableClickZoom option (true/false).

var myGeoObjects = [];

for (var i = 0; i < coords.length; i++) {
  myGeoObjects[i] = new ymaps.GeoObject({
    geometry: {
      type: "Point",
      coordinates: coords[i]
    },
    properties: {
      clusterCaption: 'Geo object # '+(i+1),
      balloonContentBody: 'Balloon text # '+(i+1)
    }
  });
}

var myClusterer = new ymaps.Clusterer(
  {clusterDisableClickZoom: true}
);
myClusterer.add(myGeoObjects);
myMap.geoObjects.add(myClusterer);

Note

If the cluster is displayed at the maximum zoom level, the cluster will not separate into separate placemarks when its marker is clicked. The balloon opens in this case, regardless of the value of the clusterDisableClickZoom parameter.

In this way, information can be displayed for geo objects that are positioned close together, even if their placemarks overlap at the maximum zoom level.

Using the clusterer significantly increases performance when displaying a large number of geo objects in the browser.

Rendering and handling a geo object is an expensive operation in terms of resource consumption, and the more objects are clusterized, the more resources are saved. Performance decreases significantly even when displaying a few hundred objects without clustering.