You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps点击提交按钮前不显示,提交后正常,该如何修复?

解决Google Maps页面加载时不显示的问题

你的问题很清晰:当前地图实例只有在点击「Get Route」按钮后才会被创建,所以页面刚加载时#map容器是空的,自然看不到地图。我们只需要把地图初始化的逻辑提前到页面加载完成时执行,而不是等到提交按钮点击时才做。

具体修改步骤:

  • 将地图初始化的代码(创建mapObject)从calculateRoute函数中移到$(document).ready()里面,这样页面一加载就会渲染出基础地图。
  • 调整calculateRoute函数,复用已创建的mapObject,不再重新创建地图实例。
  • 可选:给重置按钮添加点击事件,清除已显示的路线,让地图回到初始状态。

修改后的完整代码:

<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> 
        // 全局声明mapObject,方便后续复用
        let mapObject;

        function calculateRoute(from, to) {
            const directionsService = new google.maps.DirectionsService();
            const 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() {
            // 页面加载完成就初始化地图
            const myOptions = {
                zoom: 10,
                center: new google.maps.LatLng(22.08672, 79.42444),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

            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();
                const addressId = this.id.substring(0, this.id.indexOf("-"));
                navigator.geolocation.getCurrentPosition(function(position) {
                    const 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());
            });

            // 给重置按钮添加事件,清除路线
            $("input[type='reset']").click(function() {
                // 清除地图上的所有路线覆盖物
                mapObject.setMap(null);
                // 重新初始化地图
                mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
                $("#error").empty();
            });
        }); 
    </script> 
    <style type="text/css"> 
        #map { 
            width: 100%; 
            height: 50vh; /* 用vh更适配不同屏幕高度 */
            margin-top: 10px;
            border: 1px solid #ccc; /* 给地图加个边框,方便识别 */
        }
    </style> 
</head> 
<body> 
    <form id="calculate-route" name="calculate-route" action="#" method="get"> 
        <table> 
            <tr> 
                <td> 
                    <label for="from"><font size="6"><b>Source :</b></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 :</b></font></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>

关键改动说明:

  1. 提前初始化地图:在$(document).ready()里直接创建地图实例,页面加载完成后就会显示基础地图(以你设置的经纬度为中心)。
  2. 复用地图实例:calculateRoute函数不再重复创建地图,而是直接使用全局的mapObject来渲染路线。
  3. 重置按钮优化:添加了重置按钮的点击事件,点击后会清除现有路线并重新初始化地图,让界面回到初始状态。
  4. 样式小调整:把地图高度改成50vh(视口高度的50%),并添加了边框,让地图在页面上更明显。

这样修改后,页面一加载就能看到地图,点击「Get Route」按钮后正常显示路线,重置按钮也能正确清除路线啦!

内容的提问来源于stack exchange,提问作者omkara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:23:15