Stack Overflow на русском Asked by 1div0 on October 3, 2020
Есть точки (метки), с которыми взаимодействует пользователь. Точек может быть больше ста, поэтому они загружаются на карту с помощью ObjectManager.
При нажатии на точку должно меняться содержимое точки (метки) – iconContent. Нужно просто пронумеровать нажатые.
Полный пример описывающий проблему с некоторым решением.
Вопрос: Как динамически изменить надпись внутри метки ObjectManager-а?
Есть готовые решения для объекта Placemark (например вот). Но точки ObjectManager-а – это не Placemark.
Обращение напрямую к свойству недостаточно, так как значение меняется, но на карте ничего не происходит.
placemark.properties.iconContent = "12";
Максимум, чего удалось добиться, это изменение содержимого, после щелчка мышью на метке и дополнительно ухода мыши с метки. Если просто щёлкнуть мышью и не двигать ей – ничего не произойдёт. Может потребоваться несколько меток нажать. То есть явно это нештатный способ. Тем не менее, достигается это двумя способами:
let placemarks = gObjectManager.objects.getAll();
manipulate(placemarks);
gObjectManager.objects.removeAll();
gObjectManager.objects.add(placemarks);
function placemarkUpdate(placemark) {
let objectId = placemark.id;
gObjectManager.objects.remove(objectId);
gObjectManager.objects.add(placemark);
}
Можно ещё пробовать менять опции, но это всё не работает как надо. Что я делаю не так?
Поясню полный пример.
// сначала всё стандартно
ymaps.ready(init);
function init() {
// инициализируем карту
gMap = new ymaps.Map('map', {
center: [55.753960, 37.620393],
zoom: 10,
controls: []
});
// инициализируем мегазагрузчик точек
gObjectManager = new ymaps.ObjectManager({});
gObjectManager.events.add('click', om_onclick); // указываем, что нам надо событие нажатия на объект
gMap.geoObjects.add(gObjectManager);
// добавляем точки в ObjectManager (внутри функции длинный JSON, хранящий 43 точки)
addPoints();
}
// обрабатываем событие нажатия
function om_onclick(e) {
// здесь всё обычно - получаем объект, на который пользователь нажал мышкой
let objectId = e.get('objectId');
let placemark = gObjectManager.objects.getById(objectId);
let n = gCurrentRoute.indexOf(objectId); // ищем в массиве нажатых
if (n >= 0) {
// если метка есть в массиве - удаляем из него
gCurrentRoute.splice(n, 1);
} else {
// если нет - добавляем в массив
gCurrentRoute.push(objectId);
}
// обновляем содержимое точек
update_labels();
}
// нерабочий вариант перенумерования всех точек
function update_labels() {
let placemarks = gObjectManager.objects.getAll();
placemarks.forEach(function(placemark) {
let objectId = placemark.id;
let n = gCurrentRoute.indexOf(objectId);
let oldIconContent = placemark.properties.iconContent;
if (n >= 0) {
placemark.properties.iconContent = "" + n;
} else {
placemark.properties.iconContent = "";
}
if (oldIconContent != placemark.properties.iconContent) {
placemarkUpdate(placemark);
}
});
}
// нерабочий вариант обновления конкретной точки
function placemarkUpdate(placemark) {
let objectId = placemark.id;
gObjectManager.objects.remove(objectId);
gObjectManager.objects.add(placemark);
}
Сначала меняем содержимое метки так, как указано в вопросе:
placemark.properties.iconContent = "12";
Затем главное - вот такой способ я нашёл для перезагрузки ObjectManager на карте (обновление карты):
gMap.geoObjects.remove(gObjectManager);
gMap.geoObjects.add(gObjectManager);
Но! При этом курсор над меткой меняется, что нехорошо. Без смены курсора никак не получается. Побеждается применением костыля:
// объявляем глобальную переменную
var gCursorCrutch = 0;
//...
// внутри события нажатия на метку
if (gCursorCrutch == 0) {
gCursorCrutch = gMap.cursors.push('pointer');
}
//...
gMap.events.add('mousemove', map_onMouseMove);
//...
function map_onMouseMove(e) {
if (gCursorCrutch != 0) {
gCursorCrutch.remove();
gCursorCrutch = 0;
}
}
Полный рабочий пример:
"use strict";
var gMap = 0;
var gObjectManager = 0;
var gCurrentId = 0;
var gCurrentRoute = [];
var gCursorCrutch = 0;
function myOnLoad() {
ymaps.ready(init);
}
function init() {
gMap = new ymaps.Map('map', {
center: [55.753960, 37.620393],
zoom: 10,
controls: []
});
gMap.events.add('mousemove', mapOnMouseMove);
gObjectManager = new ymaps.ObjectManager({});
gObjectManager.events.add('click', omOnClick);
gMap.geoObjects.add(gObjectManager);
addPoints();
}
function mapOnMouseMove(e) {
if (gCursorCrutch != 0) {
gCursorCrutch.remove();
gCursorCrutch = 0;
}
}
function omOnClick(e) {
let objectId = e.get('objectId');
let placemark = gObjectManager.objects.getById(objectId);
let n = gCurrentRoute.indexOf(objectId);
if (n >= 0) {
//route_del(placemark, n);
gCurrentRoute.splice(n, 1);
} else {
let coords = placemark.geometry.coordinates;
let latitude = coords[0];
let longitude = coords[1];
//route_add(placemark, latitude, longitude);
gCurrentRoute.push(objectId);
}
if (gCursorCrutch == 0) {
gCursorCrutch = gMap.cursors.push('pointer');
}
update_labels();
}
function update_labels() {
let placemarks = gObjectManager.objects.getAll();
placemarks.forEach(function(placemark) {
let objectId = placemark.id;
let n = gCurrentRoute.indexOf(objectId);
let oldIconContent = placemark.properties.iconContent;
if (n >= 0) {
placemark.properties.iconContent = "" + n;
} else {
placemark.properties.iconContent = "";
}
});
gMap.geoObjects.remove(gObjectManager);
gMap.geoObjects.add(gObjectManager);
}
function addPoints()
{
let json = `
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": "0",
"geometry": {
"type": "Point",
"coordinates": [
55.818948,
37.702706
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "1",
"geometry": {
"type": "Point",
"coordinates": [
55.615553,
37.448752
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "2",
"geometry": {
"type": "Point",
"coordinates": [
55.495323,
37.578487
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "3",
"geometry": {
"type": "Point",
"coordinates": [
55.9999633,
37.5260016
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "4",
"geometry": {
"type": "Point",
"coordinates": [
55.481092,
37.602714
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "5",
"geometry": {
"type": "Point",
"coordinates": [
55.445676,
37.626026
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "6",
"geometry": {
"type": "Point",
"coordinates": [
55.624398,
37.45875
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "7",
"geometry": {
"type": "Point",
"coordinates": [
55.615553,
37.448752
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "8",
"geometry": {
"type": "Point",
"coordinates": [
55.616819,
37.469458
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "9",
"geometry": {
"type": "Point",
"coordinates": [
55.733346,
37.697235
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "10",
"geometry": {
"type": "Point",
"coordinates": [
55.718486,
37.633284
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "11",
"geometry": {
"type": "Point",
"coordinates": [
55.655765,
37.6310452
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "12",
"geometry": {
"type": "Point",
"coordinates": [
55.67228,
37.614294
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "13",
"geometry": {
"type": "Point",
"coordinates": [
55.584492,
37.611994
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "14",
"geometry": {
"type": "Point",
"coordinates": [
55.848402,
37.379914
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "15",
"geometry": {
"type": "Point",
"coordinates": [
55.835114,
37.402543
]
},
"properties": {},
"options": {
"preset": "islands#blackCircleIcon"
}
},
{
"type": "Feature",
"id": "16",
"geometry": {
"type": "Point",
"coordinates": [
55.896731,
37.519243
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "17",
"geometry": {
"type": "Point",
"coordinates": [
55.684554,
37.886303
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "18",
"geometry": {
"type": "Point",
"coordinates": [
55.9999633,
37.5260016
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "19",
"geometry": {
"type": "Point",
"coordinates": [
55.923629,
38.040652
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "20",
"geometry": {
"type": "Point",
"coordinates": [
56.020994,
37.458184
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "21",
"geometry": {
"type": "Point",
"coordinates": [
55.375352,
37.785962
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "22",
"geometry": {
"type": "Point",
"coordinates": [
55.551242,
37.685386
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "23",
"geometry": {
"type": "Point",
"coordinates": [
55.815848,
37.362729
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "24",
"geometry": {
"type": "Point",
"coordinates": [
55.815848,
37.362729
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "25",
"geometry": {
"type": "Point",
"coordinates": [
55.856093,
37.384019
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "26",
"geometry": {
"type": "Point",
"coordinates": [
55.6840806828,
37.4127423987
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "27",
"geometry": {
"type": "Point",
"coordinates": [
55.845486,
37.436409
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "28",
"geometry": {
"type": "Point",
"coordinates": [
55.841261,
37.494422
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
}
]
}
`;
let data = JSON.parse(json);
gObjectManager.removeAll();
gObjectManager.add(data);
gMap.setBounds(gMap.geoObjects.getBounds(),{checkZoomRange:true, zoomMargin:9});
}
html, body, #map {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&load=Map,Placemark,ObjectManager&onload=myOnLoad" type="text/javascript"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
Correct answer by 1div0 on October 3, 2020
Вот таким методом получается динамически изменить содержимое метки:
gObjectManager.objects.events.add('click', function (e) {
let objectId = e.get('objectId');
let object = gObjectManager.objects.getById(objectId);
gObjectManager.objects.setObjectOptions(objectId, {
preset: 'islands#redIcon'
});
object.properties.iconContent = "12";
});
"use strict";
var gMap = 0;
var gObjectManager = 0;
var gCurrentId = 0;
var gCurrentRoute = [];
function myOnLoad() {
ymaps.ready(init);
}
function init() {
gMap = new ymaps.Map('map', {
center: [55.753960, 37.620393],
zoom: 10,
controls: []
});
gObjectManager = new ymaps.ObjectManager({});
gObjectManager.objects.events.add('click', function (e) {
let objectId = e.get('objectId');
let object = gObjectManager.objects.getById(objectId);
gObjectManager.objects.setObjectOptions(objectId, {
preset: 'islands#redIcon'
});
object.properties.iconContent = "12";
});
gMap.geoObjects.add(gObjectManager);
addPoints();
}
function addPoints()
{
let json = `
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": "0",
"geometry": {
"type": "Point",
"coordinates": [
55.818948,
37.702706
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "1",
"geometry": {
"type": "Point",
"coordinates": [
55.615553,
37.448752
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "2",
"geometry": {
"type": "Point",
"coordinates": [
55.495323,
37.578487
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "3",
"geometry": {
"type": "Point",
"coordinates": [
55.9999633,
37.5260016
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "4",
"geometry": {
"type": "Point",
"coordinates": [
55.481092,
37.602714
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "5",
"geometry": {
"type": "Point",
"coordinates": [
55.445676,
37.626026
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "6",
"geometry": {
"type": "Point",
"coordinates": [
55.624398,
37.45875
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "7",
"geometry": {
"type": "Point",
"coordinates": [
55.615553,
37.448752
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "8",
"geometry": {
"type": "Point",
"coordinates": [
55.616819,
37.469458
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "9",
"geometry": {
"type": "Point",
"coordinates": [
55.733346,
37.697235
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "10",
"geometry": {
"type": "Point",
"coordinates": [
55.718486,
37.633284
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "11",
"geometry": {
"type": "Point",
"coordinates": [
55.655765,
37.6310452
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "12",
"geometry": {
"type": "Point",
"coordinates": [
55.67228,
37.614294
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "13",
"geometry": {
"type": "Point",
"coordinates": [
55.584492,
37.611994
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "14",
"geometry": {
"type": "Point",
"coordinates": [
55.848402,
37.379914
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "15",
"geometry": {
"type": "Point",
"coordinates": [
55.835114,
37.402543
]
},
"properties": {},
"options": {
"preset": "islands#blackCircleIcon"
}
},
{
"type": "Feature",
"id": "16",
"geometry": {
"type": "Point",
"coordinates": [
55.896731,
37.519243
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "17",
"geometry": {
"type": "Point",
"coordinates": [
55.684554,
37.886303
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "18",
"geometry": {
"type": "Point",
"coordinates": [
55.9999633,
37.5260016
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "19",
"geometry": {
"type": "Point",
"coordinates": [
55.923629,
38.040652
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "20",
"geometry": {
"type": "Point",
"coordinates": [
56.020994,
37.458184
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "21",
"geometry": {
"type": "Point",
"coordinates": [
55.375352,
37.785962
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "22",
"geometry": {
"type": "Point",
"coordinates": [
55.551242,
37.685386
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "23",
"geometry": {
"type": "Point",
"coordinates": [
55.815848,
37.362729
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "24",
"geometry": {
"type": "Point",
"coordinates": [
55.815848,
37.362729
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "25",
"geometry": {
"type": "Point",
"coordinates": [
55.856093,
37.384019
]
},
"properties": {},
"options": {
"preset": "islands#darkGreenCircleIcon"
}
},
{
"type": "Feature",
"id": "26",
"geometry": {
"type": "Point",
"coordinates": [
55.6840806828,
37.4127423987
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "27",
"geometry": {
"type": "Point",
"coordinates": [
55.845486,
37.436409
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
},
{
"type": "Feature",
"id": "28",
"geometry": {
"type": "Point",
"coordinates": [
55.841261,
37.494422
]
},
"properties": {},
"options": {
"preset": "islands#blueCircleIcon"
}
}
]
}
`;
let data = JSON.parse(json);
gObjectManager.removeAll();
gObjectManager.add(data);
gMap.setBounds(gMap.geoObjects.getBounds(),{checkZoomRange:true, zoomMargin:9});
}
html, body, #map {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&load=Map,Placemark,ObjectManager&onload=myOnLoad" type="text/javascript"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
Answered by shchedrin on October 3, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP