How to move marker on the google map react js

General Tech Bugs & Fixes . 2 years ago

  0   2   0   0   0 tuteeHUB earn credit +10 pts

5 Star Rating 5 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Write Your Comments or Explanations to Help Others



Tuteehub forum answer Answers (2)


profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 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 2 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.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community