在 jquery mobile 中使用谷歌地图的清晰方向示例? [英] clean example of directions with google maps in jquery mobile?

查看:25
本文介绍了在 jquery mobile 中使用谷歌地图的清晰方向示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试获得一个有效的 jquery 移动地图方向页面.列出了这个例子:

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

但是示例代码很乱,无法运行:(.宜家使用它.

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

但他们也非常定制了 js,所以很难看出会发生什么.

有谁知道一个很好的简洁示例或易于遵循的实现?

解决方案

您可以在下面找到在 jQuery Mobile 页面中使用 Google 地图路线服务的基本示例.

<头><title>带有 Google 地图地理方向示例的 jQuery mobile</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() {初始化();});$(document).on('click', '#submit', function(e) {e.preventDefault();计算路线();});var方向显示,路线服务 = 新的 google.maps.DirectionsService(),地图;函数初始化(){方向显示 = 新 google.maps.DirectionsRenderer();var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278);var myOptions = {缩放:10,mapTypeId: google.maps.MapTypeId.ROADMAP,中心:地图中心}map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);DirectionsDisplay.setMap(地图);DirectionsDisplay.setPanel(document.getElementById("directions"));}函数计算路由(){var selectedMode = $("#mode").val(),start = $("#from").val(),end = $("#to").val();如果(开始 == '' || 结束 == ''){//无法计算路线$("#results").hide();返回;}别的{无功请求 = {起源:开始,目的地:结束,travelMode: google.maps.DirectionsTravelMode[selectedMode]};路线Service.route(请求,功能(响应,状态){如果(状态 == google.maps.DirectionsStatus.OK){DirectionsDisplay.setDirections(响应);$("#results").show();/*var myRoute = response.routes[0].legs[0];for (var i = 0; i < myRoute.steps.length; i++) {警报(myRoute.steps[i].instructions);}*/}别的 {$("#results").hide();}});}}<身体><div data-role="page" id="map_page"><div data-role="header"><h1><a href="#">jQuery mobile - Google 地图路线服务</h1>

<div data-role="内容"><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="瑞典哥德堡"/>

<div data-role="fieldcontain"><label for="to">To</label><input type="text" id="to" value="瑞典斯德哥尔摩"/>

<div data-role="fieldcontain"><label for="mode" class="select">运输方式:</label><select name="select-choice-0" id="mode"><option value="驾驶">驾驶</option><option value="WALKING">Walking</option><option value="BICYCLING">骑自行车</option></选择>

<a data-icon="search" data-role="button" href="#" id="submit">获取路线</a>

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

更新 1:

以下示例使用自动定位的当前位置和用户提供的目标目的地地址.

<html lang="zh-cn"><头><title>带有谷歌地图的jQuery mobile</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">无功地图,当前位置,方向显示,方向服务;函数初始化(纬度,经度){方向显示 = 新 google.maps.DirectionsRenderer();路线服务 = 新的 google.maps.DirectionsService();currentPosition = new google.maps.LatLng(lat, lon);map = new google.maps.Map(document.getElementById('map_canvas'), {变焦:15,中心:当前位置,mapTypeId: google.maps.MapTypeId.ROADMAP});DirectionsDisplay.setMap(地图);var currentPositionMarker = new google.maps.Marker({位置:当前位置,地图:地图,标题:当前位置"});var infowindow = new google.maps.InfoWindow();google.maps.event.addListener(currentPositionMarker, 'click', function() {infowindow.setContent("当前位置:纬度:" + lat +" 经度:" + lon);infowindow.open(map, currentPositionMarker);});}函数locError(错误){//使用静态预定义纬度、经度初始化地图初始化(59.3426606750,18.0736160278);}功能locSuccess(位置){初始化(position.coords.latitude,position.coords.longitude);}函数计算路由(){var targetDestination = $("#target-dest").val();if (currentPosition && currentPosition != '' && targetDestination && targetDestination != '') {无功请求 = {原点:当前位置,目的地:目标目的地,travelMode: google.maps.DirectionsTravelMode["DRIVING"]};路线Service.route(请求,功能(响应,状态){如果(状态 == google.maps.DirectionsStatus.OK){DirectionsDisplay.setPanel(document.getElementById("directions"));DirectionsDisplay.setDirections(响应);/*var myRoute = response.routes[0].legs[0];for (var i = 0; i < myRoute.steps.length; i++) {警报(myRoute.steps[i].instructions);}*/$("#results").show();}别的 {$("#results").hide();}});}别的 {$("#results").hide();}}$(document).live("pagebeforeshow", "#map_page", function() {navigator.geolocation.getCurrentPosition(locSuccess, locError);});$(document).on('click', '#directions-button', function(e){e.preventDefault();计算路线();});<身体><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 data-role="内容"><div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"><div id="map_canvas" style="height:350px;"></div>

<div data-role="fieldcontain"><label for="target-dest">目标目的地:</label><input type="text" name="target-dest" id="target-dest" value=""/>

<a href="#" id="directions-button" data-role="button" data-inline="true" data-mini="true">获取路线</a><div id="results" style="display:none;"><div id="方向"></div>

更新 2:

以下示例定位当前位置并自动计算距离并显示当前位置与静态预定义目的地位置之间的路线详细信息.

<html lang="zh-cn"><头><title>带有谷歌地图的jQuery mobile</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">无功地图,当前位置,方向显示,方向服务,目的地纬度 = 59.3426606750,目的地经度 = 18.0736160278;函数 initializeMapAndCalculateRoute(lat, lon){方向显示 = 新 google.maps.DirectionsRenderer();路线服务 = 新的 google.maps.DirectionsService();currentPosition = new google.maps.LatLng(lat, lon);map = new google.maps.Map(document.getElementById('map_canvas'), {变焦:15,中心:当前位置,mapTypeId: google.maps.MapTypeId.ROADMAP});DirectionsDisplay.setMap(地图);var currentPositionMarker = new google.maps.Marker({位置:当前位置,地图:地图,标题:当前位置"});//当前位置标记信息/*var infowindow = new google.maps.InfoWindow();google.maps.event.addListener(currentPositionMarker, 'click', function() {infowindow.setContent("当前位置:纬度:" + lat +" 经度:" + lon);infowindow.open(map, currentPositionMarker);});*///计算路线计算路线();}函数locError(错误){//无法定位当前位置}功能locSuccess(位置){//用当前位置初始化地图并计算路线initializeMapAndCalculateRoute(position.coords.latitude, position.coords.longitude);}函数计算路由(){var targetDestination = new google.maps.LatLng(destinationLatitude, destinationLongitude);if (currentPosition != '' && targetDestination != '') {无功请求 = {原点:当前位置,目的地:目标目的地,travelMode: google.maps.DirectionsTravelMode["DRIVING"]};路线Service.route(请求,功能(响应,状态){如果(状态 == google.maps.DirectionsStatus.OK){DirectionsDisplay.setPanel(document.getElementById("directions"));DirectionsDisplay.setDirections(响应);/*var myRoute = response.routes[0].legs[0];for (var i = 0; i < myRoute.steps.length; i++) {警报(myRoute.steps[i].instructions);}*/$("#results").show();}别的 {$("#results").hide();}});}别的 {$("#results").hide();}}$(document).live("pagebeforeshow", "#map_page", function() {//找到当前位置并成功初始化地图并计算路线navigator.geolocation.getCurrentPosition(locSuccess, locError);});<身体><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 data-role="内容"><div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"><div id="map_canvas" style="height:350px;"></div>

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

我希望这会有所帮助.

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?

解决方案

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>

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

I hope this helps.

这篇关于在 jquery mobile 中使用谷歌地图的清晰方向示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆