Как в yandex map api автоматом открывать balloon у MultiRoute?
Всем привет! Сделал скрипт который при вводе адреса прокладывались 3 маршрута к ближайшим меткам. Никак не могу понять как автоматом открывать баул у MultiRoute. Пробовал и через events.fire('balloonopen'); ничего не помогает. Вот демо https://dev5.vh448018.eurodir.ru/
ymaps.ready(function () {
var myMap = new ymaps.Map('map', {
center: [37.617633, 55.755820],
zoom: 8,
controls: ['zoomControl', 'fullscreenControl', 'routeButtonControl'],
},
{
searchControlProvider: 'yandex#search'
});
var pinsJson, searchGeoPoision, objcsJson = [];
function findClosestObjects () {
// Найдем в выборке кафе, ближайшее к найденной станции метро,
// и откроем его балун.
//pinsJson.getClosestTo(searchGeoPoision.get(0)).balloon.open();
// Будем открывать балун кафе, который ближе всего к месту клика
/*myMap.events.add('click', function (event) {
pinsJson.getClosestTo(event.get('coords')).balloon.open();
});*/
console.log(searchGeoPoision.get(0).geometry.getCoordinates());
}
//console.log(objcsJson);
pinsJson = ymaps.geoQuery({
type: 'FeatureCollection',
"features": [
{
"type": "Feature",
"id": 0,
"geometry": {
"type": "Point",
"coordinates": [
37.49736,
55.824804
]
},
"properties": {
"description": "Москва, Ленинградское шоссе, 16",
"iconCaption": "Point 1",
"marker-color": "#1bad03"
}
},
{
"type": "Feature",
"id": 1,
"geometry": {
"type": "Point",
"coordinates": [
37.605939,
55.622609
]
},
"properties": {
"description": "Москва, Кировоградская улица, 14",
"iconCaption": "Point 2",
"marker-color": "#ffff00"
}
},
{
"type": "Feature",
"id": 2,
"geometry": {
"type": "Point",
"coordinates": [
37.606514,
55.883742
]
},
"properties": {
"description": "Москва, улица Плещеева, 4",
"iconCaption": "Point 3",
"marker-color": "#0000ff"
}
},
{
"type": "Feature",
"id": 3,
"geometry": {
"type": "Point",
"coordinates": [
37.495994,
55.693505
]
},
"properties": {
"description": "Россия, Москва, улица Раменки, 3",
"iconCaption": "Point 4",
"marker-color": "#000000"
}
},
{
"type": "Feature",
"id": 4,
"geometry": {
"type": "Point",
"coordinates": [
37.409253,
55.759238
]
},
"properties": {
"description": "Москва, Осенний бульвар, 12",
"iconCaption": "Point 5",
"marker-color": "#ff0000"
}
}
]
}).addToMap(myMap);
// С помощью обратного геокодирования найдем метро "Кропоткинская".
//searchGeoPoision = ymaps.geoQuery(ymaps.geocode([37.603423, 55.744828], {kind: 'metro'})).then(findClosestObjects);
/*
* Search
*/
var suggestView = new ymaps.SuggestView('suggest'),
routeIndex1,
routeIndex2,
routeIndex3;
$('#searchYanMap').submit(function(e) {
e.preventDefault();
var addr = $('#suggest').val();
if( addr != '' ) {
var myGeocoder = ymaps.geocode(addr, { results: 1 });
myGeocoder.then(
function (res) {
var cord = res.geoObjects.get(0).geometry.getCoordinates();
// console.log(cord[0]);
// console.log(cord[1]);
searchGeoPoision = ymaps.geoQuery(ymaps.geocode(cord, {kind: 'metro'})).then(function() {
/*var nearTips = pinsJson.getClosestTo(searchGeoPoision.get(0));
var nearTipsCord = nearTips.geometry.getCoordinates();
nearTips.balloon.open();*/
var sortedByPolyline = pinsJson.sortByDistance(cord);
// console.log(sortedByPolyline.get(0).geometry.getCoordinates());
// console.log(sortedByPolyline.get(1).geometry.getCoordinates());
// console.log(sortedByPolyline.get(3).geometry.getCoordinates());
var nearTips1 = sortedByPolyline.get(0),
nearTipsCord1 = nearTips1.geometry.getCoordinates(),
nearTips2 = sortedByPolyline.get(1),
nearTipsCord2 = nearTips2.geometry.getCoordinates(),
nearTips3 = sortedByPolyline.get(2),
nearTipsCord3 = nearTips3.geometry.getCoordinates();
// nearTips1.balloon.open();
// nearTips2.balloon.open();
// nearTips3.balloon.open();
//var tt = ;
if(routeIndex1) {
myMap.geoObjects.remove(routeIndex1);
myMap.geoObjects.remove(routeIndex2);
myMap.geoObjects.remove(routeIndex3);
}
var balloonLayout1 = ymaps.templateLayoutFactory.createClass(
"<div class='route-balloon'>" +
'<a class="close" href="#">×</a>' +
"<span class='title'>{{ properties.pinsTitle }}<span>{{ properties.pinsDesc }}</span></span>" +
"Расстояние: " +
"<i>{{ properties.distance.text }}</i>,<br />" +
"Время в пути: " +
"<i>{{ properties.duration.text }} (без учета пробок) </i>" +
"</div>", {
build: function () {
this.constructor.superclass.build.call(this);
this._$element = $('.route-balloon', this.getParentElement());
this._$element.find('.close')
.on('click', $.proxy(this.onCloseClick, this));
console.log(this);
},
onCloseClick: function (e) {
e.preventDefault();
this.events.fire('userclose');
},
}
);
//searchGeoPoision = ymaps.geoQuery(ymaps.geocode([37.603423, 55.744828], {kind: 'metro'})).then(findClosestObjects);
var multiRoute1 = new ymaps.multiRouter.MultiRoute({
// Точки маршрута. Точки могут быть заданы как координатами, так и адресом.
referencePoints: [
nearTipsCord1,
cord
],
params: {
results: 2,
// Тип маршрута: на общественном транспорте.
routingMode: "auto",
},
}, {
// Автоматически устанавливать границы карты так,
// чтобы маршрут был виден целиком.
//boundsAutoApply: true,
routeStrokeColor: "000088",
routeActiveStrokeColor: "ff0000",
pinIconFillColor: "ff0000",
balloonLayout: balloonLayout1,
// Отключаем режим панели для балуна.
balloonPanelMaxMapArea: 0,
test: 11233
});
//console.log(multiRoute1.model);
//multiRoute1.model.events.fire('balloonopen');
//multiRoute1._data.properties._data.test = 1111;
//multiRoute1.balloon.open();
//multiRoute1.events.fire(['balloonopen', 'click']);
//multiRoute1.events.add('click', this.up, this);
/*multiRoute1.properties.set({
test: nearTips1.properties._data.iconCaption,
test2: nearTips1.properties._data.balloonContent
});*/
var multiRoute2 = new ymaps.multiRouter.MultiRoute({
// Точки маршрута. Точки могут быть заданы как координатами, так и адресом.
referencePoints: [
nearTipsCord2,
addr
],
params: {
// Тип маршрута: на общественном транспорте.
routingMode: "auto"
}
}, {
// Автоматически устанавливать границы карты так,
// чтобы маршрут был виден целиком.
//boundsAutoApply: true
balloonLayout: balloonLayout1,
// Отключаем режим панели для балуна.
balloonPanelMaxMapArea: 0,
});
var multiRoute3 = new ymaps.multiRouter.MultiRoute({
// Точки маршрута. Точки могут быть заданы как координатами, так и адресом.
referencePoints: [
nearTipsCord3,
addr
],
params: {
// Тип маршрута: на общественном транспорте.
routingMode: "auto",
routeMarker: false,
}
}, {
// Автоматически устанавливать границы карты так,
// чтобы маршрут был виден целиком.
//boundsAutoApply: true
balloonLayout: balloonLayout1,
// Отключаем режим панели для балуна.
balloonPanelMaxMapArea: 0,
});
ymaps.vow.all([
multiRoute1,
multiRoute2,
multiRoute3
]).spread(function (route1, route2, route3) {
var objectsLength = myMap.geoObjects.getLength();
myMap.geoObjects.add(route1);
myMap.geoObjects.add(route2);
myMap.geoObjects.add(route3);
routeIndex1 = route1;
routeIndex2 = route2;
routeIndex3 = route3;
multiRoute1.model.events.add("requestsuccess", function () {
var routes = multiRoute1.model.getRoutes();
routes[0].properties.set('pinsTitle', nearTips1.properties._data.iconCaption);
routes[0].properties.set('pinsDesc', nearTips1.properties._data.balloonContent);
});
multiRoute2.model.events.add("requestsuccess", function () {
var routes = multiRoute2.model.getRoutes();
routes[0].properties.set('pinsTitle', nearTips2.properties._data.iconCaption);
routes[0].properties.set('pinsDesc', nearTips2.properties._data.balloonContent);
});
multiRoute3.model.events.add("requestsuccess", function () {
var routes = multiRoute3.model.getRoutes();
routes[0].properties.set('pinsTitle', nearTips3.properties._data.iconCaption);
routes[0].properties.set('pinsDesc', nearTips3.properties._data.balloonContent);
});
// Авто маштабирование
myMap.setBounds(sortedByPolyline.slice(0, 3).getBounds(), {
checkZoomRange: true,
zoomMargin: [150, 0, 100, 0]
});
});
});
}
); // End geocode
} else {
$('.wrap-suggest').addClass('empty');
setTimeout(function() {
$('.wrap-suggest').removeClass('empty');
}, 2000);
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<title>Map zavod</title>
<style>
#map {width: 100%;height: 700px;}
#notice{display: none;}
.wrap-suggest {transition: all 300ms linear;}
.wrap-suggest.empty:after {
content: 'Введите свой аддрес';
font-size: 12px;
transition: all 300ms linear;
margin-top: 5px;
display: table;
color: red;
}
.wrap-suggest.empty #suggest {border-color: red;transition: all 300ms linear}
.route-balloon {
display: inline-block;
padding: 4px 10px;
/*height: 75px;*/
position: relative;
bottom: 0;
left: -35px;
transform: translateY(-100%);
margin-top: -35px;
width: 158px;
font-size: 12px;
line-height: 15px;
color: #333333;
text-align: left;
vertical-align: middle;
background-color: #fff;
border-radius: 5px;
font-family: 'Arial', sans-serif;
position: relative;
box-shadow: 3px 3px 10px rgba(0, 0, 0, .3);
}
.route-balloon .title{
display: block;
/*font-size: 12px;*/
margin-bottom: 5px;
font-weight: 700;
color: #000;
}
.route-balloon .title span {
display: block;
font-weight: 400;
font-size: 11px;
}
.route-balloon .close {
position: absolute;
right: 4px;
top: 0;
}
</style>
<script src="https://yastatic.net/jquery/2.2.3/jquery.min.js"></script>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&coordorder=longlat&apikey=04107d8c-9835-492a-b09d-5252ee96daca"></script>
<script src="map.js"></script>
</head>
<body>
<br>
<br>
<br>
<div class="container">
<!-- <script type="text/javascript" charset="utf-8" async src="https://api-maps.yandex.ru/services/constructor/1.0/js/?um=constructor%3A25f3d5740f5d5a1aff192d6e12801721c0d1e7d74f3573ea19754665c456a94c&width=100%25&height=657&lang=ru_RU&id=map&scroll=true&search=true&apikey=04107d8c-9835-492a-b09d-5252ee96daca"></script> -->
<form action="#" id="searchYanMap">
<div class="form-group row">
<label for="inputPassword" class="col-sm-3 col-form-label"><b>Введите свой аддрес</b></label>
<div class="col-sm-7">
<div class="wrap-suggest">
<input type="text" class="form-control" placeholder="Напр.: Москва, ул. Никольская, 10" id="suggest" autocomplete="off">
</div>
</div>
<div class="col-sm-2">
<button class="btn btn-primary" id="btn-ymap-search">Найти</button>
</div>
</div>
<p id="notice">Адрес не найден</p>
</form>
<br>
<div id="map" class="map"></div>
</div>
<br>
<br>
<br>
</body>
</html>
Можно ввести например этот адрес: Москва, Новогиреевская улица, 48a Нужно чтобы при вводе адреса строился маршрут и автоматом открывался баул, результат должен быть такой https://yadi.sk/i/XnwHuhIzidCMKw
Долго искал решение, но так и не нашел как это сделать. Если кто знает подскажите куда копать