Как включить отображение Jquery Mobile - карты Google только при нажатии кнопки

0

Я видел этот скрипт здесь, и он отлично подходит для моей потребности, я создаю мобильный сайт JQuery, и я хочу, чтобы показать карту только при нажатии кнопки

Мне трудно работать.

 var map,
            currentPosition,
            directionsDisplay, 
            directionsService,
            destinationLatitude = latt,
            destinationLongitude = lonn;

        function initializeMapAndCalculateRoute(lat, lon)
        {
            directionsDisplay = new google.maps.DirectionsRenderer(); 
            directionsService = new google.maps.DirectionsService();

            currentPosition = new google.maps.LatLng(lat, lon);

            map = new google.maps.Map(document.getElementById('map_canvas'), {
               zoom: 25,
               center: currentPosition,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });

            directionsDisplay.setMap(map);

             var currentPositionMarker = new google.maps.Marker({
                position: currentPosition,
                map: map,
                title: "Current position"
            });



            // calculate Route
            calculateRoute();
        }

        function locError(error) {
           // the current position could not be located
        }

        function locSuccess(position) {
            // initialize map with current position and calculate the route
            initializeMapAndCalculateRoute(position.coords.latitude, position.coords.longitude);
        }

        function calculateRoute() {

            var targetDestination =  new google.maps.LatLng(destinationLatitude, destinationLongitude);
            if (currentPosition != '' && targetDestination != '') {

                var request = {
                    origin: currentPosition, 
                    destination: targetDestination,
                    travelMode: google.maps.DirectionsTravelMode["DRIVING"]
                };

                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setPanel(document.getElementById("directions"));
                        directionsDisplay.setDirections(response); 

                        /*
                            var myRoute = response.routes[0].legs[0];
                            for (var i = 0; i < myRoute.steps.length; i++) {
                                alert(myRoute.steps[i].instructions);
                            }
                        */
                        $("#results").show();
                    }
                    else {
                        $("#results").hide();
                    }
                });
            }
            else {
                $("#results").hide();
            }
        }

      $(document).live("pagebeforeshow", "#detailPage", function() {
            // find current position and on success initialize map and calculate the route
            navigator.geolocation.getCurrentPosition(locSuccess, locError);
        });

Я завернул его в событие клика, и когда я ничего не нахожу, отчет консоли браузера - Uncaught TypeError: Object # map-button не имеет метода 'click'

('#map-button').click(function(){

 // Code for map goes here

 });

HTML-код

<div data-role="page" id="detailPage">
<div data-role="header">
<h1>Detail Page</h1>
</div>
<div data-role="content">
<div id="itemDetails"></div>
 <button id="map-button">Get Direction</button>
 </div>
  <div id="map_canvas" style="height:300px; width:100%"></div>

   <div id="results" style="display:none;">
     <div id="directions"></div>
   </div>

   <div data-role="footer">
    <h4>Footer</h4>
    </div>
  </div>

Я хочу, чтобы карта отображалась только после нажатия кнопки. Любая помощь будет оценена.

Теги:
jquery-mobile

1 ответ

1

Вам не хватает "$"

$('#map-button').click(function(){

// Code for map goes here

});

Это должно помочь с событием click.

Как упоминал Омар выше о текущих версиях JQuery.on используется вместо.live

$(document).on("pagebeforeshow", "#detailPage", function() {
  // find current position and on success initialize map and calculate the route
  navigator.geolocation.getCurrentPosition(locSuccess, locError);
});
  • 0
    Спасибо, я добавил знак $, а также завернул документ кода готов. Теперь, когда я нажимаю, он говорит: у Object [object Object] нет метода 'live'
  • 0
    .ready() не должен использоваться в JQM.
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню