Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.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 Google Maps - Fatal编程技术网

Javascript 从路径删除点更新多边形

Javascript 从路径删除点更新多边形,javascript,reactjs,google-maps,react-google-maps,Javascript,Reactjs,Google Maps,React Google Maps,我有下面的地图,正如你应该在地图上我有一个多边形和标记,它们是多边形的主要点,下面我有多边形的主要点打印,即标记 我为用户提供了删除多边形点的可能性,如下图所示,通过单击X,该点被删除 问题是,当我单击X时,该点作为标记被消除,但它似乎仍然是多边形的固定点,这是不应该的,多边形应该根据消除的点更改其形状 我无法理解我错在哪里。 你能给我一些帮助吗 链接: 索引: import React from "react"; import ReactDOM from "react-dom"; impor

我有下面的地图,正如你应该在地图上我有一个多边形和标记,它们是多边形的主要点,下面我有多边形的主要点打印,即标记

我为用户提供了删除多边形点的可能性,如下图所示,通过单击X,该点被删除

问题是,当我单击X时,该点作为标记被消除,但它似乎仍然是多边形的固定点,这是不应该的,多边形应该根据消除的点更改其形状

我无法理解我错在哪里。 你能给我一些帮助吗

链接:

索引:

import React from "react";
import ReactDOM from "react-dom";

import Map from "./Map";
import "./styles.css";

//import { makeStyles } from "@material-ui/core/styles";
import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ClearIcon from "@material-ui/icons/Clear";
import TextField from "@material-ui/core/TextField";

const API_KEY = "MY_API_KEY";

/*const useStyles = makeStyles(theme => ({
  root: {
    width: "100%"
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: theme.typography.fontWeightRegular
  }
}));*/

const useStyles = theme => ({
  root: {
    width: "100%"
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: theme.typography.fontWeightRegular
  }
});

const center = {
  lat: 38.9065495,
  lng: -77.0518192
};

//const classes = useStyles();
//className={classes.heading}

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      paths: [
        { lat: 38.97330905858943, lng: -77.10469090410157 },
        { lat: 38.9209748864926, lng: -76.9083102888672 },
        { lat: 38.82689001319151, lng: -76.92204319902345 },
        { lat: 38.82261046915962, lng: -77.0181735701172 },
        { lat: 38.90174038629909, lng: -77.14314305253907 }
      ]
    };
  }

  render() {
    const { paths } = this.state;

    return (
      <div className="App2">
        <Map
          apiKey={API_KEY}
          center={center}
          paths={paths}
          point={paths => this.setState({ paths })}
        />
        {paths.map((pos, key) => {
          return (
            <ExpansionPanel key={key}>
              <ExpansionPanelSummary
                expandIcon={<ExpandMoreIcon />}
                aria-controls="panel1a-content"
                id="panel1a-header"
              >
                <ClearIcon
                  style={{ color: "#dc004e" }}
                  onClick={() => {
                    paths.splice(key, 1);
                    console.log(paths);
                    this.setState({ paths: paths });
                  }}
                />
                <Typography>Point #{key}</Typography>
              </ExpansionPanelSummary>
              <ExpansionPanelDetails>
                <TextField
                  fullWidth
                  key={"lat" + key}
                  label="Latitude"
                  type="text"
                  value={pos.lat}
                  disabled={true}
                />
                <TextField
                  fullWidth
                  key={"lng" + key}
                  label="Longitude"
                  type="text"
                  value={pos.lng}
                  disabled={true}
                />
              </ExpansionPanelDetails>
            </ExpansionPanel>
          );
        })}
      </div>
    );
  }
}

//export default withStyles(useStyles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
从“React”导入React;
从“react dom”导入react dom;
从“/Map”导入地图;
导入“/styles.css”;
//从“@material ui/core/styles”导入{makeStyles}”;
从“@material ui/core/ExpansionPanel”导入ExpansionPanel;
从“@material ui/core/ExpansionPanelSummary”导入ExpansionPanelSummary;
从“@material ui/core/ExpansionPanelDetails”导入ExpansionPanelDetails;
从“@material ui/core/Typography”导入排版;
从“@material ui/icons/ExpandMore”导入ExpandMoreIcon;
从“@material ui/icons/Clear”导入ClearIcon;
从“@material ui/core/TextField”导入TextField;
const API_KEY=“我的API_KEY”;
/*const useStyles=makeStyles(主题=>({
根目录:{
宽度:“100%”
},
标题:{
fontSize:主题。排版。pxToRem(15),
fontWeight:theme.typography.fontWeightRegular
}
}));*/
const useStyles=主题=>({
根目录:{
宽度:“100%”
},
标题:{
fontSize:主题。排版。pxToRem(15),
fontWeight:theme.typography.fontWeightRegular
}
});
常数中心={
纬度:38.9065495,
液化天然气:-77.0518192
};
//const classes=useStyles();
//className={classes.heading}
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
路径:[
{拉丁美洲:38.973309005858943,液化天然气:-77.10469090410157},
{拉丁美洲:38.92097488864926,液化天然气:-76.9083102888672},
{拉丁美洲:38.82689001319151,液化天然气:-76.92204319902345},
{拉丁美洲:38.82261046915962,液化天然气:-77.01817357011172},
{拉丁美洲:38.90174038629909,液化天然气:-77.14314305253907}
]
};
}
render(){
const{paths}=this.state;
返回(
this.setState({path})}
/>
{paths.map((位置,键)=>{
返回(
{
路径。拼接(图例1);
console.log(路径);
this.setState({path:path});
}}
/>
点#{key}
);
})}
);
}
}
//导出默认样式(useStyles)(应用程序);
const rootElement=document.getElementById(“根”);
render(,rootElement);
地图:

import React,{useState,useRef,useCallback}来自“React”;
进口{
加载脚本,
谷歌地图,
绘图经理,
多边形,
标记
}来自“@react谷歌地图/api”;
导入“/styles.css”;
常量库=[“绘图”];
常量选项={
drawingControl:对,
drawingControlOptions:{
绘图模式:[“多边形”]
},
多克隆选择:{
填充颜色:`#2196F3`,
strokeColor:`2196F3`,
填充不透明度:0.5,
冲程重量:2,
可点击:正确,
是的,
真的,
zIndex:1
}
};
类LoadScriptOnlyIfNeeded扩展LoadScript{
componentDidMount(){
常数cleaningUp=true;
const isBrowser=typeof document!=“undefined”//require(“@react google maps/api/src/utils/isBrowser”)
康斯特·伊萨尔里德=
window.google&&
window.google.maps&&
document.querySelector(“body.first-hit completed”);//AJAX页面加载系统在第一次加载应用程序时添加此类
如果(!isAlreadyLoaded&&isBrowser){
//@ts忽略
如果(window.google&!cleaningUp){
console.error(“google api已经出现”);
返回;
}
this.isCleaningUp().then(this.injectScript);
}
如果(isAlreadyLoaded){
this.setState({loaded:true});
}
}
}
导出默认函数映射({apiKey,center,path=[],point}){
const[path,setPath]=useState(路径);
常量[状态,设置状态]=使用状态({
绘图模式:“多边形”
});
常量noDraw=()=>{
设置状态(功能设置(prevState){
返回Object.assign({},prevState{
绘图模式:“制造商”
});
});
};
const onPolygonComplete=React.useCallback(
函数onPolygonComplete(poly){
常量polyArray=poly.getPath().getArray();
设路径=[];
polyArray.forEach(函数(路径){
push({lat:path.lat(),lng:path.lng()});
});
设置路径(路径);
log(“onPolygonComplete”,路径);
点(路径);
noDraw();
poly.setMap(空);
},
[要点]
);
/*const onLoad=React.useCallback(函数onLoad(map){
//控制台日志(map);
}, []);
const onDrawingManagerLoad=React.useCallback(函数onDrawingManagerLoad(
绘图经理
) {
//控制台日志(drawingManager);
},
[]);*/
//定义多边形实例和侦听器的参照
const polygonRef=useRef(null);
const listenersRef=useRef([]);
//使用新编辑的路径调用setPath
const onEdit=useCallback(()=>{
if(polygonRef.电流){
const nextPath=polygonRef.current
.getPath()
.getArray()
.map(latLng=>{
返回{lat:latLng.lat(),lng:latLng.lng()};
});
设置路径(下一个路径);
点(下一个);
}
},[setPath,point]);
//将参照绑定到当前多边形和侦听器
const onLoad=useCallback(
多边形=>{
polygonRef.current=多边形;
const path=polygon.getPath();
import React, { useState, useRef, useCallback } from "react";
import {
  LoadScript,
  GoogleMap,
  DrawingManager,
  Polygon,
  Marker
} from "@react-google-maps/api";

import "./styles.css";
const libraries = ["drawing"];

const options = {
  drawingControl: true,
  drawingControlOptions: {
    drawingModes: ["polygon"]
  },
  polygonOptions: {
    fillColor: `#2196F3`,
    strokeColor: `#2196F3`,
    fillOpacity: 0.5,
    strokeWeight: 2,
    clickable: true,
    editable: true,
    draggable: true,
    zIndex: 1
  }
};

class LoadScriptOnlyIfNeeded extends LoadScript {
  componentDidMount() {
    const cleaningUp = true;
    const isBrowser = typeof document !== "undefined"; // require('@react-google-maps/api/src/utils/isbrowser')
    const isAlreadyLoaded =
      window.google &&
      window.google.maps &&
      document.querySelector("body.first-hit-completed"); // AJAX page loading system is adding this class the first time the app is loaded
    if (!isAlreadyLoaded && isBrowser) {
      // @ts-ignore
      if (window.google && !cleaningUp) {
        console.error("google api is already presented");
        return;
      }

      this.isCleaningUp().then(this.injectScript);
    }

    if (isAlreadyLoaded) {
      this.setState({ loaded: true });
    }
  }
}

export default function Map({ apiKey, center, paths = [], point }) {
  const [path, setPath] = useState(paths);
  const [state, setState] = useState({
    drawingMode: "polygon"
  });

  const noDraw = () => {
    setState(function set(prevState) {
      return Object.assign({}, prevState, {
        drawingMode: "maker"
      });
    });
  };

  const onPolygonComplete = React.useCallback(
    function onPolygonComplete(poly) {
      const polyArray = poly.getPath().getArray();
      let paths = [];
      polyArray.forEach(function(path) {
        paths.push({ lat: path.lat(), lng: path.lng() });
      });
      setPath(paths);
      console.log("onPolygonComplete", paths);
      point(paths);
      noDraw();
      poly.setMap(null);
    },
    [point]
  );

  /*const onLoad = React.useCallback(function onLoad(map) {
    //console.log(map);
  }, []);

  const onDrawingManagerLoad = React.useCallback(function onDrawingManagerLoad(
    drawingManager
  ) {
    // console.log(drawingManager);
  },
  []);*/

  // Define refs for Polygon instance and listeners
  const polygonRef = useRef(null);
  const listenersRef = useRef([]);

  // Call setPath with new edited path
  const onEdit = useCallback(() => {
    if (polygonRef.current) {
      const nextPath = polygonRef.current
        .getPath()
        .getArray()
        .map(latLng => {
          return { lat: latLng.lat(), lng: latLng.lng() };
        });
      setPath(nextPath);
      point(nextPath);
    }
  }, [setPath, point]);

  // Bind refs to current Polygon and listeners
  const onLoad = useCallback(
    polygon => {
      polygonRef.current = polygon;
      const path = polygon.getPath();
      listenersRef.current.push(
        path.addListener("set_at", onEdit),
        path.addListener("insert_at", onEdit),
        path.addListener("remove_at", onEdit)
      );
    },
    [onEdit]
  );

  // Clean up refs
  const onUnmount = useCallback(() => {
    listenersRef.current.forEach(lis => lis.remove());
    polygonRef.current = null;
  }, []);

  console.log(path);

  return (
    <div className="App">
      <LoadScriptOnlyIfNeeded
        id="script-loader"
        googleMapsApiKey={apiKey}
        libraries={libraries}
        language="it"
        region="us"
      >
        <GoogleMap
          mapContainerClassName="App-map"
          center={center}
          zoom={10}
          version="weekly"
          //onLoad={onLoad}
        >
          {path.length === 0 ? (
            <DrawingManager
              drawingMode={state.drawingMode}
              options={options}
              onPolygonComplete={onPolygonComplete}
              //onLoad={onDrawingManagerLoad}
              editable
              draggable
              // Event used when manipulating and adding points
              onMouseUp={onEdit}
              // Event used when dragging the whole Polygon
              onDragEnd={onEdit}
            />
          ) : (
            <Polygon
              options={{
                fillColor: `#2196F3`,
                strokeColor: `#2196F3`,
                fillOpacity: 0.5,
                strokeWeight: 2
              }}
              // Make the Polygon editable / draggable
              editable
              draggable
              path={path}
              // Event used when manipulating and adding points
              onMouseUp={onEdit}
              // Event used when dragging the whole Polygon
              onDragEnd={onEdit}
              onLoad={onLoad}
              onUnmount={onUnmount}
            />
          )}
          {path.map((pos, key) => {
            return <Marker key={key} label={"" + key} position={pos} />;
          })}
        </GoogleMap>
      </LoadScriptOnlyIfNeeded>
    </div>
  );
}
removetheArray = value => {
    const { paths } = this.state;
    this.setState({
      paths: paths.splice(value, 1)
    });
  };
export default function Map({ apiKey, center, paths = [], point }) {
  const [path, setPath] = useState();
  const [state, setState] = useState({
    drawingMode: "polygon"
  });
  useEffect(() => {
    setPath(paths);
  }, [paths]);
 .
 .
 .
 onClick={() => {
                    this.setState({
                      paths: this.state.paths.filter((_, i) => i !== key)
                    });
 onClick={() => {
                   
                    const paths = this.state.paths;
                    this.setState({ 
                      paths: [...paths.slice(0,key), ...paths.slice(key+1)]})

                  }}