2012-11-12 12 views
10

Cerca di ottenere una pagina di direzione delle mappe mobili di jquery funzionante. C'è questo esempio elencato:pulire l'esempio di indicazioni stradali con google maps in jquery mobile?

http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html#directions_map 

Ma il codice di esempio è disordinata e non sono stati in grado di farlo funzionare :( Ikea usa

http://m.ikea.com/nl/nl/stores/415/map/ 

ma anche molto personalizzabile.. i js quindi è molto difficile vedere cosa succede.

qualcuno sa di un buon esempio pulita o applicazione che è facile da seguire?

+1

Il mio suggerimento sarebbe quello di contattare lo sviluppatore originale (s) in quanto sta utilizzando la versione alfa jQM di 1.0 https://code.google.com/p/jquery-ui-map/source/browse/tags/2.0. 2/demo/jquery-mobile-example-3.html –

risposta

41

Di seguito puoi trovare un esempio di base sull'utilizzo del servizio di indicazioni stradali di Google Maps in una pagina jQuery Mobile.

<!DOCTYPE html> 
<html> 
    <head> 
     <title>jQuery mobile with Google maps geo directions example</title> 
     <meta content="en" http-equiv="content-language"> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> 
     <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
     <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> 
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script> 
     <script type="text/javascript"> 
      $(document).on("pageinit", "#map_page", function() { 
       initialize(); 
      }); 

      $(document).on('click', '#submit', function(e) { 
       e.preventDefault(); 
       calculateRoute(); 
      }); 

      var directionDisplay, 
       directionsService = new google.maps.DirectionsService(), 
       map; 

      function initialize() 
      { 
       directionsDisplay = new google.maps.DirectionsRenderer(); 
       var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278); 

       var myOptions = { 
        zoom:10, 
        mapTypeId: google.maps.MapTypeId.ROADMAP, 
        center: mapCenter 
       } 

       map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
       directionsDisplay.setMap(map); 
       directionsDisplay.setPanel(document.getElementById("directions")); 
      } 

      function calculateRoute() 
      { 
       var selectedMode = $("#mode").val(), 
        start = $("#from").val(), 
        end = $("#to").val(); 

       if(start == '' || end == '') 
       { 
        // cannot calculate route 
        $("#results").hide(); 
        return; 
       } 
       else 
       { 
        var request = { 
         origin:start, 
         destination:end, 
         travelMode: google.maps.DirectionsTravelMode[selectedMode] 
        }; 

        directionsService.route(request, function(response, status) { 
         if (status == google.maps.DirectionsStatus.OK) { 
          directionsDisplay.setDirections(response); 
          $("#results").show(); 
          /* 
           var myRoute = response.routes[0].legs[0]; 
           for (var i = 0; i < myRoute.steps.length; i++) { 
            alert(myRoute.steps[i].instructions); 
           } 
          */ 
         } 
         else { 
          $("#results").hide(); 
         } 
        }); 

       } 
      } 
     </script> 
    </head> 
    <body> 
     <div data-role="page" id="map_page"> 
      <div data-role="header"> 
       <h1><a href="#">jQuery mobile - Google maps directions service</h1> 
      </div> 
      <div data-role="content"> 
       <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"> 
        <div id="map_canvas" style="height:300px;"></div> 
        <div data-role="fieldcontain"> 
         <label for="from">From</label> 
         <input type="text" id="from" value="Goteborg, Sweden"/> 
        </div> 
        <div data-role="fieldcontain"> 
         <label for="to">To</label> 
         <input type="text" id="to" value="Stockholm, Sweden"/> 
        </div> 
        <div data-role="fieldcontain"> 
         <label for="mode" class="select">Transportation method:</label> 
         <select name="select-choice-0" id="mode"> 
          <option value="DRIVING">Driving</option> 
          <option value="WALKING">Walking</option> 
          <option value="BICYCLING">Bicycling</option> 
         </select> 
        </div> 
        <a data-icon="search" data-role="button" href="#" id="submit">Get directions</a> 
       </div> 
       <div id="results" style="display:none;"> 
        <div id="directions"></div> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

enter image description here

UPDATE 1:

Il sotto esempio impiega la posizione attuale che si trova automaticamente e un indirizzo di destinazione di destinazione che è dato dall'utente.

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>jQuery mobile with Google maps</title> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> 
     <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
     <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> 
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script> 
     <script type="text/javascript"> 

      var map, 
       currentPosition, 
       directionsDisplay, 
       directionsService; 

      function initialize(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: 15, 
        center: currentPosition, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }); 

       directionsDisplay.setMap(map); 

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

       var infowindow = new google.maps.InfoWindow(); 
       google.maps.event.addListener(currentPositionMarker, 'click', function() { 
        infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon); 
        infowindow.open(map, currentPositionMarker); 
       }); 
      } 

      function locError(error) { 
       // initialize map with a static predefined latitude, longitude 
       initialize(59.3426606750, 18.0736160278); 
      } 

      function locSuccess(position) { 
       initialize(position.coords.latitude, position.coords.longitude); 
      } 

      function calculateRoute() { 
       var targetDestination = $("#target-dest").val(); 
       if (currentPosition && currentPosition != '' && targetDestination && 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", "#map_page", function() { 
       navigator.geolocation.getCurrentPosition(locSuccess, locError); 
      }); 

      $(document).on('click', '#directions-button', function(e){ 
       e.preventDefault(); 
       calculateRoute(); 
      }); 

     </script> 
    </head> 
    <body> 
     <div id="basic-map" data-role="page"> 
      <div data-role="header"> 
       <h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a></h1> 
      </div> 
      <div data-role="content"> 
       <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"> 
        <div id="map_canvas" style="height:350px;"></div> 
       </div> 
       <div data-role="fieldcontain"> 
        <label for="target-dest">Target Destination:</label> 
        <input type="text" name="target-dest" id="target-dest" value="" /> 
       </div> 
       <a href="#" id="directions-button" data-role="button" data-inline="true" data-mini="true">Get Directions</a> 
       <div id="results" style="display:none;"> 
        <div id="directions"></div> 
       </div> 
      </div> 
     </div>  
    </body> 
</html> 

UPDATE 2:

Il sotto esempio localizza la posizione corrente e calcola automaticamente la distanza e visualizza i dettagli del percorso tra la posizione corrente e una posizione di destinazione predefinita statico.

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>jQuery mobile with Google maps</title> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> 
     <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
     <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> 
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script> 
     <script type="text/javascript"> 

      var map, 
       currentPosition, 
       directionsDisplay, 
       directionsService, 
       destinationLatitude = 59.3426606750, 
       destinationLongitude = 18.0736160278; 

      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: 15, 
        center: currentPosition, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }); 

       directionsDisplay.setMap(map); 

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

       // current position marker info 
       /* 
       var infowindow = new google.maps.InfoWindow(); 
       google.maps.event.addListener(currentPositionMarker, 'click', function() { 
        infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon); 
        infowindow.open(map, currentPositionMarker); 
       }); 
       */ 

       // 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", "#map_page", function() { 
       // find current position and on success initialize map and calculate the route 
       navigator.geolocation.getCurrentPosition(locSuccess, locError); 
      }); 

     </script> 
    </head> 
    <body> 
     <div id="basic-map" data-role="page"> 
      <div data-role="header"> 
       <h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a></h1> 
      </div> 
      <div data-role="content"> 
       <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"> 
        <div id="map_canvas" style="height:350px;"></div> 
       </div> 
       <div id="results" style="display:none;"> 
        <div id="directions"></div> 
       </div> 
      </div> 
     </div>  
    </body> 
</html> 

Spero che questo aiuti.

+0

Grazie questo è un esempio più pulito di quelli forniti sul sito thx. Ma il problema è che questo non ha ancora indicazioni ** basate sulla posizione corrente (gps su iphone per esempio), quindi non posso contrassegnarlo come risposta corretta. Provo a costruire sul tuo esempio e ad aggiungere il materiale geografico – Rubytastic

+0

Vuoi controllare la mia risposta aggiornata. Ho aggiunto un esempio che utilizza la posizione corrente. –

+0

grazie mille, è davvero complicato, ma le mappe di google possono essere complicate per funzionare. Solo 1 ultimo problema che ho, vorrei avere le indicazioni calcolate * dopo * l'utente dà la sua posizione. Sapresti come fare anche questo? Ho rimosso il campo e il pulsante di input delle direzioni e ho impostato il valore di destinazione codificato in js. Il passo finale sarebbe quello di calcolare le direzioni dopo che l'utente ha assegnato la sua posizione corrente. – Rubytastic

Problemi correlati