Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用道具传递数据以使用谷歌地图显示多段线_Javascript_Reactjs_Google Maps_React Props_Polyline - Fatal编程技术网

Javascript 使用道具传递数据以使用谷歌地图显示多段线

Javascript 使用道具传递数据以使用谷歌地图显示多段线,javascript,reactjs,google-maps,react-props,polyline,Javascript,Reactjs,Google Maps,React Props,Polyline,下面是在谷歌地图上显示车辆移动的代码。 在代码中,对于路径数组,纬度和经度坐标被指定为硬代码值。 我需要的是,如何使用道具将纬度和经度坐标从另一个组件传递到“路径”数组 import React from "react"; import { withGoogleMap, withScriptjs, GoogleMap, Polyline, Marker, } from "react-google-maps"; class Map ex

下面是在谷歌地图上显示车辆移动的代码。 在代码中,对于路径数组,纬度和经度坐标被指定为硬代码值。 我需要的是,如何使用道具将纬度和经度坐标从另一个组件传递到“路径”数组

import React from "react";
import {
  withGoogleMap,
  withScriptjs,
  GoogleMap,
  Polyline,
  Marker,
} from "react-google-maps";

class Map extends React.Component {
  state = {
    progress: [],
  };

  path = [
    { lat: 18.558908, lng: -68.389916 },
    { lat: 18.558853, lng: -68.389922 },
    { lat: 18.558375, lng: -68.389729 },
    { lat: 18.558032, lng: -68.389182 },
    { lat: 18.55805, lng: -68.388613 },
    { lat: 18.558256, lng: -68.388213 },
    { lat: 18.558744, lng: -68.387929 },
  ];

  velocity = 5;
  initialDate = new Date();

  getDistance = () => {
    // seconds between when the component loaded and now
    const differentInTime = (new Date() - this.initialDate) / 1000; // pass to seconds
    return differentInTime * this.velocity; // d = v*t -- thanks Newton!
  };

  componentDidMount = () => {
    this.interval = window.setInterval(this.moveObject, 1000);
  };

  componentWillUnmount = () => {
    window.clearInterval(this.interval);
  };

  moveObject = () => {
    const distance = this.getDistance();
    if (!distance) {
      return;
    }

    let progress = this.path.filter(
      (coordinates) => coordinates.distance < distance
    );

    const nextLine = this.path.find(
      (coordinates) => coordinates.distance > distance
    );
    if (!nextLine) {
      this.setState({ progress });
      return; // it's the end!
    }
    const lastLine = progress[progress.length - 1];

    const lastLineLatLng = new window.google.maps.LatLng(
      lastLine.lat,
      lastLine.lng
    );

    const nextLineLatLng = new window.google.maps.LatLng(
      nextLine.lat,
      nextLine.lng
    );

    // distance of this line
    const totalDistance = nextLine.distance - lastLine.distance;
    const percentage = (distance - lastLine.distance) / totalDistance;

    const position = window.google.maps.geometry.spherical.interpolate(
      lastLineLatLng,
      nextLineLatLng,
      percentage
    );

    progress = progress.concat(position);
    this.setState({ progress });
  };

  componentWillMount = () => {
    this.path = this.path.map((coordinates, i, array) => {
      if (i === 0) {
        return { ...coordinates, distance: 0 }; // it begins here!
      }
      const { lat: lat1, lng: lng1 } = coordinates;
      const latLong1 = new window.google.maps.LatLng(lat1, lng1);

      const { lat: lat2, lng: lng2 } = array[0];
      const latLong2 = new window.google.maps.LatLng(lat2, lng2);

      // in meters:
      const distance = window.google.maps.geometry.spherical.computeDistanceBetween(
        latLong1,
        latLong2
      );

      return { ...coordinates, distance };
    });

    console.log(this.path);
  };

  render = () => {
    return (
      <GoogleMap
        defaultZoom={16}
        defaultCenter={{ lat: 18.559008, lng: -68.388881 }}
      >
        {this.state.progress && (
          <>
            <Polyline
              path={this.state.progress}
              options={{ strokeColor: "#FF0000 " }}
            />
            <Marker
              position={this.state.progress[this.state.progress.length - 1]}
            />
          </>
        )}
      </GoogleMap>
    );
  };
}

const MapComponent = withScriptjs(withGoogleMap(Map));

export default () => (
  <MapComponent
    googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
    loadingElement={<div style={{ height: `100%` }} />}
    containerElement={<div style={{ height: `400px`, width: "940px" }} />}
    mapElement={<div style={{ height: `100%` }} />}
  />
);

有人能帮我建这个吗?谢谢你的帮助

这是一个
注意:使用您自己的API键使代码工作)
和下面关于如何实现它的代码片段。在
index.js
中,我将路径数组放在json文件中,然后导入json文件作为映射中的元素。然后在我的
Map.js
中,我设置了构造函数(props)和super(props)。我将
react google maps
放在
render
中的
GoogleMapExample
变量中。然后我在
返回中使用这个变量。在代码的
组件willmount
函数中,需要使用
this.props.path.map
从props获取路径值

Index.js

import React, { Component } from "react";
import { render } from "react-dom";
import { withScriptjs } from "react-google-maps";
import Map from "./Map";
import "./style.css";
import jsonPath from "./data.json";

const App = () => {
  const MapLoader = withScriptjs(Map);

  return (
    <MapLoader
      path={jsonPath}
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry,places"
      loadingElement={<div style={{ height: `100%` }} />}
    />
  );
};

render(<App />, document.getElementById("root"));
import React,{Component}来自“React”;
从“react dom”导入{render};
从“react google maps”导入{withScriptjs};
从“/Map”导入地图;
导入“/style.css”;
从“/data.json”导入jsonPath;
常量应用=()=>{
const MapLoader=withScriptjs(Map);
返回(
);
};
render(,document.getElementById(“根”));
Map.js

import React, { Component } from "react";
import {
  withGoogleMap,
  GoogleMap,
  Polyline,
  Marker
} from "react-google-maps";

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progress: []
    };
  }

  velocity = 5;
  initialDate = new Date();

  getDistance = () => {
    // seconds between when the component loaded and now
    const differentInTime = (new Date() - this.initialDate) / 1000; // pass to seconds
    return differentInTime * this.velocity; // d = v*t -- thanks Newton!
  };

  componentDidMount = () => {
    this.interval = window.setInterval(this.moveObject, 1000);
    console.log(this.props.path);
  };

  componentWillUnmount = () => {
    window.clearInterval(this.interval);
  };

  moveObject = () => {
    const distance = this.getDistance();
    if (!distance) {
      return;
    }

    let progress = this.path.filter(
      coordinates => coordinates.distance < distance
    );

    const nextLine = this.path.find(
      coordinates => coordinates.distance > distance
    );
    if (!nextLine) {
      this.setState({ progress });
      return; // it's the end!
    }
    const lastLine = progress[progress.length - 1];

    const lastLineLatLng = new window.google.maps.LatLng(
      lastLine.lat,
      lastLine.lng
    );

    const nextLineLatLng = new window.google.maps.LatLng(
      nextLine.lat,
      nextLine.lng
    );

    // distance of this line
    const totalDistance = nextLine.distance - lastLine.distance;
    const percentage = (distance - lastLine.distance) / totalDistance;

    const position = window.google.maps.geometry.spherical.interpolate(
      lastLineLatLng,
      nextLineLatLng,
      percentage
    );

    progress = progress.concat(position);
    this.setState({ progress });
  };

  componentWillMount = () => {
    this.path = this.props.path.map((coordinates, i, array) => {
      if (i === 0) {
        return { ...coordinates, distance: 0 }; // it begins here!
      }
      const { lat: lat1, lng: lng1 } = coordinates;
      const latLong1 = new window.google.maps.LatLng(lat1, lng1);

      const { lat: lat2, lng: lng2 } = array[0];
      const latLong2 = new window.google.maps.LatLng(lat2, lng2);

      // in meters:
      const distance = window.google.maps.geometry.spherical.computeDistanceBetween(
        latLong1,
        latLong2
      );

      return { ...coordinates, distance };
    });

    console.log(this.path);
  };

  render() {
    const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultZoom={16}
        defaultCenter={{ lat: 6.8667528, lng: 79.8769134 }}
      >
        {this.state.progress && (
          <>
            <Polyline
              path={this.state.progress}
              options={{ strokeColor: "#FF0000 " }}
            />
            <Marker
              position={this.state.progress[this.state.progress.length - 1]}
            />
          </>
        )}
      </GoogleMap>
    ));

    return (
      <div>
        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: "500px" }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;
import React,{Component}来自“React”;
进口{
用谷歌地图,
谷歌地图,
多段线,
标记
}从“谷歌地图反应”;
类映射扩展组件{
建造师(道具){
超级(道具);
此.state={
进展:[]
};
}
速度=5;
initialDate=新日期();
getDistance=()=>{
//加载组件时与现在之间的秒数
const differentInTime=(new Date()-this.initialDate)/1000;//传递到秒
返回differentintTime*this.velocity;//d=v*t--谢谢牛顿!
};
componentDidMount=()=>{
this.interval=window.setInterval(this.moveObject,1000);
console.log(this.props.path);
};
组件将卸载=()=>{
window.clearInterval(this.interval);
};
moveObject=()=>{
常量距离=this.getDistance();
如果(!距离){
返回;
}
让progress=this.path.filter(
坐标=>坐标.距离<距离
);
const nextLine=this.path.find(
坐标=>坐标.距离>距离
);
如果(!nextLine){
this.setState({progress});
return;//结束了!
}
const lastLine=progress[progress.length-1];
const lastLineLatLng=new window.google.maps.LatLng(
lastLine.lat,
lastLine.lng
);
const nextlineatlng=new window.google.maps.LatLng(
nextLine.lat,
nextLine.lng
);
//这条线的距离
const totalDistance=nextLine.distance-lastLine.distance;
常量百分比=(距离-lastLine.distance)/总距离;
const position=window.google.maps.geometry.spheremic.interpolate(
lastLineLatLng,
下一步,
百分比
);
进度=进度。concat(位置);
this.setState({progress});
};
组件将装入=()=>{
this.path=this.props.path.map((坐标、i、数组)=>{
如果(i==0){
返回{…坐标,距离:0};//从这里开始!
}
常数{lat:lat1,lng:lng1}=坐标;
const latLong1=new window.google.maps.LatLng(lat1,lng1);
const{lat:lat2,lng:lng2}=array[0];
const latLong2=new window.google.maps.LatLng(lat2,lng2);
//以米为单位:
常量距离=window.google.maps.geometry.spheremic.ComputedDistanceBetween(
latLong1,
拉特朗2
);
返回{…坐标,距离};
});
console.log(this.path);
};
render(){
const GoogleMapExample=withGoogleMap(道具=>(
{this.state.progress&&(
)}
));
返回(
);
}
}
导出默认地图;
import React, { Component } from "react";
import {
  withGoogleMap,
  GoogleMap,
  Polyline,
  Marker
} from "react-google-maps";

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progress: []
    };
  }

  velocity = 5;
  initialDate = new Date();

  getDistance = () => {
    // seconds between when the component loaded and now
    const differentInTime = (new Date() - this.initialDate) / 1000; // pass to seconds
    return differentInTime * this.velocity; // d = v*t -- thanks Newton!
  };

  componentDidMount = () => {
    this.interval = window.setInterval(this.moveObject, 1000);
    console.log(this.props.path);
  };

  componentWillUnmount = () => {
    window.clearInterval(this.interval);
  };

  moveObject = () => {
    const distance = this.getDistance();
    if (!distance) {
      return;
    }

    let progress = this.path.filter(
      coordinates => coordinates.distance < distance
    );

    const nextLine = this.path.find(
      coordinates => coordinates.distance > distance
    );
    if (!nextLine) {
      this.setState({ progress });
      return; // it's the end!
    }
    const lastLine = progress[progress.length - 1];

    const lastLineLatLng = new window.google.maps.LatLng(
      lastLine.lat,
      lastLine.lng
    );

    const nextLineLatLng = new window.google.maps.LatLng(
      nextLine.lat,
      nextLine.lng
    );

    // distance of this line
    const totalDistance = nextLine.distance - lastLine.distance;
    const percentage = (distance - lastLine.distance) / totalDistance;

    const position = window.google.maps.geometry.spherical.interpolate(
      lastLineLatLng,
      nextLineLatLng,
      percentage
    );

    progress = progress.concat(position);
    this.setState({ progress });
  };

  componentWillMount = () => {
    this.path = this.props.path.map((coordinates, i, array) => {
      if (i === 0) {
        return { ...coordinates, distance: 0 }; // it begins here!
      }
      const { lat: lat1, lng: lng1 } = coordinates;
      const latLong1 = new window.google.maps.LatLng(lat1, lng1);

      const { lat: lat2, lng: lng2 } = array[0];
      const latLong2 = new window.google.maps.LatLng(lat2, lng2);

      // in meters:
      const distance = window.google.maps.geometry.spherical.computeDistanceBetween(
        latLong1,
        latLong2
      );

      return { ...coordinates, distance };
    });

    console.log(this.path);
  };

  render() {
    const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultZoom={16}
        defaultCenter={{ lat: 6.8667528, lng: 79.8769134 }}
      >
        {this.state.progress && (
          <>
            <Polyline
              path={this.state.progress}
              options={{ strokeColor: "#FF0000 " }}
            />
            <Marker
              position={this.state.progress[this.state.progress.length - 1]}
            />
          </>
        )}
      </GoogleMap>
    ));

    return (
      <div>
        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: "500px" }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;