⚡ GMapsBook.com is crafted by Jozef Sorocin (🟢 Book a consulting hour) and powered by:
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?
polygon.[getPath()](<https://developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getPath>)
returns an MVCArray.polygon.getPath().[getArray()](<https://developers.google.com/maps/documentation/javascript/reference/event#MVCArray.getArray>)
returns an iterable list of LatLng
objects..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}]
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}]