How to move marker on the google map react js

General Tech Bugs & Fixes 3 years ago

6.16K 2 0 0 0

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago

 

I want to move multiple markers on the google map when I get the latitude and longitude from MongoDB. I'm always getting updated latitude and longitude from db, but my markers are not moving, and after refreshing the page, the markers positions are changing, but I need to do it without refreshing the page.

This is my code`

class Maps extends React.Component {
 constructor(props){
 super(props);
    this.state = { 
        dronePosition: []
     };

    var _this = this;
    const config = { 
      headers: {
                "Authorization" : `Bearer ${localStorage.getItem('token')}`,
              }
    };


// If I'm using setInterval, the markers are not showing at all. That's why here I call the getAllDrones() function
// setInterval(function(){
axios.get(packages.proxy+'drones/getAllDrones',config)
             .then(res => {
 //Here I'm always getting updated positions for markers from backend.
                _this.state.dronePosition = [];
               res.data.forEach( function(element) {
                if(element.userId == localStorage.getItem("user_https://forum.tuteehub.com/tag/id">id")){
                    _this.state.dronePosition.push({https://forum.tuteehub.com/tag/id">id: element._https://forum.tuteehub.com/tag/id">id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
                }
                else{
                    _this.state.dronePosition.push({https://forum.tuteehub.com/tag/id">id: element._https://forum.tuteehub.com/tag/id">id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
                }
               });
                 _this.getAllDrones();
             }) 

        // }, 2000)

    }

getAllDrones(){
        var _this = this;
        const config = { 
              headers: {
                        "Authorization" : `Bearer ${localStorage.getItem('token')}`,
                      }
            };
        axios.get(packages.proxy+'drones/getAllDrones',config)
             .then(res => {
                _this.state.dronePosition = [];
               res.data
                                                
0 views
0 shares

profilepic.png
manpreet 3 years ago

 

If you want the markers to update without a refresh of the page you need to add them to the component state. Since I don't have access to your mongo-db I've used a dummy api just for demo purpose.

And when making api-calls they should be used in Lifecycle-method componentDidMount, not in the constructor.

I've left out the if-statement for local storage and element.userID since I don't know what that is and the component since I don't have access to it.

import React from "react";
import axios from "axios";

export default class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dronePosition: []
    };
  }

  componentDidMount() {
    this.refreshMarkers();
  }

  refreshMarkers = () => {
    // Clear state to prevent duplicates
    this.setState({dronePosition: []});
    const config = {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`
      }
    };
    axios.get("https://swapi.co/api/starships").then(res => {
      res.data.results.forEach(element => {
        this.setState({
          dronePosition: [...this.state.dronePosition, element]
        });
      });
      console.log(this.state.dronePosition);
    });
  };

  render() {
    return(
      <div>
        <div onClick={this.refreshMarkers}>Click on me to refresh markersdiv>
        render the map here...
      div>
    ); 
  }
}

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum