M
M
Mad Coder2020-08-12 04:37:18
Yandex maps
Mad Coder, 2020-08-12 04:37:18

How to dynamically add labels in React Yandex Map?

import React, { useEffect } from 'react'
import { YMaps, Map, Clusterer, Placemark } from 'react-yandex-maps';
import { useStyles } from './style';

const YandexMapComponent = ({ checkedObjects }) => {
  const classes = useStyles();
  let myMap;

function myGeoCode(ymaps, myMap, address) {
    ymaps.geocode(address, {
        results: 1
    }).then(function (res) {
        // Выбираем первый результат геокодирования.
        let firstGeoObject = res.geoObjects.get(0)
        // Координаты геообъекта.
        let coords = firstGeoObject.geometry.getCoordinates()
        // Область видимости геообъекта.
        let bounds = firstGeoObject.properties.get('boundedBy');

        firstGeoObject.options.set('preset', 'islands#darkBlueDotIconWithCaption');
        // Получаем строку с адресом и выводим в иконке геообъекта.
        //firstGeoObject.properties.set('iconCaption', firstGeoObject.getAddressLine());

        // Добавляем первый найденный геообъект на карту.
        myMap.geoObjects.add(firstGeoObject);
        // Масштабируем карту на область видимости геообъекта.
        myMap.setBounds(bounds, {
            // Проверяем наличие тайлов на данном масштабе.
            checkZoomRange: true
        });

        let myPlacemark = new ymaps.Placemark(coords, {
            iconContent: 'моя метка',
        }, {
            preset: 'islands#violetStretchyIcon'
        });

        myPlacemark.events.add('click', function() {
            alert(address)
        });

        myMap.geoObjects.add(myPlacemark);
    });
}

    function init(ymaps, myMap) {
        checkedObjects.forEach(address => myGeoCode(ymaps, myMap, `${address.district.city.name}, ${address.address}`))
    }

  return (
    <YMaps
      query={{
        ns: 'use-load-option',
        apikey: 'af28acb6-4b1c-4cd1-8251-b2f67a908cac',
        load: 'package.full'
      }}
    >
      <Map
        key={checkedObjects}
        state={{
          center: [],
          zoom: 9,
          controls: ['zoomControl', 'fullscreenControl']
        }}
        modules={["geolocation", "geocode"]}
        onLoad={ymaps => {
            ymaps.ready(() => {
                init(ymaps, myMap)
            });
        }}
        instanceRef={yaMap => {
            if (yaMap) {
                myMap = yaMap;
            }
        }}
        className={classes.mapContainterStyle}
      />
    </YMaps>
  )
};

export default YandexMapComponent;


created the specified component. Where at the address I display a label on the map. I have dynamic addition of addresses. How can I make them right. The only thing that came to this is forced redrawing of the component. I understand that this is a game, but I do not understand how to do it right. I would be grateful for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Nagayev, 2020-08-20
@nagayev

Well, in theory, the useState hook should help.
Example:

const [placemarks,setPlacemarks] = useState([]);
setPlacemarks([<Placemark key={0} geometry={[45.12,35.1]} />
return placemarks;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question