M
M
Mad Coder2020-08-12 09:26:16
JavaScript
Mad Coder, 2020-08-12 09:26:16

How to remove extra coordinates in react-yandex-map?

There is a React-Yandex-Map component. It takes addresses, translates them into coordinates, and displays them on the map. The problem is that when adding a new address, it adds a new coordinate, but at the same time two more old ones. How can this be avoided? Thanks in advance!

import React, { useState, useEffect } from 'react'
import { YMaps, Map, Placemark, Clusterer } from 'react-yandex-maps';

function App() {
    const [address, setAddress] =  useState(['Тверская область, г. Осташков, ул. Константина Заслонова, д.3', 'Тверская область, г. Осташков, ул. Константина Заслонова, д.7' ]);
    const [center, setCenter] = useState([57.142203, 33.125205]);
    const [state, setState] = useState([])
    const [pops, setPops] = useState(null);

    let geocode = (ymaps) => {
      address.forEach(item => {
         ymaps.geocode(item).then(result => {
          setState(prevState => [...prevState, result.geoObjects.get(0).geometry.getCoordinates()])
        })
      })
    }

    console.log(state)
    console.log(address)

    useEffect(() => {
      if(pops) {
        address.forEach(item => {
          pops.geocode(item).then(result => {
           setState(prevState => [...prevState, result.geoObjects.get(0).geometry.getCoordinates()])
         })
       })
      }
    }, [address])

    return (
        <div>
        <button
          onClick={() => {
            setAddress(prevState => [...prevState, 'Тверская область, г. Осташков, ул. Рудинская, д.7'])
          }}
        >Click</button>
        <YMaps
            query={{
                load: 'package.full',
                lang: 'ru_RU',
                apikey: '41694293-66c0-4133-89c1-0a6928c2497e',
            }}
        >
            <Map
              state={{
                  center: center,
                  zoom: 11,
                  controls: []
              }}
              style={{ height: '580px', width: '100%' }}
              modules={["geolocation", "geocode"]}
              onLoad={ymaps => {
                geocode(ymaps)
                setPops(ymaps)
              }}
              
            > 
               {
                 state.map(elem => {
                   return (
                    <Placemark key={Math.random()} geometry={elem} />
                   )
                 })
               }
            </Map>
        </YMaps>
        </div>
    )
}

export default App

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