简体   繁体   English

如何使用谷歌地图事件监听器传递变量并提交表单

[英]How to use a Google map event listener to pass a variable and submit a form

I'm following a Google Maps v3 demo gallery example here , which is a rectangle overlay.我正在关注此处的 Google Maps v3 演示库示例,它是一个矩形叠加层。 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.接下来,我通过添加一个参数更改了 editSite 的签名。

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.我的目标是能够创建许多矩形,每个矩形在单击时将唯一 ID 传递给 editSite。 How can I do this and avoid the problem I've created?我怎样才能做到这一点并避免我创造的问题?

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):没有参数的“editSite”是一个函数指针(在你的“工作”代码中):

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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