【问题标题】:Jquery variable problem in jquery mobile & google maps appjquery mobile和google maps app中的jquery变量问题
【发布时间】:2011-07-31 22:18:19
【问题描述】:

遇到 j​​avascript 问题,想知道您是否可以帮助我。我遇到的问题是变量没有被拾取,认为它可能是范围问题,但无法弄清楚。

我正在尝试使用 jquery mobile 设置基于谷歌地图的应用程序,并且一直在使用 http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt4part1 教程,但会根据我的需要进行调整。

总体计划是有一个链接列表,当您单击它们时,它们会在地图上打开不同的位置,并提供从您当前位置到新目的地的路径查找器。

所以我设置了一个函数来从 hrefs 数据身份中提取信息。

<a href="#page-map" class="destinationlink" data-role=button data-identity="53.37677497506021, -6.274824142456055" data-icon="star">Location link</a>

它引入的信息是纬度/经度坐标。然后,我将已提取的信息拆分并将信息放入 2 个变量(纬度和经度)。这部分工作正常 - 我已经提醒所有通过 latValue 和 longValue 的信息,并且在单击任一按钮时都显示正常。

$('.destinationlink').live('click', 
              function() {

                 mapID = $(this).data("identity");

                 // var mapID = '53.33970117191209, -6.24922513961792';


                //using this to split the lat/long info into 2 variables
                var LocArray = mapID.split(',');
                latValue = LocArray[0];
                longValue = LocArray[1];
                //can alert out these 2 values fine from here

               }
               );

问题出在下面一行:

  var mapdata = { destination: new google.maps.LatLng(latValue, longValue) };

纬度/经度的值似乎没有通过。我猜它是某种变量范围问题,但我不太确定,所以非常感谢任何帮助!

如果我将硬编码的详细信息放在这一行中,例如:

var mapdata = { destination: new google.maps.LatLng(53.37677497506021, -6.274824142456055) };

地图加载工作正常。

如果我放

var latValue = 53.33970117191209;
var longValue = -6.24922513961792;

直接在该行之前,它也可以正常工作。所以我知道其余的设置是正确的,就我所见,它只是变量没有通过。

但它不会从 click 函数中传递变量。曾尝试将整个事情作为一个功能,但这对我也不起作用。

有什么想法吗??

我会把完整的代码放在下面,以防我遗漏了任何重要的东西。我尝试设置一个 jsfiddle,但不适合我,对不起!

提前感谢您的帮助,非常感谢!我对 javascript 还是很陌生,所以我想如果你在任何帮助下记住这一点! :)

            var mapID;
    var latValue;
    var longValue;

     $('.destinationlink').live('click', 
                      function() {

                         mapID = $(this).data("identity");

                         // var mapID = '53.33970117191209, -6.24922513961792';


                        //using this to split the lat/long info into 2 variables
                        var LocArray = mapID.split(',');
                        latValue = LocArray[0];
                        longValue = LocArray[1];
                        //can alert out these 2 values fine from here

                       }
                       );

    // var latValue = 53.33970117191209;
    // var longValue = -6.24922513961792;

    var mapdata = { destination: new google.maps.LatLng(latValue, longValue) };


    //var mapdata = { destination: new google.maps.LatLng(53.37677497506021, -6.274824142456055) };

    // Start page
    $('#page-home').live("pagecreate", function() {                                         

        $('#map_square').gmap(
                { 'center' : mapdata.destination, 
                  'zoom' : 12, 
                  'mapTypeControl' : false, 
                  'navigationControl' : false,
                  'streetViewControl' : false, 
                  'callback' : function(map) {
                      $('#map_square').gmap('addMarker', 
                          { 'position' : map.getCenter(), 
                            'animation' : google.maps.Animation.DROP
                           });
                 }
            });
        $('#map_square').click( function() {
            $.mobile.changePage('#page-map', 'slide');
        });
    });

    //Create the fullscreen map, request display of directions
    var toggleval = true; // used for test case: static locations
    $('.refresh').live("click", function() {
        $('#map_canvas').gmap({
            'callback' : function(map) {



                    // START: Tracking location with device geolocation
        if ( navigator.geolocation ) { 
            navigator.geolocation.getCurrentPosition ( 
                function(position) {
                     $.mobile.showPageLoadingMsg();
                    $('#map_canvas').gmap('displayDirections', 
                    { 'origin' : new google.maps.LatLng(position.coords.latitude,
                                     position.coords.longitude), 
                      'destination' : mapdata.destination, 'travelMode' :
                                     google.maps.DirectionsTravelMode.DRIVING},
                    { 'panel' : document.getElementById('dir_panel')},
                         function (success, result) {
                             if (success) {
                                 $.mobile.hidePageLoadingMsg();
                                 var center = result.routes[0].bounds.getCenter();
                                 $('#map_canvas').gmap('option', 'center', center);
                                 $($('#map_canvas').gmap('getMap')).triggerEvent('resize');
                              } else {
                                alert('Unable to get route');
                              }
                          }
                     );         
                }, 
                function(){ 
                    alert('Unable to get location');
                    $.mobile.changePage('#page-home', 'slide'); 
                }); 
            }            
        // END: Tracking location with device geolocation






                // START: Tracking location with test lat/long coordinates
                // Toggle between two origins to test refresh, force new route to be calculated
               /* var position = {};
                if (toggleval) {
                    toggleval = false;
                    position = { coords: { latitude: 57.6969943, longitude: 11.9865 } };//Gothenburg
                } else {
                    toggleval = true;
                    position = { coords: { latitude: 58.5365967, longitude: 15.0373319 } };//Motala
                }
                $('#map_canvas').gmap('displayDirections', 
                    { 'origin' : new google.maps.LatLng(position.coords.latitude,
                                                        position.coords.longitude), 
                      'destination' : mapdata.destination, 
                      'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
                      { 'panel' : document.getElementById('dir_panel')},
                      function (success, result) {
                          if (success) {
                              var center = result.routes[0].bounds.getCenter();
                              $('#map_canvas').gmap('option', 'center', center);
                              $($('#map_canvas').gmap('getMap')).triggerEvent('resize');
                          } else {
                              alert('Unable to get route');
                          }
                      });*/
                // END: Tracking location with test lat/long coordinates
            }
        });
        return false;
    });

    // Map page
    $('#page-map').live("pagecreate", function() {
        $('.refresh').trigger('click');
    });

    // Go to map page to see instruction detail (zoom) on map page
    $('#dir_panel').live("click", function() {
        $.mobile.changePage('#page-map', 'slide');
    });

    // Briefly show hint on using instruction tap/zoom
    /*
    $('#page-dir').live("pageshow", function() {
        $("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"
                + "Tap any instruction" + "<br>" + "to see details on map" +"</h1></div>")
        .css({ "display": "block", "opacity": 0.9, "top": $(window).scrollTop() + 100 })
        .appendTo( $.mobile.pageContainer )
        .delay( 1400 )
        .fadeOut( 700, function(){
            $(this).remove();
       });
    });*/

还有 html..

        <!DOCTYPE HTML>
        <html>
          <head>
            <meta name="viewport" content="width=screen.width; user-scalable=no" />
            <meta http-equiv="Content-type" content="text/html; charset=utf-8">
            <title>jQuery Google Maps Plugin</title>
            <link rel="stylesheet" href="jquery.mobile-1.0b1.css" />
            <link rel="stylesheet" href="mapapp.css" type="text/css">

            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>    
            <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
            <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script> 
            <script type="text/javascript" src="jquery.mobile/jquery.ui.map.js"></script>     

            <script type="text/javascript" charset="utf-8" src="phonegap.0.9.5.js"></script>     
            <script type="text/javascript" charset="utf-8" src="mapapp.js"></script>

            </head>
          <body>
            <div data-role="page" data-theme="c" id="page-home">
            <div data-role="header" data-theme="d" data-nobackbtn="true">
            <h1>Find a pitch</h1>
            </div>

            <div data-role="content" id="contenthome">

                <div class="ui-grid-a">
                <!-- 
                This line brings in the mini map - might be useful later on for a team page 
                <div class="ui-block-a"><div id="map_square"></div></div> 
                 -->

                <div class="ui-block-b"><p><strong>Tap on the map to see route and driving directions to this location.</strong></p></div>
                </div><!-- /grid-a -->

                <div data-role="controlgroup" data-theme="a" data-type="horizontal">

                    <a href="#page-map" class="destinationlink" data-role=button data-identity="53.37677497506021, -6.274824142456055" data-icon="star">Location link</a>

                <a href="#page-map" class="destinationlink" data-role=button data-identity="53.39251677780504, -6.285123825073242" data-icon="star">Location 2</a>



                </div>
            </div><!-- /content -->

            <div data-role="footer" data-position="fixed">
                <h5>Footloose</h5>
            </div><!-- /footer -->  
            </div><!-- /page-home -->

            <div data-role="page" data-theme="c" data-fullscreen="true" id="page-map">

            <div data-role="content" class="map-content">
                <div id="map_canvas"></div>
            </div><!-- /content -->

            <div data-role="footer" data-theme="d" data-position="fixed">
            <div data-role="navbar">
            <ul>
                <li><a href="#page-home">Home</a></li>
                <li><a href="#page-map" class="refresh">Refresh</a></li>
                <li><a href="#page-dir">Directions</a></li>
            </ul>
            </div><!-- /navbar -->
            </div><!-- /footer -->
            </div><!-- /page-map -->

            <div data-role="page" data-theme="c" data-fullscreen="true" id="page-dir">

            <div data-role="content">
                <div id="dir_panel"></div>
            </div><!-- /content -->

            <div data-role="footer" data-theme="d" data-position="fixed">
            <div data-role="navbar">
                <ul>
                <li><a href="#page-home">Home</a></li>
                <li><a href="#page-map">Map</a></li>
                </ul>
            </div><!-- /navbar -->
            </div><!-- /footer -->
            </div><!-- /page-dir -->

          </body>
        </html>

编辑

好的,所以我接受了下面的建议,并将 mapdata var 和 $('#map_square').gmap(.. 放在 click 函数中,但它对我来说不起作用。位置仍然没有加载. 我一开始只放了 mapdata var,但这似乎破坏了它,页面根本没有加载。有人有什么建议吗?

感谢您的宝贵时间!

这就是我现在所拥有的(以防语法错误或其他任何事情)

         $('.destinationlink').live('click', 
                          function() {

                             mapID = $(this).data("identity");

                             // var mapID = '53.33970117191209, -6.24922513961792';


                            //using this to split the lat/long info into 2 variables
                            var LocArray = mapID.split(',');
                            latValue = LocArray[0];
                            longValue = LocArray[1];
                            //can alert out these 2 values fine from here

                           var mapdata = { destination: new google.maps.LatLng(latValue, longValue) };

                           // Start page
                            $('#page-home').live("pagecreate", function() {                                         

                                $('#map_square').gmap(
                                        { 'center' : mapdata.destination, 
                                          'zoom' : 12, 
                                          'mapTypeControl' : false, 
                                          'navigationControl' : false,
                                          'streetViewControl' : false, 
                                          'callback' : function(map) {
                                              $('#map_square').gmap('addMarker', 
                                                  { 'position' : map.getCenter(), 
                                                    'animation' : google.maps.Animation.DROP
                                                   });
                                         }
                                    });
                                $('#map_square').click( function() {
                                    $.mobile.changePage('#page-map', 'slide');
                                });
                            });

                           }
                           );

        // var latValue = 53.33970117191209;
        // var longValue = -6.24922513961792;




        //var mapdata = { destination: new google.maps.LatLng(53.37677497506021, -6.274824142456055) };



        //Create the fullscreen map, request display of directions
        var toggleval = true; // used for test case: static locations
        $('.refresh').live("click", function() {
            $('#map_canvas').gmap({
                'callback' : function(map) {



                        // START: Tracking location with device geolocation
            if ( navigator.geolocation ) { 
                navigator.geolocation.getCurrentPosition ( 
                    function(position) {
                         $.mobile.showPageLoadingMsg();
                        $('#map_canvas').gmap('displayDirections', 
                        { 'origin' : new google.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude), 
                          'destination' : mapdata.destination, 'travelMode' :
                                         google.maps.DirectionsTravelMode.DRIVING},
                        { 'panel' : document.getElementById('dir_panel')},
                             function (success, result) {
                                 if (success) {
                                     $.mobile.hidePageLoadingMsg();
                                     var center = result.routes[0].bounds.getCenter();
                                     $('#map_canvas').gmap('option', 'center', center);
                                     $($('#map_canvas').gmap('getMap')).triggerEvent('resize');
                                  } else {
                                    alert('Unable to get route');
                                  }
                              }
                         );         
                    }, 
                    function(){ 
                        alert('Unable to get location');
                        $.mobile.changePage('#page-home', 'slide'); 
                    }); 
                }            
            // END: Tracking location with device geolocation






                    // START: Tracking location with test lat/long coordinates
                    // Toggle between two origins to test refresh, force new route to be calculated
                   /* var position = {};
                    if (toggleval) {
                        toggleval = false;
                        position = { coords: { latitude: 57.6969943, longitude: 11.9865 } };//Gothenburg
                    } else {
                        toggleval = true;
                        position = { coords: { latitude: 58.5365967, longitude: 15.0373319 } };//Motala
                    }
                    $('#map_canvas').gmap('displayDirections', 
                        { 'origin' : new google.maps.LatLng(position.coords.latitude,
                                                            position.coords.longitude), 
                          'destination' : mapdata.destination, 
                          'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
                          { 'panel' : document.getElementById('dir_panel')},
                          function (success, result) {
                              if (success) {
                                  var center = result.routes[0].bounds.getCenter();
                                  $('#map_canvas').gmap('option', 'center', center);
                                  $($('#map_canvas').gmap('getMap')).triggerEvent('resize');
                              } else {
                                  alert('Unable to get route');
                              }
                          });*/
                    // END: Tracking location with test lat/long coordinates
                }
            });
            return false;
        });

        // Map page
        $('#page-map').live("pagecreate", function() {
            $('.refresh').trigger('click');
        });

        // Go to map page to see instruction detail (zoom) on map page
        $('#dir_panel').live("click", function() {
            $.mobile.changePage('#page-map', 'slide');
        });

        // Briefly show hint on using instruction tap/zoom
        /*
        $('#page-dir').live("pageshow", function() {
            $("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"
                    + "Tap any instruction" + "<br>" + "to see details on map" +"</h1></div>")
            .css({ "display": "block", "opacity": 0.9, "top": $(window).scrollTop() + 100 })
            .appendTo( $.mobile.pageContainer )
            .delay( 1400 )
            .fadeOut( 700, function(){
                $(this).remove();
           });
        });*/

【问题讨论】:

    标签: javascript jquery google-maps jquery-mobile


    【解决方案1】:

    您需要将var mapdata 放入click 函数中。该脚本不等待单击设置该 mapdata 变量,因此 latValuelongValue 为空。

    【讨论】:

    • Beat me to it +1 :) 我还将添加以将 $('#map_square').gmap( 移动到同一个点击事件中,以便保证 var 声明依赖关系。
    • 感谢您的建议,是的,我认为这将是一些类似的事情,但就是无法让它发挥作用。我已经按照建议移动了线条,但它仍然不适合我。只是为了确保我做对了...我已将 var mapdata= ... 和 map$('#map_square').gmap( .. 移到 longValue = LocArray[1]; 下面是什么你建议?这似乎对我不起作用:(
    • 如果我带上 var mapdata = { 目的地:新的 google.maps.LatLng(latValue, longValue) };在 longValue = LocArray[1] 下;该页面实际上根本没有加载..
    【解决方案2】:

    在评估您的 mapData 时,latlong 未分配(它们在 click 上分配)。改用它(假设在pagecreate 发生时,点击已被触发:

    $('#map_square').gmap(
            { 'center' : { destination: new google.maps.LatLng(latValue, longValue) }, 
                     ...
    

    【讨论】:

    • 嘿,谢谢你的帮助,我试过了,但没有运气 - 我有 - code $('#page-home').live("pagecreate", function() { $( '#map_square').gmap( { 'center' : { destination: new google.maps.LatLng(latValue, longValue) }, 'zoom' : 12, 'mapTypeControl' : false,你是这个意思吗?
    【解决方案3】:

    不应该是这样的吗?每当有人单击链接时,它将转到页面地图,每当页面地图创建它时,它都会从元素数据中访问 latlng。下一个链接不会创建地图,而是使用新的 latlng 值更新地图。

    var mapdata = { destination: new google.maps.LatLng('INITIAL_LAT', 'INITIAL_LNG') };
    $('.destinationlink').live('click', function() { 
        // get the el data
        mapdata.destination = new google.maps.LatLng(LocArray[0], LocArray[1]);
    });
    
    $('#page-map').live("pagecreate", function() {
        // setup the gmap with mapdata.destination as center
    });
    
    $('#page-map').live("pageshow", function() {
        // update the gmap center
        $('#map_square').gmap('option', 'center', mapdata.destination);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2013-05-14
      • 2012-02-09
      • 2011-11-24
      • 2014-04-13
      • 1970-01-01
      相关资源
      最近更新 更多