问题
I'm following a Google Maps v3 demo gallery example here, which is a rectangle overlay. I modified the rectangle to make it clickable.
rectangle = new google.maps.Rectangle({
map: map,
clickable: true
});
Then I added an event listener to the rectangle
google.maps.event.addListener(rectangle, 'click', editSite);
and made a method to cause the form to submit, and it worked properly.
function editSite() {
document.getElementById("siteSelection").value = 22;
document.siteSelectionForm.submit();
}
Next, I changed editSite's signature by adding an argument.
google.maps.event.addListener(rectangle, 'click', editSite(22));
...
function editSite(siteId) {
document.getElementById("siteSelection").value = siteId;
document.siteSelectionForm.submit();
}
It stopped working properly. The form would submit as soon as the map loaded, which was before I ever had the opportunity to click the rectangle. It's as though the method was invoked as soon as it was added to the listener during page reload.
My goal is to be able to create many rectangles, each rectangle, when clicked, passing a unique ID to editSite. How can I do this and avoid the problem I've created?
回答1:
This won't do what you expect (and it is missing a closing ")", is that a typo?):
google.maps.event.addListener(rectangle, 'click', editSite(22);
the "editSite" without the arguments is a function pointer (in your "working" code):
google.maps.event.addListener(rectangle, 'click', editSite);
if you add an argument, it gets executed immediately and the return value is used as the function to be executed when the event occurs (not what you want in this case). If you want to call a named function with an argument, wrap it in an anonymous function:
google.maps.event.addListener(rectangle, 'click', function() {
editSite(22);
});
来源:https://stackoverflow.com/questions/21273986/how-to-use-a-google-map-event-listener-to-pass-a-variable-and-submit-a-form