堆js创建多个对象数组声明

时间:2021-05-03 15:52:01

Below is my coding when I am trying to get the coordinates of the polygon from react-google-maps:

下面是我的编码,当我试图从反应谷歌地图得到多边形的坐标时:

const coords = { lat:{}, lng:{} }

 getCoordinates: () => (polygon) => {
  const paths = polygon.getPath()
  const coor = paths.b

  {coor.map(function(coor, i){
    coords.lat= coor.lat()
    coords.lng= coor.lng()
  })}
  return console.log(coords)
}

I'm trying to get the object array for "coords"like below:

我正在尝试获取对象数组作为“coords”,如下所示:

coords = [
  { lat: 3.1323583333745533, lng: 101.62676453590393 },
  { lat: 3.1318226928949433, lng: 101.62672162055969 },
  { lat: 3.131753059612469, lng: 101.6274243593216 }
]

But using the code will give me this:

但使用这些代码会让我明白:

coords = { 
  lat: 3.131753059612469, 
  lng: 101.6274243593216 
}

which is the last coordinates out of the three.

这是这三个中的最后一个坐标。

How do I can get all three coordinates under "coords"?

如何在coords下得到这三个坐标?

2 个解决方案

#1


2  

You have to push to an array instead of object, hope it helps!

你必须推到一个数组而不是对象,希望它能有所帮助!

let coords = [];

getCoordinates: () => (polygon) => {
    const paths = polygon.getPath();
    const coor  = paths.b;

    coor.forEach((c) => {
        coords.push({
            lat: c.lat(),
            lng: c.lng()
        });
    });

    return console.log(coords);
}

#2


2  

This code is really confused. You seem to be looking for

这段代码非常混乱。你似乎在寻找

function getCoordinates(polygon) {
  const paths = polygon.getPath()
  const coords = paths.b.map(coor => ({
    lat: coor.lat(),
    lng: coor.lng()
  }));
  return coords;
}

console.log(getCoordinates(…));

#1


2  

You have to push to an array instead of object, hope it helps!

你必须推到一个数组而不是对象,希望它能有所帮助!

let coords = [];

getCoordinates: () => (polygon) => {
    const paths = polygon.getPath();
    const coor  = paths.b;

    coor.forEach((c) => {
        coords.push({
            lat: c.lat(),
            lng: c.lng()
        });
    });

    return console.log(coords);
}

#2


2  

This code is really confused. You seem to be looking for

这段代码非常混乱。你似乎在寻找

function getCoordinates(polygon) {
  const paths = polygon.getPath()
  const coords = paths.b.map(coor => ({
    lat: coor.lat(),
    lng: coor.lng()
  }));
  return coords;
}

console.log(getCoordinates(…));