0

Есть балун:

var MyBalloonContentLayout = ymaps.templateLayoutFactory.createClass(
        '<div class="main">'+
        '<div class="driverInfo driverInfoContent" id="header">'+
        '<div class="photo driverInfoContent"><img src="icons/avatar.jpg" class="avatar"></div>'+
        '<div class="name driverInfoContent"><p>Ivan Ivan</p></div>'+
        '<div class="rating driverInfoContent"><p>4.8</p></div>'+
        '<div class="ratingPic driverInfoContent"><img src="icons/ratingIcon.png" class="ratingPic"></div>'+
        '</div>'+
        '<div class="line" id="footer">'+
        '<div class="carInfo line">'+
        '<div class="carPic"><img src="icons/Taxi_1.png" class="carPicture"></div>'+
        '<div class="carModelNumber">'+
        '<div class="model">BMX x4</div>'+
        '<div class="number">1234 BM-4</div>'+
        '</div>'+
        '</div>'+
        '<div class="reqBtn line btnPic" id="coords" onclick="hide()"></div>'+
        '</div>'+
        '<div class="afterHide" id="afterHide" hidden>'+
        '<input type="text" class="input" id="suggest" placeholder="Введите адресс">'+
        '</div>'+
        '<div id="buttons" hidden>'+
        '<div class="cancelBtn cancelBtnPic" id="cancel" onclick="back()" hidden></div>'+
        '<div class="confirmBtn confirmBtnPic" id="confirm"></div>'+
        '</div>'+
       '</div>'
    );

Он открывается при нажатию на метки, которые берутся из json файла.

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 0,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.678703,
          23.835601
        ]
      },
      "properties": {
        "hintContent": "Pizza&Coffe"
      },
      "options":{
        "preset":"islands#blueHomeIcon",
        "hasBalloon": false
      }
    },
    {
      "type": "Feature",
      "id": 1,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.674244,
          23.737227
        ]
      },
      "properties": {
        "hintContent": "Казановского 11"
      },
      "status": "free"
    },
    {
      "type": "Feature",
      "id": 2,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.682719,
          23.831406
        ]
      },
      "properties": {
        "hintContent": "Виленская 6"
      },
      "status": "free"
    },
    {
      "type": "Feature",
      "id": 3,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.656318,
          23.849840
        ]
      },
      "properties": {
        "hintContent": "Янки Купалы 80/2"
      },
      "status": "busy"
    },
    {
      "type": "Feature",
      "id": 4,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.622756,
          23.814832
        ]
      },
      "properties": {
        "hintContent": "Великая Ольшанка 15"
      },
      "status": "busy"
    },
    {
      "type": "Feature",
      "id": 5,
      "geometry": {
        "type": "Point",
        "coordinates": [
          53.685108,
          23.839967
        ]
      },
      "properties": {
        "hintContent": "Ожешко 22"
      },
      "status": "free"
    }
  ]
}

В балуне есть поле input. Я хочу вводить в это поле адрес и строить маршрут к этому адресу. Проблема в том, что js не видит этот input, т.к. он создается в js файле и не относится к родительскому HTML документу.

Как мне его туда добавить? Бьюсь уже 3 день.

Весь код js-файла.

ymaps.ready(init);

function init() {
    var myMap = new ymaps.Map('map', {
            center: [53.677850, 23.829484],
            zoom: 10,
        }, {
            searchControlProvider: 'yandex#search'
        });

    var MyBalloonContentLayout = ymaps.templateLayoutFactory.createClass(
        '<div class="main">'+
        '<div class="driverInfo driverInfoContent" id="header">'+
        '<div class="photo driverInfoContent"><img src="icons/avatar.jpg" class="avatar"></div>'+
        '<div class="name driverInfoContent"><p>Ivan Ivan</p></div>'+
        '<div class="rating driverInfoContent"><p>4.8</p></div>'+
        '<div class="ratingPic driverInfoContent"><img src="icons/ratingIcon.png" class="ratingPic"></div>'+
        '</div>'+
        '<div class="line" id="footer">'+
        '<div class="carInfo line">'+
        '<div class="carPic"><img src="icons/Taxi_1.png" class="carPicture"></div>'+
        '<div class="carModelNumber">'+
        '<div class="model">BMX x4</div>'+
        '<div class="number">1234 BM-4</div>'+
        '</div>'+
        '</div>'+
        '<div class="reqBtn line btnPic" id="coords" onclick="hide()"></div>'+
        '</div>'+
        '<div class="afterHide" id="afterHide" hidden>'+
        '<input type="text" class="input" id="suggest" placeholder="Введите адресс">'+
        '</div>'+
        '<div id="buttons" hidden>'+
        '<div class="cancelBtn cancelBtnPic" id="cancel" onclick="back()" hidden></div>'+
        '<div class="confirmBtn confirmBtnPic" id="confirm"></div>'+
        '</div>'+
        '</div>'
    );

    objectManager = new ymaps.ObjectManager({
        clusterize: false,
        gridSize: 32,
        geoObjectBalloonLayout: MyBalloonContentLayout,
        geoObjectBalloonShadow: false,
        geoObjectBalloonPanelMaxMapArea: 0,
        geoObjectBalloonOffset: [-285, -155],
        geoObjectHideIconOnBalloonOpen: false,
    });
    objectManager1 = new ymaps.ObjectManager({
        clusterize: false,
        gridSize: 32,
        hasBalloon:false
    });
    objectManager2 = new ymaps.ObjectManager({
        clusterize: false,
        gridSize: 32,
        hasBalloon:false
    });
    myMap.events.add('click', function (e) {
        myMap.balloon.close();
    });

    $.ajax({
        url: "data.json"
    }).done(function (data) {

        for(let i=1;i<data["features"].length;i++){
            objectManager2.add(data["features"][0]);
            if (data["features"][i]["status"]==="free"){
                data["features"][i]['options'] = [];
                data["features"][i]['options']['preset'] = 'islands#greenAutoIcon';
                objectManager.add(data["features"][i])
            }else{
                data["features"][i]['options'] = [];
                data["features"][i]['options']['preset'] = 'islands#redAutoIcon';
                data["features"][i]['options']['hasBalloon'] = 'false';
                objectManager1.add(data["features"][i])
            }
        }
        console.log(data);
        var maxLat = 0,
            maxLon = 0,
            minLat = 100,
            minLon = 100;
        objectManager.objects.each(function (object) {
            var lat = object.geometry.coordinates[0],
                lon = object.geometry.coordinates[1];
            maxLat = (lat <= maxLat) ? maxLat : lat;
            maxLon = (lon <= maxLon) ? maxLon : lon;
            minLat = (lat >= minLat) ? minLat : lat;
            minLon = (lon >= minLon) ? minLon : lon;
        }, myMap);
        objectManager1.objects.each(function (object) {
            var lat = object.geometry.coordinates[0],
                lon = object.geometry.coordinates[1];
            maxLat = (lat <= maxLat) ? maxLat : lat;
            maxLon = (lon <= maxLon) ? maxLon : lon;
            minLat = (lat >= minLat) ? minLat : lat;
            minLon = (lon >= minLon) ? minLon : lon;
        }, myMap);
        myMap.setBounds([[minLat, minLon], [maxLat, maxLon]]);
    });
    myMap.balloon.close(false);
    myMap.geoObjects.add(objectManager);
    myMap.geoObjects.add(objectManager1);
    myMap.geoObjects.add(objectManager2);
}
3
  • а почему хотите именно через балун это делать? можно добавить на карту собственный элемент управления, показывать его при клике на метку и заполнять нужными деталями. Если обязательно делать это через балуны, то вам нужно переопределять метод build и вообще заморачиваться с его логикой, которая вроде и не нужна задаче.
    – Reni
    16 авг 2018 в 10:07
  • Требуется именно через балун. Я не знаю как это сделать.
    – Ivan Ivan
    16 авг 2018 в 10:40
  • Тогда посмотрите, как сделано в примере и прочитайте документацию - вам нужно переопределять метод build, без этого это просто "мёртвый" html. После приведите код, если что-то не получится.
    – Reni
    16 авг 2018 в 10:58

1 ответ 1

1

При создании html шаблона надо переопределить метод build. В этом методе можно получить доступ к корневому элементу используя метод getElement. Пример:

var MyBalloonContentLayout = ymaps.templateLayoutFactory.createClass(
  `
   <div class="main">
     <input name="myinput"/>
   </div>
  `,
  {
    build: function () {
      MyBalloonContentLayout.superclass.build.call(this);
      var input = this.getElement().querySelector('input[name=myinput]');
      console.log('input', input);

    }
  }
);

jsfiddle: https://jsfiddle.net/jdswokty/13/

2
  • И потом обращаться к переменной, хранящей в себе инпут, а не по Id этого инупута, я правильно вас понимаю?
    – Ivan Ivan
    18 авг 2018 в 9:44
  • Организация кода на ваше усмотрение остается 20 авг 2018 в 12:18

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.