🏡 Home 👈 Prev 👉 Next

⚡  GMapsBook.com is crafted by Jozef Sorocin (🟢 Book a consulting hour) and powered by:

Extracting Coordinates

Obtaining coordinates from markers is quite straightforward — analogously to map.getCenter(), you’d call marker.[getPosition()](<https://developers.google.com/maps/documentation/javascript/reference/marker#Marker.getPosition>). Since that’d return a LatLng object instance, you’d need to chain .toJSON() to arrive at the familiar lat,lng coordinate pair:

const position = {lat: 40.7419, lng: -73.9921};
const marker = new google.maps.Marker({
  map,
  position,
});

const extractedPosition = marker.getPosition().getCenter();
// returns {lat: 40.7419, lng: -73.9921}

Equally straightforward is obtaining a circle's center — you’d need circle.getCenter().toJSON().

But what about more complicated shapes like polylines and markers? How do you obtain their coordinates?

Getting latitude & longitude of lines & polygons

Polylines

  1. A polyline’s coordinates form a path.
  2. Calling polygon.[getPath()](<https://developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getPath>) returns an MVCArray.
  3. Calling polygon.getPath().[getArray()](<https://developers.google.com/maps/documentation/javascript/reference/event#MVCArray.getArray>) returns an iterable list of LatLng objects.
  4. Finally, calling .toJSON() on each object individually produces a familiar list of coordinates.
const nycToLaFlightCoords = [
  { lat: 40.7419, lng: -73.9921 },
  { lat: 37.772, lng: -122.214 },
];

const flightPolyline = new google.maps.Polyline({
  map,
  path: nycToLaFlightCoords,
  geodesic: true,
});

const coords = flightPolyline.getPath()
											       .getArray()
											       .map((latLng) => latLng.toJSON())
// returns [{"lat":40.7419,"lng":-73.9921},{"lat":37.772,"lng":-122.214}]

Polygons

A polygon’s coordinates form a closed loop. Similarly to polylines, you’ll need to call .getPath() and .getArray() on the polygon object:

const polygonCoords = [
  { lat: 40.7419, lng: -73.9921 },
  { lat: 37.772, lng: -122.214 },
  { lat: 32.321, lng: -64.757 },
	{ lat: 40.7419, lng: -73.9921 }
];

const polygon = new google.maps.Polygon({
  map,
  paths: polygonCoords
});

const coords = polygon.getPath()
									    .getArray()
									    .map((latLng) => latLng.toJSON())
// returns [{"lat":40.7419,"lng":-73.9921},{"lat":37.772,"lng":-122.214},{"lat":32.321,"lng":-64.757},{"lat":40.7419,"lng":-73.9921}]