在鼠标悬停上动态创建的谷歌地图只有第一次才能正确显示

Google maps created dynamically on mouseover show correctly only the first time

本文关键字:第一次 显示 谷歌地图 悬停 鼠标 动态 创建      更新时间:2023-09-26

我用PHP文件中的坐标创建了一个谷歌地图多段线。鼠标悬停时,它会显示一个包含地图的div。第一次用光标输入时,地图显示正确,但第二次没有绘制多段线+地图在div中较小。代码:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript">
    $(document).ready(function(event) {
        $(".testhover").on('mouseover', function(e) {
            $.ajax({
                type: "POST",
                url: 'Paten/ajaxtest',
                dataType: 'json',
                data: {routeid: this.value},
                success: function(response) {
                    var mapOptions = {
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    var map = new google.maps.Map(document.getElementById('map-canvas'),
                            mapOptions);
                    // coordinates
                    var coordinates = [];
                    for (i = 0; i < response.length; i++) {
                        var point = new google.maps.LatLng(response[i].lat, response[i].lon);
                        coordinates.push(point);
                    }

                    var Route = new google.maps.Polyline({
                        path: coordinates,
                        geodesic: true,
                        strokeColor: '#FF0000',
                        strokeOpacity: 0.7,
                        strokeWeight: 4
                    });
                    var bounds = new google.maps.LatLngBounds();    // set bounds
                    for (var i = 0; i < coordinates.length; i++) {
                        bounds.extend(coordinates[i]);
                    }
                    bounds.getCenter();
                    map.fitBounds(bounds);
                    Route.setMap(map);
                    $('#map-canvas').show();
                    $('#map-canvas').css({
                        top: (e.pageY) + "px",
                        left: (e.pageX) + "px"
                    });
                }
            })

        })
        $(".testhover").on('mouseout', function() {
            $("#map-canvas").hide();
        })
    });
</script>

html

    <style type="text/css">
    #map-canvas{
        display: none;
        position: absolute;
        width: 400px;
        height: 400px;
        padding: 10px;
        background-color: grey;
    }
</style>

<div >
    <button  id="447" value="447" class="testhover">Hover 1</button>
    <button  id="449" value="449" class="testhover">Hover 2</button>
</div>
<div id="map-canvas" ></div>

我在这里做错了什么?非常感谢。

问题已经解决。我不知道为什么,但我需要移动

                $('#map-canvas').show();
                $('#map-canvas').css({
                    top: (e.pageY) + "px",
                    left: (e.pageX) + "px"
                });

在"成功"之后的最初阶段。