使用函数外部的变量

时间:2013-05-13 00:33:52

标签: jquery variables

下面我使用google api获取地址的长/ lat。但经度和latitube的变量我需要在gmap中使用。正在创建map_canvas。

如何在下一个函数中使用这些变量? (其中long / lat现在用数字写入)

Jquery的:

        var geocoder = new google.maps.Geocoder();
    var address = markerInformation = $('#googleMapLocation').val();

    geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
    latitude = results[0].geometry.location.lat();
    longitude = results[0].geometry.location.lng();
    } 
    }); 
    markerInformation = $('#googleMapInformation').val();
           $(function() { 
            demo.add(function() {
                $('#map_canvas').gmap({'center': '57.7973333,12.0502107', 'zoom': 10, 'disableDefaultUI':true, 'callback': function() {
                    var self = this;
                    self.addMarker({'position': this.get('map').getCenter() }).click(function() {
                        self.openInfoWindow({ 'content': markerInformation }, this);
                    }); 
                }});
            }).load();

        }); 

3 个答案:

答案 0 :(得分:0)

你可以通过两种方式做到这一点,就是通过简单地删除变量名之前的保留字var将它们变成全局变量。

或者你可以在函数中调用函数

答案 1 :(得分:0)

由于您使用的是jQuery,因此您可以使用jQuery的data method来存储和检索任意数据。

答案 2 :(得分:0)

只需使用API​​添加标记:

  if (status == google.maps.GeocoderStatus.OK) {
      var latitude = results[0].geometry.location.lat();
      var longitude = results[0].geometry.location.lng();
      $('#map_canvas').gmap('addMarker', { position: latitude + ',' + longitude });
  }