Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

clean example of directions with google maps in jquery mobile?

Try to get a working jquery mobile maps direction page. There is this example listed:

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

But the example code is messy and haven't been able to get it working :(. Ikea uses it.

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

but they also very customized the js so its very hard to see what happens.

Does anyone know of a good clean example or implementation that's easy to follow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Below you can find a basic example of using the Google Maps directions service in a jQuery Mobile page.

<!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:

The below example uses the current position which is automatically located and a target destination address which is given from the user.

<!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:

The below example locates the current position and it automatically calculates the distance and displays the route details between the current location and a static predefined destination location.

<!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,
                dest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...