React Leaflet: Updating coords of multiple markers in state





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I can't seem to figure out how to properly update the coords of individual markers after storing them in the state. How it works currently is that when you click somewhere on the map, it adds a marker and stores its initial position in the state (in markerData) which is then displayed on the map through a map function. You can move the individual markers around but I'm having difficulty figuring out a possible solution to updating the specific markers position so that eventually I can send and store the marker information in the back end.



Here is my current code.



import React, { Component } from 'react';
import { ImageOverlay, Map, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet/dist/leaflet.js';
import L from 'leaflet';

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
iconUrl: require('leaflet/dist/images/marker-icon.png'),
shadowUrl: require('leaflet/dist/images/marker-shadow.png')
});

export default class CustomMapExample extends Component {
constructor(props) {
super(props);
this.state = {
center: {
lat: 512,
lng: 1024,
},
zoom: 1,
draggable: true,
dimensions: [1024, 2048],
markerData: ,
};
}

toggleDraggable = () => {
this.setState({ draggable: !this.state.draggable })
}

addMarker = (event) => {
const {markerData} = this.state
const coords = event.latlng
markerData.push(coords)
this.setState({markerData})
}

updateMarker = (event) => {
console.log(event)
}

render () {
const boundOrigin = [0, 0];
const bounds = [boundOrigin, this.state.dimensions];
const position = [this.state.center.lat, this.state.center.lng]

return (
<div>
<Map
id="map"
crs={L.CRS.Simple}
minZoom={-1}
bounds={bounds}
center={position}
zoom={this.state.zoom}
onClick={this.addMarker}
>
<ImageOverlay
url='http://www.online-tabletop.com/wp-content/uploads/2017/01/tutoriala.jpg'
bounds={bounds}
/>
{this.state.markerData.map((element, index) =>
<Marker
key={index}
position={element}
draggable={this.state.draggable}
onDragend={this.updateMarker}
>
<Popup>
<span onClick={this.toggleDraggable}>
{this.state.draggable ? `Hello` : 'MARKER FIXED'}
</span>
</Popup>
</Marker>
)}
</Map>
</div>
);
}
}









share|improve this question





























    1















    I can't seem to figure out how to properly update the coords of individual markers after storing them in the state. How it works currently is that when you click somewhere on the map, it adds a marker and stores its initial position in the state (in markerData) which is then displayed on the map through a map function. You can move the individual markers around but I'm having difficulty figuring out a possible solution to updating the specific markers position so that eventually I can send and store the marker information in the back end.



    Here is my current code.



    import React, { Component } from 'react';
    import { ImageOverlay, Map, Marker, Popup } from 'react-leaflet';
    import 'leaflet/dist/leaflet.css';
    import 'leaflet/dist/leaflet.js';
    import L from 'leaflet';

    delete L.Icon.Default.prototype._getIconUrl;

    L.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
    iconUrl: require('leaflet/dist/images/marker-icon.png'),
    shadowUrl: require('leaflet/dist/images/marker-shadow.png')
    });

    export default class CustomMapExample extends Component {
    constructor(props) {
    super(props);
    this.state = {
    center: {
    lat: 512,
    lng: 1024,
    },
    zoom: 1,
    draggable: true,
    dimensions: [1024, 2048],
    markerData: ,
    };
    }

    toggleDraggable = () => {
    this.setState({ draggable: !this.state.draggable })
    }

    addMarker = (event) => {
    const {markerData} = this.state
    const coords = event.latlng
    markerData.push(coords)
    this.setState({markerData})
    }

    updateMarker = (event) => {
    console.log(event)
    }

    render () {
    const boundOrigin = [0, 0];
    const bounds = [boundOrigin, this.state.dimensions];
    const position = [this.state.center.lat, this.state.center.lng]

    return (
    <div>
    <Map
    id="map"
    crs={L.CRS.Simple}
    minZoom={-1}
    bounds={bounds}
    center={position}
    zoom={this.state.zoom}
    onClick={this.addMarker}
    >
    <ImageOverlay
    url='http://www.online-tabletop.com/wp-content/uploads/2017/01/tutoriala.jpg'
    bounds={bounds}
    />
    {this.state.markerData.map((element, index) =>
    <Marker
    key={index}
    position={element}
    draggable={this.state.draggable}
    onDragend={this.updateMarker}
    >
    <Popup>
    <span onClick={this.toggleDraggable}>
    {this.state.draggable ? `Hello` : 'MARKER FIXED'}
    </span>
    </Popup>
    </Marker>
    )}
    </Map>
    </div>
    );
    }
    }









    share|improve this question

























      1












      1








      1


      0






      I can't seem to figure out how to properly update the coords of individual markers after storing them in the state. How it works currently is that when you click somewhere on the map, it adds a marker and stores its initial position in the state (in markerData) which is then displayed on the map through a map function. You can move the individual markers around but I'm having difficulty figuring out a possible solution to updating the specific markers position so that eventually I can send and store the marker information in the back end.



      Here is my current code.



      import React, { Component } from 'react';
      import { ImageOverlay, Map, Marker, Popup } from 'react-leaflet';
      import 'leaflet/dist/leaflet.css';
      import 'leaflet/dist/leaflet.js';
      import L from 'leaflet';

      delete L.Icon.Default.prototype._getIconUrl;

      L.Icon.Default.mergeOptions({
      iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
      iconUrl: require('leaflet/dist/images/marker-icon.png'),
      shadowUrl: require('leaflet/dist/images/marker-shadow.png')
      });

      export default class CustomMapExample extends Component {
      constructor(props) {
      super(props);
      this.state = {
      center: {
      lat: 512,
      lng: 1024,
      },
      zoom: 1,
      draggable: true,
      dimensions: [1024, 2048],
      markerData: ,
      };
      }

      toggleDraggable = () => {
      this.setState({ draggable: !this.state.draggable })
      }

      addMarker = (event) => {
      const {markerData} = this.state
      const coords = event.latlng
      markerData.push(coords)
      this.setState({markerData})
      }

      updateMarker = (event) => {
      console.log(event)
      }

      render () {
      const boundOrigin = [0, 0];
      const bounds = [boundOrigin, this.state.dimensions];
      const position = [this.state.center.lat, this.state.center.lng]

      return (
      <div>
      <Map
      id="map"
      crs={L.CRS.Simple}
      minZoom={-1}
      bounds={bounds}
      center={position}
      zoom={this.state.zoom}
      onClick={this.addMarker}
      >
      <ImageOverlay
      url='http://www.online-tabletop.com/wp-content/uploads/2017/01/tutoriala.jpg'
      bounds={bounds}
      />
      {this.state.markerData.map((element, index) =>
      <Marker
      key={index}
      position={element}
      draggable={this.state.draggable}
      onDragend={this.updateMarker}
      >
      <Popup>
      <span onClick={this.toggleDraggable}>
      {this.state.draggable ? `Hello` : 'MARKER FIXED'}
      </span>
      </Popup>
      </Marker>
      )}
      </Map>
      </div>
      );
      }
      }









      share|improve this question














      I can't seem to figure out how to properly update the coords of individual markers after storing them in the state. How it works currently is that when you click somewhere on the map, it adds a marker and stores its initial position in the state (in markerData) which is then displayed on the map through a map function. You can move the individual markers around but I'm having difficulty figuring out a possible solution to updating the specific markers position so that eventually I can send and store the marker information in the back end.



      Here is my current code.



      import React, { Component } from 'react';
      import { ImageOverlay, Map, Marker, Popup } from 'react-leaflet';
      import 'leaflet/dist/leaflet.css';
      import 'leaflet/dist/leaflet.js';
      import L from 'leaflet';

      delete L.Icon.Default.prototype._getIconUrl;

      L.Icon.Default.mergeOptions({
      iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
      iconUrl: require('leaflet/dist/images/marker-icon.png'),
      shadowUrl: require('leaflet/dist/images/marker-shadow.png')
      });

      export default class CustomMapExample extends Component {
      constructor(props) {
      super(props);
      this.state = {
      center: {
      lat: 512,
      lng: 1024,
      },
      zoom: 1,
      draggable: true,
      dimensions: [1024, 2048],
      markerData: ,
      };
      }

      toggleDraggable = () => {
      this.setState({ draggable: !this.state.draggable })
      }

      addMarker = (event) => {
      const {markerData} = this.state
      const coords = event.latlng
      markerData.push(coords)
      this.setState({markerData})
      }

      updateMarker = (event) => {
      console.log(event)
      }

      render () {
      const boundOrigin = [0, 0];
      const bounds = [boundOrigin, this.state.dimensions];
      const position = [this.state.center.lat, this.state.center.lng]

      return (
      <div>
      <Map
      id="map"
      crs={L.CRS.Simple}
      minZoom={-1}
      bounds={bounds}
      center={position}
      zoom={this.state.zoom}
      onClick={this.addMarker}
      >
      <ImageOverlay
      url='http://www.online-tabletop.com/wp-content/uploads/2017/01/tutoriala.jpg'
      bounds={bounds}
      />
      {this.state.markerData.map((element, index) =>
      <Marker
      key={index}
      position={element}
      draggable={this.state.draggable}
      onDragend={this.updateMarker}
      >
      <Popup>
      <span onClick={this.toggleDraggable}>
      {this.state.draggable ? `Hello` : 'MARKER FIXED'}
      </span>
      </Popup>
      </Marker>
      )}
      </Map>
      </div>
      );
      }
      }






      react-leaflet






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 17:17









      David SonDavid Son

      112




      112
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Since Marker accepts options object as a second parameter, marker index could be introduced to reference which marker is getting updated:



          <Marker
          key={index}
          marker_index={index}
          position={element}
          draggable={this.state.draggable}
          onDragend={this.updateMarker}
          />


          And then markerData state could be updated like this once the marker is dragged:



          updateMarker = event => {
          const latLng = event.target.getLatLng(); //get updated marker LatLng
          const markerIndex = event.target.options.marker_index; //get marker index
          //update
          this.setState(prevState => {
          const markerData = [...prevState.markerData];
          markerData[markerIndex] = latLng;
          return { markerData: markerData };
          });
          };


          Demo






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342547%2freact-leaflet-updating-coords-of-multiple-markers-in-state%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Since Marker accepts options object as a second parameter, marker index could be introduced to reference which marker is getting updated:



            <Marker
            key={index}
            marker_index={index}
            position={element}
            draggable={this.state.draggable}
            onDragend={this.updateMarker}
            />


            And then markerData state could be updated like this once the marker is dragged:



            updateMarker = event => {
            const latLng = event.target.getLatLng(); //get updated marker LatLng
            const markerIndex = event.target.options.marker_index; //get marker index
            //update
            this.setState(prevState => {
            const markerData = [...prevState.markerData];
            markerData[markerIndex] = latLng;
            return { markerData: markerData };
            });
            };


            Demo






            share|improve this answer






























              1














              Since Marker accepts options object as a second parameter, marker index could be introduced to reference which marker is getting updated:



              <Marker
              key={index}
              marker_index={index}
              position={element}
              draggable={this.state.draggable}
              onDragend={this.updateMarker}
              />


              And then markerData state could be updated like this once the marker is dragged:



              updateMarker = event => {
              const latLng = event.target.getLatLng(); //get updated marker LatLng
              const markerIndex = event.target.options.marker_index; //get marker index
              //update
              this.setState(prevState => {
              const markerData = [...prevState.markerData];
              markerData[markerIndex] = latLng;
              return { markerData: markerData };
              });
              };


              Demo






              share|improve this answer




























                1












                1








                1







                Since Marker accepts options object as a second parameter, marker index could be introduced to reference which marker is getting updated:



                <Marker
                key={index}
                marker_index={index}
                position={element}
                draggable={this.state.draggable}
                onDragend={this.updateMarker}
                />


                And then markerData state could be updated like this once the marker is dragged:



                updateMarker = event => {
                const latLng = event.target.getLatLng(); //get updated marker LatLng
                const markerIndex = event.target.options.marker_index; //get marker index
                //update
                this.setState(prevState => {
                const markerData = [...prevState.markerData];
                markerData[markerIndex] = latLng;
                return { markerData: markerData };
                });
                };


                Demo






                share|improve this answer















                Since Marker accepts options object as a second parameter, marker index could be introduced to reference which marker is getting updated:



                <Marker
                key={index}
                marker_index={index}
                position={element}
                draggable={this.state.draggable}
                onDragend={this.updateMarker}
                />


                And then markerData state could be updated like this once the marker is dragged:



                updateMarker = event => {
                const latLng = event.target.getLatLng(); //get updated marker LatLng
                const markerIndex = event.target.options.marker_index; //get marker index
                //update
                this.setState(prevState => {
                const markerData = [...prevState.markerData];
                markerData[markerIndex] = latLng;
                return { markerData: markerData };
                });
                };


                Demo







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 18 '18 at 8:31

























                answered Nov 17 '18 at 20:00









                Vadim GremyachevVadim Gremyachev

                37.8k774116




                37.8k774116
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342547%2freact-leaflet-updating-coords-of-multiple-markers-in-state%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues