mapbox / mapbox.js

Mapbox JavaScript API, a Leaflet Plugin
mapbox.com/mapbox.js/
Other
1.92k stars 386 forks source link

setLngLat on marker doesn't work #1354

Open S-Masoud-Emamian opened 3 years ago

S-Masoud-Emamian commented 3 years ago

I want to change current marker to new position.

let marker = new mapboxgl.Marker({ color: 'red', draggable: true })

  useEffect(() => {
    initMap()
  }, [])

  const initMap = () => {
    mapboxgl.accessToken = '*******1g';
    if (mapboxgl.getRTLTextPluginStatus() !== 'loaded') {
      mapboxgl.setRTLTextPlugin(
        'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js',
        null,
        true // Lazy load the plugin
      );
    }

    const map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [51.446558, 33.980739],
      zoom: 12,
      textAlign: 'left'
    });

    map.on('click', function (e) {
      var coordinates = e.lngLat;
      marker.setLngLat(coordinates).addTo(map); //this line does't setted.
  });

    setTimeout(() => {
      initMapMarker(map, 51.41691337396722, 34.022980413997786)
    }, 1000);
  }

  const initMapMarker = (map, initLon, initLat) => {

    // eslint-disable-next-line no-unused-vars
    marker.setLngLat([initLon, initLat])
      .addTo(map);

    marker.on('dragend', () => {
      const lngLat = marker.getLngLat();
      getFormatedAddress(lngLat)

    });
  }

but after click on map this line did not work:

marker.setLngLat(coordinates).addTo(map);

It removed default marker.

riastrad commented 3 years ago

Thank you for using Mapbox! Please note that this repository's issues are used for reporting bugs and requesting features for Mapbox.js. For general how-to questions like this, we recommend contacting Mapbox Support or asking on Stack Overflow.

riastrad commented 3 years ago

Ah, wait. Looks like I closed this without reading closely enough. We can leave this open for further investigation for now.