2

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 = [
  { 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"?

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Don't use map together with push. If you want to push to an array explicitly, use a normal for (let c of coor) loop instead
Sorry for using the wrong method, I am just modifying the code without checking the function used, updated the code to forEach instead
Thanks, better, though I still dislike the forEach + push combination when one could just use map :-P
Got it, I am overusing forEach recently so can't think of using map, will try to use more map and filter etc in the future =)
I recommend to never use forEach. For side effects (i.e. when you don't need a result value), use for … of. This also allows to use things like yield, await, return, break and continue in the loop body.
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(…));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.