谷歌地图方向服务地理位置和地址输入jquery移动

时间:2014-06-03 14:56:54

标签: jquery google-maps jquery-mobile google-maps-api-3

我整理了一个简单的jquery移动地图,该地图使用谷歌地图和路线服务。这一切都有效,除非用户输入地址(开始或目的地)而不进入城市,结果非常远。谷歌的指示将返回另一个省甚至美国的某个地区。

我认为方向将基于lat long起源,它会尝试使用本地地址地理编码?如何改善输入,以便用户只需输入地址即可获得更准确的结果?

以下是我的代码:

 $(document).on("pageinit", "#map_page", function () {
            initialize();
        });

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

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

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

        function initialize() {
            // set the default center of the map
            var mapCenter = new google.maps.LatLng(55.1669513, -118.8031093);
            // set route options (draggable means you can alter/drag the route in the map)
            var rendererOptions = { draggable: true };
            directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

            //updateMapSize(mapCenter);
            // set the display options for the map
            var myOptions = {
                mapTypeControl: false,
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: mapCenter
            }
            // add the map to the map placeholder
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            // bind the map to the directions
            directionsDisplay.setMap(map);
            // point the directions to the container for the direction details
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));         

        }

        function notFound(msg) {
            alert('Could not find your location :(')
        }

        function findCurrentPosition() {   
            // start the geolocation API
            if (navigator.geolocation) {
                // when geolocation is available on your device, run this function
                navigator.geolocation.getCurrentPosition(foundYou, notFound);
            } else {
                // when no geolocation is available, alert this message
                alert('Geolocation not supported or not enabled.');
            }
        }

        function foundYou(position) {
            // convert the position returned by the geolocation API to a google coordinate object
            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            // then try to reverse geocode the location to return a human-readable address
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    // if the geolocation was recognized and an address was found
                    if (results[0]) {
                        // add a marker to the map on the geolocated point
                        marker = new google.maps.Marker({
                            position: latlng,                   
                            map: map
                        });
                        // compose a string with the address parts
                        var address = results[0].address_components[1].long_name + ' ' + results[0].address_components[0].long_name + ', ' + results[0].address_components[3].long_name
                        // set the located address to the link, show the link and add a click event handler

                            // onclick, set the geocoded address to the start-point formfield
                            $('#from').text(address);
                            $('#from').val(address);
                            // call the calcRoute function to start calculating the route        
                    }
                } else {
                    // if the address couldn't be determined, alert and error with the status message
                    alert("Geocoder failed due to: " + status);
                }
            });
        }

        function calculateRoute() {
            var selectedtravelMode = $('#mode option:selected').val();
            // alert(selectedtravelMode);
            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[selectedtravelMode]
                };

                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        $("#results").show();                   
                    }
                    else {
                        $("#results").hide();
                    }
                });

            }
        }
    </script>
</head>
<body>
    <div data-role="page" id="map_page">
        <div data-role="header">
            <h1>Directions Map</h1>
            <a href="http://mysiteaddress/" data-ajax="false" rel="external" id="returnMobile">Home</a>
        </div>
        <div data-role="content" class="ui-content">
            <div>
                <div id="map_canvas" style="width: 100%; height: 300px"></div>
                <div data-role="my-ui-field-contain">
                    <!--<div>
            <label for="mode" class="select">Transportation method:</label>
        </div>-->
                    <div>
                        <select name="select-choice-0" id="mode">
                            <option value="TRANSIT">Public Transit</option>
                            <option value="DRIVING">Driving</option>
                            <option value="WALKING">Walking</option>
                            <option value="BICYCLING">Bicycling</option>
                        </select>
                    </div>
                </div>                
                <div data-role="my-ui-field-contain">
                    <input type="text" id="from" placeholder="From Address" value="" /><button id="getCurrentLoc" data-icon="star">Use Current Location</button>
                </div>
                <div data-role="my-ui-field-contain">
                    <input type="text" id="to" placeholder="To Destination" value="" />
                </div>
                <a data-icon="search" data-role="button" href="#" id="getDirectionsSubmit">Get directions</a>
            </div>
            <div id="results" style="display:none;">
                <div id="directionsPanel"></div>
            </div>
        </div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我现在正在使用它。我在文本输入框中添加了自动完成功能,并将输出限制在国家/地区级别,这确实有助于避免错误的开始和结束目标问题。

var options = {componentRestrictions:{country:&#39; ca&#39;}};