如何在Google Map React JS上移动标记

时间:2019-03-29 05:17:58

标签: javascript reactjs google-maps

当我从MongoDB获取经度和纬度时,我想在Google地图上移动多个标记。我总是从db获取更新的纬度和经度,但是我的标记没有移动,刷新页面后,标记位置发生了变化,但是我需要在不刷新页面的情况下进行操作。

这是我的代码。

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>
            )
    }

1 个答案:

答案 0 :(得分:0)

如果您希望更新标记而不刷新页面,则需要将其添加到组件状态。由于我无权访问您的mongo-db,因此我仅使用了一个虚拟api进行演示。

并且在进行api调用时,应在生命周期方法componentDidMount中使用它们,而不是在构造函数中使用。

由于我不知道它是什么,并且由于无法访问该组件,所以省略了本地存储和element.userID的if语句。

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>
    ); 
  }
}