Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.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_Next.js_Google Maps React - Fatal编程技术网

Javascript 如何更新谷歌地图反应路线?

Javascript 如何更新谷歌地图反应路线?,javascript,reactjs,google-maps,next.js,google-maps-react,Javascript,Reactjs,Google Maps,Next.js,Google Maps React,我有一个坐标数组,如果我在数组中添加另一个坐标,地图的路线方向应该更新 这是我在googlemap.js中的代码 /* global google */ import React, { Component } from "react"; import { Map, GoogleApiWrapper } from "google-maps-react"; import "./config"; import Router from 'nex

我有一个坐标数组,如果我在数组中添加另一个坐标,地图的路线方向应该更新

这是我在googlemap.js中的代码

/* global google */
import React, { Component } from "react";
import { Map, GoogleApiWrapper } from "google-maps-react";
import "./config";
import Router from 'next/router';


class MapContainer extends React.Component {


  constructor(props) {
    super(props);
    this.handleMapReady = this.handleMapReady.bind(this);
  }

  handleMapReady(mapProps, map) {
    this.calculateAndDisplayRoute(map);
  }
  

calculateAndDisplayRoute(map) {
  const directionsService = new google.maps.DirectionsService();
  const directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);

  const waypoints = this.props.data.map((item) => {
    return {
      location: { lat: item.lat, lng: item.lng },
      stopover: true,
    };
  });
  const origin = waypoints.shift().location;
  const destination = waypoints.pop().location;

  directionsService.route(
    {
      origin: origin,
      destination: destination,
      waypoints: waypoints,
      travelMode: "DRIVING",
    },
    (response, status) => {
      if (status === "OK") {
        directionsDisplay.setDirections(response);
      } else {
        window.alert("Directions request failed due to " + status);
      }
    }
  );
}
  render() {
   
    return (
      <div className="map-container"  >
        <Map
          google={this.props.google}
          className={"map"}
          zoom={14}
          initialCenter={{
            lat: 14.5995,
            lng: 120.9842,
          }}
          onClick={this.handleMapClick}
          onReady={this.handleMapReady}
        />
      </div>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "",
  libraries: [],
})(MapContainer);
/*全球谷歌*/
从“React”导入React,{Component};
从“google maps react”导入{Map,GoogleApiWrapper};
导入“/config”;
从“下一个/路由器”导入路由器;
类MapContainer扩展了React.Component{
建造师(道具){
超级(道具);
this.handleMapReady=this.handleMapReady.bind(this);
}
handleMapReady(地图道具、地图){
此。计算显示路线(地图);
}
计算显示路线(地图){
const directionsService=new google.maps.directionsService();
const directionsDisplay=new google.maps.DirectionsRenderer();
方向显示.setMap(地图);
const waypoints=this.props.data.map((项目)=>{
返回{
位置:{lat:item.lat,lng:item.lng},
中途停留:是的,
};
});
常量原点=航路点.shift().位置;
const destination=waypoints.pop().位置;
方向服务.路线(
{
来源:来源,,
目的地:目的地,
航路点:航路点,
travelMode:“驾驶”,
},
(响应、状态)=>{
如果(状态==“正常”){
方向显示。设置方向(响应);
}否则{
窗口警报(“由于“+状态,指示请求失败”);
}
}
);
}
render(){
返回(
);
}
}
导出默认GoogleApprapper({
apiKey:“,
图书馆:[],
})(地图容器);

我在这个插件中有点新,因为我在过去几天里使用了react google maps,但它不再被维护,这就是我现在使用这个插件的原因。

如果你有一个坐标数组,并且想在地图中显示这些坐标的方向,您需要将
第一个坐标
设置为
起点
最后一个坐标
设置为
目的地
之间的
坐标设置为
航路点

然后,在阵列中添加新坐标后,需要在航路点中包含上一个最后一个坐标,并将新添加的坐标作为目的地

这是一个例子,我使用Google Place Autocomplete,你可以输入一个地点,它会提供建议,一旦你从建议中选择了一个地点,它就会得到它的坐标,并在数组中推送坐标

请参阅下面的代码片段:

import React, { Component } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";
import "./style.css";
import "./config";
export class MapContainer extends Component {

  onMapReady = (mapProps, map) => {
    let coords = [];
    let waypoints = [];
    //put data from config file in an array
    {
      places.map((place) => coords.push({ lat: place.lat, lng: place.lng }));
    }

    //instantiate directions service and directions renderer
    const directionsService = new google.maps.DirectionsService();
    const directionsDisplay = new google.maps.DirectionsRenderer();
    //put directions renderer to render in the map
    directionsDisplay.setMap(map);
    //Getting the first coordinate in the array as the start/origin
    let start = { lat: coords[0].lat, lng: coords[0].lng };
    //Getting the last coordinate in the array as the end/destination
    let end = {
      lat: coords[coords.length - 1].lat,
      lng: coords[coords.length - 1].lng,
    };
    
    //putting all the coordinates between the first and last coordinate from the array as the waypoints
    for (let i = 1; i < coords.length - 1; i++) {
      waypoints.push({
        location: { lat: coords[i].lat, lng: coords[i].lng },
        stopover: true,
      });
    }

    // directions requests

    let request = {
      origin: start,
      waypoints: waypoints,
      destination: end,
      travelMode: "DRIVING",
    };
    //show results in the directionsrenderer
    directionsService.route(request, function (result, status) {
      if (status == "OK") {
        directionsDisplay.setDirections(result);
      }
    });

    //setting the autocomplete input
    let card = document.getElementById("pac-card");
    let input = document.getElementById("pac-input");
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
    let autocomplete = new google.maps.places.Autocomplete(input);

    // Bind the map's bounds (viewport) property to the autocomplete object,
    // so that the autocomplete requests use the current map bounds for the
    // bounds option in the request.
    autocomplete.bindTo("bounds", map);

    // Set the data fields to return when the user selects a place.
    autocomplete.setFields(["address_components", "geometry", "icon", "name"]);

    //listener for the places input
    autocomplete.addListener("place_changed", function () {
      console.log(waypoints);
      let place = autocomplete.getPlace();
      if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        window.alert("No details available for input: '" + place.name + "'");
        return;
      }
      
      //Putting the previous last coordinate in the array to be part of the waypoint
      waypoints.push({
        location: {
          lat: coords[coords.length - 1].lat,
          lng: coords[coords.length - 1].lng,
        },
        stopover: true,
      });

      //putting the Place Autocomplete coordinate result in the coords array
      coords.push({
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng(),
      });
      //putting the Place Autocomplete coordinate result the value of the end/destination
      end = place.geometry.location;
      
      //changing  request
      request = {
        origin: start,
        waypoints: waypoints,
        destination: end,
        travelMode: "DRIVING",
      };
      //creating new directions request
      directionsService.route(request, function (result, status) {
        if (status == "OK") {
          directionsDisplay.setDirections(result);
        }
      });
    });
  };


  render() {
    //if (!this.props.loaded) return <div>Loading...</div>;

    return (
      <div>
        <Map
          className="map"
          initialCenter={{ lat: 14.6091, lng: 121.0223 }}
          google={this.props.google}
          onClick={this.onMapClicked}
          onReady={this.onMapReady}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        ></Map>
        <div className="pac-card" id="pac-card">
          <div>
            <div id="title">Add new point</div>

            <div id="pac-container">
              <input
                id="pac-input"
                type="text"
                placeholder="Enter a location"
              />
            </div>
          </div>
        </div>
        <div style={{ width: 500, height: 500 }} id={this.props.id} />
        <div id="infowindow-content">
          <img src="" width="16" height="16" id="place-icon" />
          <span id="place-name" className="title"></span>
          <br />
          <span id="place-address"></span>
          <br />
          <span id="place-coord"></span>
        </div>
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "YOUR_API_KEY",
  version: "3.40",
})(MapContainer);
import React,{Component}来自“React”;
从“GoogleMaps react”导入{Map,InfoWindow,Marker,GoogleApiWrapper};
导入“/style.css”;
导入“/config”;
导出类MapContainer扩展组件{
onMapReady=(mapProps,map)=>{
设coords=[];
设航路点=[];
//将配置文件中的数据放入数组中
{
places.map((place)=>coords.push({lat:place.lat,lng:place.lng}));
}
//实例化方向服务和方向渲染器
const directionsService=new google.maps.directionsService();
const directionsDisplay=new google.maps.DirectionsRenderer();
//在地图中放置要渲染的方向渲染器
方向显示.setMap(地图);
//获取数组中的第一个坐标作为起点/原点
let start={lat:coords[0]。lat,lng:coords[0]。lng};
//获取数组中的最后一个坐标作为结束/目标
让结束={
lat:coords[coords.length-1]。lat,
lng:coords[coords.length-1].lng,
};
//将数组中第一个和最后一个坐标之间的所有坐标作为航路点
for(设i=1;i