【问题标题】:Issue rendering Google maps on 2nd render In Dialog Box在对话框中第二次渲染时渲染 Google 地图的问题
【发布时间】:2015-07-24 22:35:50
【问题描述】:

我有一个网站,我用 ajax 构建了 90% 的 jQuery,所以我想通过单击按钮来呈现不同的地图和方向,而无需刷新页面。

如下图所示,我已经为第一次渲染做好了一切工作。

但是当我重新加载或更改为另一个时,我得到了这个:(我认为它仍在用点渲染地图。只是画布不正确)

这是我的映射代码:

window.initialize_map = function() {
    function getMiles(i) {
        return i*0.000621371192;
    }
    function toHHMMSS(i) {
        var sec_num = parseInt(i, 10); // don't forget the second param
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        time = hours+' hours '+minutes+' minutes ';
        return time;
    }

    var address, bounds, center, dest, dest_lat, dest_lng, directionsService, estimate_dest, estimate_origin, geocoder, map, mapOptions, none_location, one_location, origin, origin_lat, origin_lng, renderDirections, requestDirections, table, zoom, route, distance, distance1, duration, current, current_lng, current_lat, waypnt, estimate_current, directionsRenderer;
    table = $("#gmap");
    waypnt = [];
    dest_lng = table.attr("dest_lat");
    dest_lat = table.attr("dest_lng");
    origin_lng = table.attr("origin_lat");
    origin_lat = table.attr("origin_lng");
    dest = table.attr("dest");
    current_lng = table.attr("current_lng");
    current_lat = table.attr("current_lat");

    var current1 = table.attr("current");
    var origin1 = table.attr("origin");

    if (current1 === ''){
        origin = origin1;

    }
    else{
        origin = current1;
        var waypoint = origin1;
        estimate_current = new google.maps.LatLng(parseInt(current_lat), parseInt(current_lng));
    }
    estimate_origin = new google.maps.LatLng(parseInt(origin_lat), parseInt(origin_lng));
    estimate_dest = new google.maps.LatLng(parseInt(dest_lat), parseInt(dest_lng));
    geocoder = new google.maps.Geocoder();

    directionsService = new google.maps.DirectionsService;
    directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});


    renderDirections = function(result) {
        directionsRenderer.setMap(map);
        return directionsRenderer.setDirections(result);
    };
    var icons1 = {
        start: {
            name: 'Current Location',
            icon: '/assets/truck.png'
        },
        load: {
            name: 'Load Pickup',
            icon: '/assets/crate.png'
        },
        info: {
            name: 'Destination',
            icon: '/assets/enduser.png'
        }
    };
    var icons = {
        start: new google.maps.MarkerImage(
            // URL
            '/assets/truck.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        ),
        load: new google.maps.MarkerImage(
            // URL
            '/assets/crate.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        ),
        end: new google.maps.MarkerImage(
            // URL
            '/assets/enduser.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        )
    };
    function makeMarker( position, icon, title ) {
        new google.maps.Marker({
            position: position,
            map: map,
            icon: icon,
            title: title
        });
    }
    requestDirections = function(start, end, waypnt) {
        return directionsService.route({
            origin: start,
            destination: end,
            waypoints: waypnt,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function(result) {
            myObj = result;
            route = result.routes[0];
            distance = document.getElementById('distance');
            distance1 = document.getElementById('distance1');
            var distance2 = document.getElementById('distance2');
            duration = document.getElementById('duration');
            var total_distance = 0;
            var total_duration = 0;

            for (var i = 0; i < route.legs.length; i++) {
                if (route.legs.length > 1){
                    if (i === 0 ){
                        distance.innerHTML += ' <b>Dead Head:</b> <br>';
                        makeMarker( route.legs[i].start_location, icons.start, "Current Location" );
                    }
                    else{
                        distance.innerHTML += ' <b>Load Route:</b> <br>';
                        distance2.innerHTML = Math.round(getMiles(route.legs[i].distance.value)) + " Miles"
                        makeMarker( route.legs[i].start_location, icons.load, "Origin" );
                        makeMarker( route.legs[i].end_location, icons.end, 'Destination' );
                    }
                }
                else{
                    distance.innerHTML += ' <b>Load Route:</b> <br>';
                    distance2.innerHTML = Math.round(getMiles(route.legs[i].distance.value)) + " Miles"
                    makeMarker( route.legs[i].start_location, icons.load, "Origin" );
                    makeMarker( route.legs[i].end_location, icons.end, 'Destination' );
                }


                distance.innerHTML += route.legs[i].start_address + '* to ';
                distance.innerHTML += route.legs[i].end_address + '*<br>';
                distance.innerHTML += route.legs[i].duration.text + '<br>';
                distance.innerHTML += route.legs[i].distance.text + '<br><br>';
                total_duration += route.legs[i].duration.value;
                total_distance += route.legs[i].distance.value;
            }
            distance.innerHTML += '<small>*Based On Estimated Origin & Destination Locations</small>';
            distance1.innerHTML = Math.round(getMiles(total_distance)) + " Miles";
            duration.innerHTML = toHHMMSS(total_duration);

            return renderDirections(result);
        });
    };



    one_location = false;
    none_location = false;
    if (dest.toLowerCase() === "anywhere" && origin.toLowerCase() === "anywhere") {
        center = new google.maps.LatLng(37.2153, -93.2981);
        one_location = true;
        none_location = true;
        zoom = 4;
    } else if (dest.toLowerCase() === "anywhere") {
        center = estimate_origin;
        address = origin;
        zoom = 6;
        one_location = true;
    } else if (origin.toLowerCase() === "anywhere") {
        center = estimate_dest;
        address = dest;
        zoom = 6;
        one_location = true;
    } else {
        center = new google.maps.LatLng(34, 34);
        zoom = 6;
    }
    mapOptions = {
        center: center,
        zoom: zoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    if (one_location) {
        if (!none_location) {
            return geocoder.geocode({
                'address': address
            }, function(results, status) {
                var marker;
                return marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: 'Loadmax'
                });
            });
        }
    } else {
        bounds = new google.maps.LatLngBounds();
        if (estimate_current){
            bounds.extend(estimate_current);
        }
        bounds.extend(estimate_origin);
        bounds.extend(estimate_dest);
        map.fitBounds(bounds);
        var legend = document.getElementById('legend');
        for (var key in icons1) {
            var type = icons1[key];
            var name = type.name;
            var icon = type.icon;
            var div = document.createElement('div');
            div.innerHTML = '<img src="' + icon + '"> ' + name;
            legend.appendChild(div);
        }
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
        if (waypoint){
            waypnt.push({
                location:waypoint,
                stopover:true});
        }
        return requestDirections(origin, dest, waypnt);

    }

};

这是我的 html 视图代码:

<div class="span6" id="map_canvas" style="height:400px"></div>

我通过以下方式启动地图:

initialize_map();

顺便说一句,您在这些图片中看到的所有内容都是通过 ajax 请求生成的,该请求将使用以下命令替换该 div 中的所有内容:

$("#map_info_div").replaceWith(
        "<%= escape_javascript(render :partial => 'classic_dialogs/load_search/load_details', :locals => {:load_info => @load_info, :current1 => @current}) %>"
);

所以每次整个部分都被完全重绘并调用一个新的:

initialize_map();

更新:

我试过用这个:

google.maps.event.trigger(map_canvas,'resize');

它会将地图的其余部分归还给我,但它仍然不在应设置的边界内。

我目前在加载 html 时调用的函数中有渲染过程。

我一直在尝试从 chrome 浏览器的控制台访问地图实例,但由于地图变量在函数中,我无法访问它

如果有任何影响,此地图将显示在 JQUERY DIALOG 框中

通过使用它,就像谷歌地图画布从对话框的点 0,0 渲染一样,因为每次我使用调整大小代码时,我都必须将画布向下和向右拖动才能看到这些点...

【问题讨论】:

  • MarkerImage 类已弃用,请改用Icon
  • 不应该是google.maps.event.trigger(map_canvas,'resize');google.maps.event.trigger(map,'resize');
  • 我尝试使用 'map' 但没有用,所以当我使用 map_canvas 时,它所持有的地图的 div 的 id 起作用了

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


【解决方案1】:

我已经解决了这个问题...由于地图在一个对话框中,它正在尝试在完成加载 HTML 之前渲染地图,所以我必须在对话框上放置一个打开的功能以在之后触发它html已加载

$("#map_form").dialog({
    open: function( event, ui ) {
        initialize_map();
    },
    autoOpen: false,
    width: 1000,
    buttons: {
        "Close": function () {
            $(this).dialog("close");
        }
    }
});

希望这对其他人有所帮助

【讨论】:

    【解决方案2】:

    尝试在更新后使用它强制重绘地图。

    google.maps.event.trigger(yourMapInstance,'resize');
    

    【讨论】:

    • 这让我回到了地图的其余部分,但仍然没有居中我的边界
    • 在调整大小后重新居中地图。
    • 无法重新定位地图.... 无法从控制台访问 var 地图。可能是因为它在一个函数中...... window.initialize_map = function() {
    • map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2011-12-14
    • 2023-01-14
    • 2016-10-17
    相关资源
    最近更新 更多