JavaScript关闭与google.maps.Geocoder :: geocode [英] Javascript Closure with google.maps.Geocoder::geocode

查看:313
本文介绍了JavaScript关闭与google.maps.Geocoder :: geocode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用google.maps JavaScript API v3。我需要将一组城市地址转换为Google地图上的标记,并使用点击监听器。当用户点击地图中的标记时,我想要使用与该地址相关的网址打开另一个窗口(另一个标签是理想的)。

I'm using google.maps javascript API v3. I need to translate a set of civic addresses to markers on a google map with 'click' listeners. 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).

t管理保持地址和url之间的关系,因为我使用javascript Closure与google方法geocode()。

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().

我有一组地址as

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

然后我使用API​​在地图上进行地理编码和创建标记

Then I use the API to geocode and create markers on the 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);
    }
}



匿名函数,如何使用 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.

这篇关于JavaScript关闭与google.maps.Geocoder :: geocode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆