简体   繁体   English

Javascript 关闭与 google.maps.Geocoder::geocode

[英]Javascript Closure with google.maps.Geocoder::geocode

I'm using google.maps javascript API v3.我正在使用 google.maps javascript API v3。 I need to translate a set of civic addresses to markers on a google map with 'click' listeners.我需要将一组公民地址转换为带有“点击”侦听器的谷歌 map 上的标记。 When the user clicks on the marker in the map, I want another window to open with a url related to that address (another tab would be ideal).当用户单击 map 中的标记时,我希望另一个 window 打开与该地址相关的 url (另一个选项卡将是理想的)。

I can't manage to keep the relation between the address and the url, because I'm using javascript Closure with the google method geocode().我无法保持地址和 url 之间的关系,因为我正在使用 javascript Closure 和谷歌方法 geocode()。

I have a set of addresses such as我有一组地址,例如

var addresses = [ '123 street street', '124 street street' ];  
var urls = [ 'www.example.com/1', 'www.example.com/2' ];

Then I use the API to geocode and create markers on the map然后我使用 API 对 map 进行地理编码和创建标记

for (var i = 0; i<addresses.length; i++)
{
    var address = addresses[i];
    var url = urls[i];
    geocoder.geocode(
        { 'address' : address },
    function(result, status) {
       var x = url // url == ""

       var marker = new google.maps.Marker({
          position: result[0].geometry.location,
          map: map,
          title:"Test"
       });

       google.maps.event.addListener(marker, 'click', function(event){
          alert(url);
          window.open(url);
       },false);
    }
}

inside the anonymous function, how can I use var url ?在匿名 function 中,我该如何使用var url

It seems that the solution was to split everything in separate functions.似乎解决方案是将所有内容拆分为单独的功能。

function showAddress() {

    //geocoder = new Geocoder();

    for (var i = 0; i<addresses.length; i++)
    {
        var address = addresses[i];
        var url = urls[i];

        findAddress(address,url);
        pausecomp(400);
      }
}

function findAddress(address,url)
{
    geocoder.geocode(
        { 'address' : address },
        function(result, status) {
            var marker;
            if(status == google.maps.GeocoderStatus.OK) {
                marker = new google.maps.Marker({
                    position: result[0].geometry.location,
                    map: map,
                    title:"Longueuil"
                });

            }
            attachUrl(marker, url);
        }
    );
}

function attachUrl(marker, url)
{
    google.maps.event.addListener(marker, 'click', function(event){
        alert(url);
        window.open(url);
    },false);
}

My guess is that function calls create persistent copies of the values held by the variables and not merely pointers to them.我的猜测是 function 调用会创建变量持有的值的持久副本,而不仅仅是指向它们的指针。

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

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