微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用道具传递数据以在 Google 地图中显示折线

如何解决使用道具传递数据以在 Google 地图中显示折线

这是用于在谷歌地图上显示车辆运动的 reactjs 代码。 在代码中,对于 path 数组,纬度和经度坐标被指定为硬编码值。 我需要的是,应该如何使用 props 将纬度和经度坐标从另一个组件传递给“path”数组。

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%` }} />}
  />
);

这是来自 json 对象的示例数据,我从其他组件获取。我需要使用 props 将这些数据传递给上面的 path 数组。

[]
0: {lat: 6.8667528,lng: 79.8769134}
1: {lat: 6.8667112,lng: 79.8769667}
2: {lat: 6.8666556,lng: 79.8769856}
3: {lat: 6.8666023,lng: 79.8769823}
4: {lat: 6.8665584,lng: 79.8770412}
5: {lat: 6.8665478,lng: 79.8771573}
6: {lat: 6.8665295,lng: 79.8772695}
7: {lat: 6.8664823,lng: 79.8774434}
8: {lat: 6.8664434,lng: 79.8777684}
9: {lat: 6.8664023,lng: 79.87823}
10: {lat: 6.8663373,lng: 79.8786712}
11: {lat: 6.86628,lng: 79.87902}
12: {lat: 6.8662312,lng: 79.879335}
13: {lat: 6.8662145,lng: 79.8795562}
14: {lat: 6.8662095,lng: 79.879695}
15: {lat: 6.8661978,lng: 79.8797523}
16: {lat: 6.8659873,lng: 79.8798639}

谁能帮我建这个?感谢您的帮助!

解决方法

这是一个 sample code Note: use your own API key for the code to work) 和下面关于我如何实现它的代码片段。在 index.js 中,我将路径数组放在 json 文件中,然后导入 json 文件以用作地图中的元素。然后在我的 Map.js 中,我设置了构造函数(道具)和超级(道具)。我将 react-google-maps <GoogleMap> 放在 render 变量内的 GoogleMapExample 中。然后我在 return 中使用这个变量。在代码的 componentWillMount 函数中,您需要使用 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"));

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。