简体   繁体   English

如何在谷歌地图上移动标记反应js

[英]How to move marker on the google map react js

I want to move multiple markers on the google map when I get the latitude and longitude from MongoDB. 当我从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. 我总是从db获得更新的纬度和经度,但我的标记没有移动,刷新页面后,标记位置正在变化,但我需要在不刷新页面的情况下进行。

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_id")){
                    _this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
                }
                else{
                    _this.state.dronePosition.push({id: element._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.forEach( function(element) {
                if(element.userId == localStorage.getItem("user_id")){
                    _this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
                }
                else{
                    _this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
                }
               });
                _this.getAllDrones2();
             }) 
    }

getAllDrones2(){
        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.forEach( function(element) {
                if(element.userId == localStorage.getItem("user_id")){
                    _this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
                }
                else{
                    _this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
                }
               });
                _this.getAllDrones();
             }) 
    }


render(){
    var _this = this;
    const { google } = this.props;
    const icon = {
        url: `data:image/jpeg;base64,${binary_data}`, 
        scaledSize: new google.maps.Size(40, 40), 
        origin: new google.maps.Point(0,0), 
        anchor: new google.maps.Point(0, 0) 
    };
        return (
            <div>
                <Header />
                    <Map className="map" google={google} initialCenter={userLocation} zoom={15} onClick={this.onMapClicked} >

                                {_this.state.dronePosition.map(marker => (
                                    <Marker
                                      onClick={_this.MarkerClick.bind(_this, marker.id)}
                                      icon={marker.photo}
                                      position={{ lat: marker.latitude, lng: marker.longitude }}
                                      key={marker.id}
                                    />
                                ))}         
                    </Map>
            </div>
            )
    }

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. 由于我无法访问您的mongo-db,因此我只使用虚拟api进行演示。

And when making api-calls they should be used in Lifecycle-method componentDidMount, not in the constructor. 在进行api调用时,它们应该在Lifecycle-method componentDidMount中使用,而不是在构造函数中使用。

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. 我遗漏了本地存储的if语句和element.userID,因为我不知道那是什么和组件,因为我无法访问它。

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 markers</div>
        render the map here...
      </div>
    ); 
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM