Public
Edited
Dec 7, 2022
Insert cell
Insert cell
Insert cell
Insert cell
// настрока API (спецмальный объект, который будет обеспечивать взаимодействие с yandex-сервисом):
ymaps = require('https://api-maps.yandex.ru/2.1/?apikey=7a8a7026-ae95-427c-82c4-cb2208bfc100&lang=ru_RU')
.catch(() => window.ymaps)
Insert cell
map_yandex = []
Insert cell
Insert cell
{let wind = html`<div style='height:500px;'></div>`;//контейнер
yield wind;
let map1 = new ymaps.Map(wind, {
center: [53.36, 83.75], //Барнаул
zoom: 13});
// Проинициализируем координаты с центром карты
var userCoords = map1.getCenter();
var newPlacemark;
// При щелчке на карте показывается балун со значениями координат
map1.events.add('click', function (e) {
var coords = e.get('coords');
// map1.balloon.open(coords, `Выбрано:${coords}</sup>`);
if (newPlacemark) {
newPlacemark.geometry.setCoordinates(coords);
}
else
{
newPlacemark = new ymaps.Placemark(coords);
}
printAddress(newPlacemark, coords);
map1.geoObjects.add(newPlacemark);
});
}
Insert cell
Insert cell
function printAddress(newPlacemark, coords) {
newPlacemark.properties.set('iconCaption', 'поиск...');
ymaps.geocode(coords).then(function (res) {
// ищем информацию только по первому найденному объекту
var firstGeoObject = res.geoObjects.get(0);
newPlacemark.properties
.set({
// Формируем строку с данными об объекте.
iconCaption: [
// Название населенного пункта или вышестоящее административно-территориальное образование.
firstGeoObject.getLocalities().length ? firstGeoObject.getLocalities() : firstGeoObject.getAdministrativeAreas(),
// Получаем путь до топонима, если метод вернул null, запрашиваем наименование здания.
firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
].filter(Boolean).join(', '),
// В качестве контента балуна задаем строку с адресом объекта.
balloonContent: firstGeoObject.getAddressLine()
});
});
}
Insert cell
places = ["Лебединый заказник, озеро Светлое", "Гора Церковка, Белокуриха", "Денисова пещера, с. Чёрный Ануй, Солонешенский район, Алтайский край"]
Insert cell
Insert cell
viewof scale = Inputs.range([1, 12], {step: 1, value: 11, label: "Масштаб карты:", width:500})
Insert cell
Insert cell
Insert cell
Insert cell
function divs() {
var container_1 = document.getElementById('wind_1');
var container_2 = document.getElementById('wind_2');
return [container_1, container_2];
}
Insert cell
Массив контейнеров
Insert cell
con = divs()
Insert cell
{yield con[0];
//очистка контейнеров
con[0].innerHTML = '';
con[1].innerHTML = '';
// к левой карте привязываем свою локацию
// var location = ymaps.geolocation;
yield con[0];
let map1 = new ymaps.Map(con[0], {
center: [53.36, 83.75], //Барнаул
zoom: scale});
let map2 = new ymaps.Map(con[1], {
center: [53.36, 83.75], //Барнаул
zoom: scale+4});
yield con[1];

map1.events.add('click', function (e) {
var coords = e.get('coords');
map1.balloon.open(coords, `Выбрано:[${coords[0].toFixed(2)}, ${coords[1].toFixed(2)}]`);
//плавное перемешщение в заданную точку на правой карте
map2.panTo(coords, {delay: 1000, duration: 1000, flying: true});
var circle = new ymaps.Circle([coords, 300], {geodesic: true, hintContent: "Полученная область"}, {
// Задаем опции круга.
// Цвет заливки.
// Последний байт (33) определяет прозрачность.
// Прозрачность заливки также можно задать используя опцию "fillOpacity".
fillColor: "#aa003333",
// Цвет обводки.
strokeColor: "#334466",
// Прозрачность обводки.
strokeOpacity: 0.9,
// Ширина обводки в пикселях.
strokeWidth: 2
});
// Добавляем круг на карту.
map2.geoObjects.removeAll();
map2.geoObjects.add(circle);
});
}
Insert cell
Insert cell
viewof select_place = Inputs.select(places, {label: "Укажите место назначения"})
Insert cell
types = ["auto", "masstransit", "pedestrian", "bicycle"]
Insert cell
Insert cell
viewof select_type = Inputs.select(types, {label: "Укажите способ передвижения"})
Insert cell
{
let wind = html`<div style='height:400px;'></div>`;//контейнер
yield wind;
let map = new ymaps.Map(wind, {
center: [53.36, 83.75], //Барнаул
zoom: 7});
// Построение маршрута на автомобиле
// Создание экземпляра маршрута.
var multyroute_A_B = new ymaps.multiRouter.MultiRoute({
referencePoints: [
'Баранул',
select_place
],
params: {
// Тип маршрута: на автомобиле, пешком, велосипед...
routingMode: select_type
}
}, {
// Автоматически устанавливать границы карты так,
// чтобы маршрут был виден целиком.
boundsAutoApply: true
});

// Добавление маршрута на карту.
map.geoObjects.add(multyroute_A_B);
}
Insert cell
Insert cell
{
let wind = html`<div style='height:500px;'></div>`;
yield wind;
let map = new ymaps.Map(wind, {
center: [52.30, 82.47],
zoom: 7 });
let bordermap = ymaps.borders.load('RU', {lang: 'ru', quality: 1}).
then(function (geojson) {
var regions = ymaps.geoQuery(geojson);
regions.search('properties.iso3166 = "RU-ALT"').
setOptions({fillColor:'#ff001a', fillOpacity: 0.3, strokeColor: '#ffffff', strokeOpacity: 0.8, strokeWidth: 6});
regions.addToMap(map);
});
map_yandex[2]=map
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more