简体   繁体   中英

Jquery variable problem in jquery mobile & google maps app

Having a javascript issue and was wondering if you could help me at all please. The problem I'm having is with variables not being picked up, thinking its possibly a scope issue but can't figure it out.

I'm trying to set up a google maps based app using jquery mobile and have been using http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt4part1 tutorials but adjusting to suit my needs.

The overall plan is to have a list of links which when you click on them open up different locations on a map and a trail finder from your current location to the new destination.

So I've a function set up to pull in info from a hrefs data-identity.

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

The info its pulling in is lat/long co-ordinates. Then I'm splitting that info that has been pulled in and putting the info into 2 variables (lat and long). That part works fine - I have alerted all info coming through for latValue and longValue and both display fine on click of either button.

$('.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

               }
               );

The problem is in the line underneath:

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

The values for lat/long don't seem to come through. I'm guessing its some kind of variable scoping problem but I'm not really sure so any help would be much appreciated!

If I put the hardcoded details in this line like:

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

The map load works fine.

If I put

var latValue = 53.33970117191209;
var longValue = -6.24922513961792;

directly before the line, it also works fine. So I know the rest of the setup is correct, its just the variable not coming through as far as I can see.

But it doesn't carry through variables from the click function. Have tried putting the whole thing as one function but that didn't work for me either.

Any ideas??

I'll put the full code below incase I'm leaving anything important out. I tried setting up a jsfiddle but wasn't working out for me, sorry!

Thanks in advance for any help, much appreciated! I'm still new-ish to javascript so I guess if you keep that in mind with any help please!! :)

            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();
       });
    });*/

And the 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>

EDIT

Ok so I've taken the advice from below and put the mapdata var and $('#map_square').gmap(.. inside the click function but its not working out for me. The location still doesn't load. I put just the mapdata var in there at first but that seemed to break it and the page didn't load at all. Anyone got any suggestions please?

Thanks for your time!

This is what I have now (incase syntax is wrong or anything)

         $('.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();
           });
        });*/

You need to put the var mapdata inside the click function. The script is not waiting for the click to set that mapdata variable, and therefor latValue and longValue are null.

When your mapData is evaluated, lat and long are not assigned (they get assigned on click ). Use this instead (assuming by the time pagecreate happens, click has been fired:

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

Shouldn't it be something like this? Whenever someone clicks on a link, it will go to page-map, whenever the page-map creates it access the latlng from the element data. Next link will not create a map but update the map with a new latlng value.

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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