开发者

How do I access global variables that are set inside an event listener?

I am working with Google maps api V3. I need to get the values of the getSouthWest & getNorthEast bounds of my map. To do this the 'bounds_changed' event needs to be fired in order to get the new values. This is all good, however, I need to access these values from outside the event 开发者_开发技巧and passed to a server side function (more specifically, I don't want to call my server side function every time the map bounds are changed).

My code is:

//Global
var sw, nw, Searchbounds;

function myFunc(){

google.maps.event.addListener(map, 'bounds_changed', function() {
        Searchbounds = map.getBounds();
        sw = Searchbounds.getSouthWest();
        ne = Searchbounds.getNorthEast();

    });

    CallServerSideWebService(sw.lat(), ne.lng(), ne.lat(), ne.lng());
}

When executing this code I get the error message sw is undefined.

If anyone knows how I can get around this issue with the current method; or access the getBounds() function without the use of an event, then I would be very grateful!


This looks like a timing issue to me, not a scoping issue.

  1. Your function fires and adds the handler
  2. Then it tries to access sw which is undefined (as it was when it was declared)
  3. Then the event might fire and set sw.

I suppose it is possible that the API is changing a single object reference and you are holding on to that, but it seems unlikely. If that IS the case, try storing the lat and lng values instead of nw and sw since they are number primitives.

You must, though, have access to map outside of the event. It looks as simple as:

function myFunc() {
  var searchBounds = map.getBounds();
  var sw = searchBounds.getSouthWest();
  var ne = searchBounds.getNorthEast();

  CallServerSideWebService(sw.lat(), ne.lng(), ne.lat(), ne.lng());
}


I'm assuming you're actually defining the variables? They're commented out in your code...

assuming they are being defined correctly, it's possible they're not of the type you expected - eg sw may be present and populated ut may not have a lat() property - perhaps latitude()?

Try examining the sw object in a debugger after the bounds change (the firebug addon in firefox is very good for this)

Edit as your code ahs been changed:

You're calling the server-side function before the bounds changed function has been called...

Try this:

var sw, nw, Searchbounds;

function myFunc(){

google.maps.event.addListener(map, 'bounds_changed', function() {
        Searchbounds = map.getBounds();
        sw = Searchbounds.getSouthWest();
        ne = Searchbounds.getNorthEast();

        //Moved inside the event handler
        CallServerSideWebService(sw.lat(), ne.lng(), ne.lat(), ne.lng());

    });

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜