D
D
Denis Valerievich2020-12-23 18:52:29
Yandex maps
Denis Valerievich, 2020-12-23 18:52:29

Yandex Maps API. How to get label data in "input" when clicking on map?

Hello! I'm not very good at programming, so I hardly wrote this code in half to create a label on the map and pass its coordinates, address and scale to the "input" field. And slowed down on several tasks. Therefore, I decided to turn to the guru for help. Actually, the code is:

ymaps.ready(init);        
function init() {
  var myMap = new ymaps.Map("map", {
    center: [59.93840592010904,30.316897968261596],
    zoom: 12,
    controls: ['zoomControl', 'fullscreenControl', 'geolocationControl',
      new ymaps.control.SearchControl({
        options: {
          size: 'large',
          provider: 'yandex#search'
        }
      })]
  });
  
  /* Начальный адрес метки */
  var address = '59.93840592010904,30.316897968261596';
  
  ymaps.geocode(address).then(function(res) {
    var coord = res.geoObjects.get(0).geometry.getCoordinates();
    
    var myPlacemark = new ymaps.Placemark(coord, null, {
      preset: 'islands#blueDotIcon',
      draggable: true
    });
    
    myMap.events.add('click', function (e) {
      var coords = e.get('coords');
      
      // Если метка уже создана – просто передвигаем ее.
      if (myPlacemark) {
        myPlacemark.geometry.setCoordinates(coords);
      }
      // Если нет – создаем.
      else {
        myPlacemark = createPlacemark(coords);
        myMap.geoObjects.add(myPlacemark);
        // Слушаем событие окончания перетаскивания на метке.
        myPlacemark.events.add('dragend', function () {
          getAddress(myPlacemark.geometry.getCoordinates());
        });
      }
      getAddress(coords);
    });
    
    /* Событие dragend - получение нового адреса */
    myPlacemark.events.add('dragend', function(e){
      var coords = e.get('target').geometry.getCoordinates();
      var new_coords = [coords[0].toFixed(4), coords[1].toFixed(4)];
      $('#bpxl_infocoords').val(new_coords);
      ymaps.geocode(new_coords).then(function(res) {
        var data = res.geoObjects.get(0).properties.getAll();
        $('#bpxl_infoadress').val(data.text);
      });
      var zoom = myMap.getZoom()
        $('#bpxl_infoscale').val(zoom);
    });
    
    myMap.geoObjects.add(myPlacemark);	
    myMap.setCenter(coord, 12);
  });
  myMap.behaviors.disable('scrollZoom');
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
    myMap.behaviors.disable('drag');
  }
}

<!DOCTYPE html>

<head>
    <title>Определение адреса клика на карте с помощью обратного геокодирования</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!--
        Укажите свой API-ключ. Тестовый ключ НЕ БУДЕТ работать на других сайтах.
        Получить ключ можно в Кабинете разработчика: https://developer.tech.yandex.ru/keys/
    -->
    <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU&amp;apikey=<ваш API-ключ>" type="text/javascript"></script>
    <script src="event_reverse_geocode.js" type="text/javascript"></script>
    <script src="https://yandex.st/jquery/2.1.1/jquery.min.js"></script>
    <style type="text/css">
        html, body {
            width: 100%;
            height: 95%;
            margin: 0;
            padding: 0;
            font-family: Arial;
            font-size: 14px;
        }
        #map {
            width: 100%;
            height: 95%;
        }
        .header {
            padding: 5px;
        }
    </style>
</head>
<body>
<p class="header">Кликните по карте, чтобы узнать адрес</p>
<div id="map"></div>
Адрес: <input type="text" id="bpxl_infoadress">
Координаты: <input type="text" id="bpxl_infocoords">
Масштаб: <input type="text" id="bpxl_infoscale">
</body>
</html>

I check the performance of this code here - https://yandex.ru/dev/maps/jsbox/2.1/event_reverse... , replacing the native code with mine.

Actually, the problems themselves:
1. When moving the cursor by clicking on the map, the address and coordinates are not updated.
2. When changing the scale, the scale factor in the input does not change, only after moving the label.
3. How to remove the prefix "Russia, St. Petersburg" from the address and leave only the street and the house?

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question