0

I'm creating an array of polygons in Google Maps using the loadGeoJson method. I'm making one of the polygons editable. I want to add a listener when a vertice is edited/added.

If I had used the Polygon class, I could have added the listener set_at to its path(s), according to the documentation:

The listener must be set on the polygon's path. If the polygon has multiple paths, a listener must be set on each path.

Which means that in the Polygon class it can be done like this:

let polygon = new google.maps.Polygon({ ...options here ...})
let outerPath = polygon.getPath();
google.maps.event.addListener(outerPath, 'set_at', function() {
  console.log('Vertex moved on outer path.');
});

However, when the polygons are loaded using loadGeoJson, they are considered as features in the Data layer, but the Data.Feature class does not have a getPath method. How can I add the set_at listener to a Polygon in the Data.Feature class?

The geojson that is being loaded looks like this:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Test zone"},"geometry":{"type":"Polygon","coordinates":[[[28.29,70.46],[28.34,70.45],[28.37,70.47]]]},"id":"10"}]}
aanders77
  • 620
  • 8
  • 22
  • The Geometry` of the `Feature` has a [`forEachLatLng`](https://developers.google.com/maps/documentation/javascript/reference/data#Data.Geometry) method that will get the coordinates of the particular geometry. – geocodezip Jun 18 '21 at 20:40
  • Related question (gets the coordinates of all the features in the layer creates a bounds with that, then zooms to the bounds): [Zoom On Google Maps Data Layer](https://stackoverflow.com/questions/32615267/zoom-on-google-maps-data-layer) – geocodezip Jun 18 '21 at 20:46
  • I'm already creating the bounds using the forEachLatLng(): e.feature.getGeometry().getArray().forEach(function (path) { path.getArray().forEach(function (latLng) { bounds.extend(latLng); } }) I've already tried attaching the listener to each path, but it didn't work. Are you saying that I should attach it to each latLng instead? – aanders77 Jun 18 '21 at 21:01
  • 1
    A Data.Polygon is different from a google.maps.Polygon, it has different methods to get the geographic data. There are questions here that contain examples of how to create a google.maps.Polygon from the information in the DataLayer. If you want to make them editable, and add listeners to the paths, that is probably what you will have to do. – geocodezip Jun 18 '21 at 21:22
  • Yes, you're probably right. I find it strange that it's possible to make the Data.Polygon editable, and yet there's no native method to listen for the edits. I temporarily made my Data object global in order to extract the edited geojson in the console, and that worked fine. But to do the same in my .js I would have to make the object permanently global. It's possible, but it feels hacky. I'll try converting to a google.maps.Polygon tomorrow, thanks! – aanders77 Jun 18 '21 at 21:47

0 Answers0