简体   繁体   中英

GOOGLE MAP API v3, Need polygon of a path

I'm using google maps v3, and my issue is that I have 200+ polygons on one map, they are all editable, and I need to make an ajax call in the event listeners for change which use path instead of the polygon to detect the changes.

so in the callback function this = polygon.getPath(), how can I get the polygon that it belongs to. In the polygon I use set to set the info I require for the ajax call.

    poly1.set('name', 'poly1');
    poly1.set('id', 1);

    google.maps.event.addListener(poly1, 'dragend', setNewArea);
    google.maps.event.addListener(poly1.getPath(), 'insert_at', setNewArea);
    google.maps.event.addListener(poly1.getPath(), 'remove_at', setNewArea);
    google.maps.event.addListener(poly1.getPath(), 'set_at', setNewArea);

so in setNewArea, I can easily check this to see if it's the poly or the path, but if it's the path I have no way to get the parent poly for it. I don't want to have 200 custom callbacks just to hardcode the poly, there has to be an other cleaner way.

One way to do this is to add the object reference to poly1 to your assigned callback. Here is some code I wrote using the maps API that adds a listener for a click event on a specific marker that opens an info window.

var latLng = new google.maps.LatLng(lat,lng);

var marker = new google.maps.Marker({
    position: latLng,
    map: window.map,
    title: pinName
});

var infoWindow = new google.maps.InfoWindow({
    content: content
});

google.maps.event.addListener(marker, 'click', function() {
    infoWindow.open(window.map, marker);
});

So for your example, you might want to do something like what's below. That will ensure that your callback function is getting a reference to the poly object, even if the triggering event is related to the path.

poly1.set('name', 'poly1');
poly1.set('id', 1);

google.maps.event.addListener(poly1, 'dragend', function() { 
    setNewArea(poly1); 
});
google.maps.event.addListener(poly1.getPath(), 'insert_at', function() { 
    setNewArea(poly1); 
});

You can make circular reference among objects.

var thePath = poly1.getPath();
thePath.parent = poly1;

google.maps.event.addListener(thePath, 'set_at', function () {
    console.log('My parent is the polygon', this.parent);
}.bind(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM