Answer the question
In order to leave comments, you need to log in
How to change the coordinates of the Yandex map mark when clicking on links on the page?
Tell me how to solve this problem: there are several blocks on the page with the js-address class and the "Show on map" link inside them. When you click on this link, a corresponding label with the desired coordinates should appear on the map. I set the coordinates in the markup using the data attributes of the js-address link's parent block.
After loading the document, when clicking on any of the links, the map is built according to the required coordinates (indicated by the parent of the clicked link), but then clicking on another link does nothing: the label remains the same.
I started from this example in the documentation https://tech.yandex.ru/maps/jsbox/2.1/request_map, but something didn't work.
Script code:
var mapContainer = $('#map');
if(mapContainer.length) {
ymaps.ready(init);
}
function init() {
var map;
$('.contacts__address--link').each(function() {
var self = $(this);
self.bind({
click: function (e) {
e.preventDefault();
var longitude = self.parents('.js-address').attr('data-longitude');
var latitude = self.parents('.js-address').attr('data-latitude');
map = new ymaps.Map('map', {
// Координаты центра карты. «широта, долгота».
center: [longitude, latitude],
// Уровень масштабирования. Допустимые значения: от 0 (весь мир) до 19.
zoom: 17
});
// Создание метки
var myGeoObject = new ymaps.GeoObject({
// Описание геометрии.
geometry: {
type: "Point",
coordinates: [longitude, latitude]
}
});
map.geoObjects.add(myGeoObject);
map.behaviors.disable('scrollZoom');
// Получаем центр карты в пикселях
var pixelCenter = map.getGlobalPixelCenter(longitude, latitude);
// Устанавливаем сдвиг центра по оси Х
pixelCenter = [
pixelCenter[0] - 300,
pixelCenter[1]
];
// Устанавливаем новые координаты
var geoCenter = map.options.get('projection').fromGlobalPixels(pixelCenter, map.getZoom());
map.setCenter(geoCenter);
}
});
});
};
Answer the question
In order to leave comments, you need to log in
let
map = null,
marker = null;
document.addEventListener('click', function(e) {
if (!e.target.classList.contains('contacts__address--link')) {
return;
}
e.preventDefault();
const
addressData = e.target.closest('.js-address').dataset,
coord = [ addressData.longtitude, addressData.latitude ];
if (!map) {
map = new ymaps.Map('map', {
center: coord,
zoom: 17,
});
marker = new ymaps.Placemark(coord);
map.geoObjects.add(marker);
map.behaviors.disable('scrollZoom');
} else {
map.setCenter(coord);
marker.geometry.setCoordinates(coord);
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question