点击提交按钮之前没有显示地图?

时间:2018-01-25 09:20:52

标签: javascript jquery html

代码:

<html>
  <head>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        function calculateRoute(from, to) {
            var myOptions = {
                zoom: 10,
                center: new google.maps.LatLng(22.08672, 79.42444),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
            var directionsService = new google.maps.DirectionsService();
            var directionsRequest = {
                origin: from,
                destination: to,
                travelMode: google.maps.DirectionsTravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC
            };
            directionsService.route(
                directionsRequest,
                function(response, status)
                {
                    if (status == google.maps.DirectionsStatus.OK)
                    {
                        new google.maps.DirectionsRenderer({
                            map: mapObject,
                            directions: response
                        });
                    }
                    else
                    $("#error").append("Unable to retrieve your route<br />");
                }
            );
        }
        $(document).ready(function() {
            if (typeof navigator.geolocation == "undefined") {
                $("#error").text("Your browser doesn't support the Geolocation API");
                return;
            }
            $("#from-link, #to-link").click(function(event) {
                event.preventDefault();
                var addressId = this.id.substring(0, this.id.indexOf("-"));
                navigator.geolocation.getCurrentPosition(function(position) {
                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({
                        "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
                    },
                    function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK)
                        $("#" + addressId).val(results[0].formatted_address);
                        else
                        $("#error").append("Unable to retrieve your address<br />");
                    });
                },
                function(positionError){
                    $("#error").append("Error: " + positionError.message + "<br />");
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10 * 1000 // 10 seconds
                });
            });
            $("#calculate-route").submit(function(event) {
                event.preventDefault();
                calculateRoute($("#from").val(), $("#to").val());
            });
        });
    </script>
    <style type="text/css">
        #map {
            width: 100%;
            height: 50%;
            margin-top: 10px;
        }
    </style>
    </head>
<body>
    <form id="calculate-route" name="calculate-route" action="#" method="get">
        <table>
            <tr>
                <td>
                    <label for="from"><font size="6"><b>Source :</font></label> 
                </td>
                <td>
                    <input type="text" id="from" name="from" required="required" placeholder="An address" size="25"/> 
                </td> 
                <td>
                    <label for="to"><font size="6"><b>Destination :</label>
                </td>
                <td>
                    <input type="text" id="to" name="to" required="required" placeholder="Another address" size="25"/>
                </td>
                <td>
                    <input type="submit" name="submit" value="Get Route"/>
                </td>
                <td>
                    <input type="reset"/>
                </td>
            </tr>
        </table>
    </form>
    <div id="map" border></div>
    <p id="error"></p>
</body>
</html>

在这段代码中,我创建了一个地图,用户输入源和目的地,通过它我们可以在获取路线按钮提交后通过地图获取路线但我的问题是点击提交按钮地图之前没有显示在提交按钮上它完美地工作。那么,我该如何解决这个问题呢?请帮帮我。

谢谢

1 个答案:

答案 0 :(得分:0)

在页面加载时,如果您希望在尝试获取路线之前查看地图,则需要初始化地图。

<html>
  <head>
    <script async defer src="//maps.google.com/maps/api/js?sensor=true&callback=initMap"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        var map;

        function initMap(){
            var options = {
                zoom: 10,
                center: new google.maps.LatLng(22.08672, 79.42444),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map( document.getElementById("map"), options );       
        }


        function calculateRoute(from, to) {


            var directionsService = new google.maps.DirectionsService();
            var directionsRequest = {
                origin: from,
                destination: to,
                travelMode: google.maps.DirectionsTravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC
            };
            directionsService.route(
                directionsRequest,
                function(response, status)
                {
                    if (status == google.maps.DirectionsStatus.OK)
                    {
                        new google.maps.DirectionsRenderer({
                            map: map,
                            directions: response
                        });
                    }
                    else
                    $("#error").append("Unable to retrieve your route<br />");
                }
            );
        }
        $(document).ready(function() {
            if (typeof navigator.geolocation == "undefined") {
                $("#error").text("Your browser doesn't support the Geolocation API");
                return;
            }
            $("#from-link, #to-link").click(function(event) {
                event.preventDefault();
                var addressId = this.id.substring(0, this.id.indexOf("-"));

                navigator.geolocation.getCurrentPosition(function(position) {
                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({
                        "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
                    },
                    function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK)
                        $("#" + addressId).val(results[0].formatted_address);
                        else
                        $("#error").append("Unable to retrieve your address<br />");
                    });
                },
                function(positionError){
                    $("#error").append("Error: " + positionError.message + "<br />");
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10 * 1000 // 10 seconds
                });
            });
            $("#calculate-route").submit(function(event) {
                event.preventDefault();
                calculateRoute($("#from").val(), $("#to").val());
            });
        });
    </script>
    <style type="text/css">
        #map {
            width: 100%;
            height: 50%;
            margin-top: 10px;
        }
    </style>
    </head>
<body>
    <form id="calculate-route" name="calculate-route" action="#" method="get">
        <table>
            <tr>
                <td>
                    <label for="from"><font size="6"><b>Source :</font></label> 
                </td>
                <td>
                    <input type="text" id="from" name="from" required="required" placeholder="An address" size="25"/> 
                </td> 
                <td>
                    <label for="to"><font size="6"><b>Destination :</label>
                </td>
                <td>
                    <input type="text" id="to" name="to" required="required" placeholder="Another address" size="25"/>
                </td>
                <td>
                    <input type="submit" name="submit" value="Get Route"/>
                </td>
                <td>
                    <input type="reset"/>
                </td>
            </tr>
        </table>
    </form>
    <div id="map"></div>
    <p id="error"></p>
</body>
</html>