【问题标题】:Show direction between two points in Google Map Api with a padding使用填充显示 Google Map Api 中两点之间的方向
【发布时间】:2014-09-23 10:15:33
【问题描述】:

我想使用 google Map Api 并在两点之间绘制方向。我的地图部分被一个灰色框覆盖,其中可能会显示一些文本。当两点距离太远,一个点被灰色框覆盖时,就会出现问题。

如何强制它以整个路径显示在灰色框的右侧并且没有任何点与灰色框重叠的方式绘制路径?

我目前拥有的:

我的期望:

【问题讨论】:

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


【解决方案1】:

由于我已经在 SO 上看到了一些关于偏移出现在地图上覆盖的元素后面的东西的问题,所以我想我会给它一点时间。

我是这样做的:

  1. 在开始偏移过程之前,在地图上绘制路线并监听地图idle 事件。

  2. 检查路线边界的最左边点,看它是否落在覆盖层后面。这利用fromLatLngToPoint() 方法从纬度/经度坐标转换为地图投影上的一个点。

  3. 通过将路线的最左侧和最右侧点与地图上的可用空间进行比较,检查您可以偏移多少路线。偏移地图,直到两个点都适合地图画布。

  4. 如果两个点都无法放入地图画布中,请缩小并重新开始相同的过程。

  5. 脚本必须知道叠加层的宽度,并且您应该应用一些边距以使其始终适合。

这是用于在坐标和点之间转换的函数:

function fromLatLngToPoint(latLng) {

    var scale = Math.pow(2, map.getZoom());
    var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng());
    var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
    var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng);

    return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale));
}

这是演示:

JSFiddle demo

我确信它仍然可以优化,但它做得很好。如果您发现任何问题,请在此处报告问题。

编辑:

同样的技术也适用于标记:

JSFiddle demo

【讨论】:

    【解决方案2】:

    这是 mrUsidown 项目的重写 http://jsfiddle.net/upsidown/rat1fkkc/ 作为右侧栏的偏移代码 将下面的代码粘贴到上面链接中的 js 中并更改侧边栏的 css right:0

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var routeBounds = false;
    var overlayWidth = 400; // Width of the overlay DIV
    var leftMargin = 30; // Grace margin to avoid too close fits on the edge of the overlay
    var rightMargin = 30; // Grace margin to avoid too close fits on the right and leave space for the controls
    
    overlayWidth+= rightMargin;
    
    var start = new google.maps.LatLng(48.857380, 2.351717);
    var end = new google.maps.LatLng(50.108814, 8.672309);
    
    function initialize() {
    
        var btn1 = document.getElementById('calcRoute');
        btn1.addEventListener('click', calcRoute);
    
        var btn2 = document.getElementById('offsetMap');
        btn2.addEventListener('click', offsetMap);
    
        var btn3 = document.getElementById('fitAndOffsetMap');
        btn3.addEventListener('click', fitAndOffsetMap);
    
        var btn4 = document.getElementById('fitMap');
        btn4.addEventListener('click', fitMap);
    
        directionsDisplay = new google.maps.DirectionsRenderer({
            draggable: true
        });
    
        var mapOptions = {
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: start,
            panControlOptions: {
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            zoomControlOptions: {
                position: google.maps.ControlPosition.TOP_RIGHT
            }
        };
    
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        directionsDisplay.setMap(map);
    }
    
    function offsetMap() {
    
        if (routeBounds !== false) {
    
            // Clear listener defined in directions results
            google.maps.event.clearListeners(map, 'idle');
    
            // Top right corner
            var topRightCorner = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getNorthEast().lng());
    
            // Top right point
            var topRightPoint = fromLatLngToPoint(topRightCorner).x;
    
            // Get pixel position of leftmost and rightmost points
            var leftCoords = routeBounds.getSouthWest();
            var rightCoords = routeBounds.getNorthEast();
            
            var leftMost = fromLatLngToPoint(leftCoords).x;
            var rightMost = fromLatLngToPoint(rightCoords).x;
    
            // Calculate left and right offsets
            var leftOffset = leftMost-leftMargin;
            var rightOffset = (overlayWidth-(topRightPoint - rightMost));
            console.log(leftMost,rightMost,topRightPoint,leftOffset,rightOffset)
    
            // Only if left offset is needed
            if (rightOffset >= 0) {
    
                if (rightOffset < leftOffset) {
    var mapOffset = Math.round((leftOffset-rightOffset ) / 2);
    
                    // Pan the map by the offset calculated on the x axis
                    map.panBy(mapOffset, 0);
                    // Get the new left point after pan
         var newRightPoint = fromLatLngToPoint(rightCoords).x;
      
               console.log("e",newRightPoint,(topRightPoint-newRightPoint))
                    if ((topRightPoint-newRightPoint) <= overlayWidth) {
               console.log("jjjj")
                        // Leftmost point is still under the overlay
                        // Offset map again
                     offsetMap();
                                        }
               
                }
                else {
                console.log("j")
                    // Cannot offset map at this zoom level otherwise both leftmost and rightmost points will not fit
                    // Zoom out and offset map again
                    map.setZoom(map.getZoom() - 1);
                    offsetMap();
                }
            }
        }
    }
    
    function fromLatLngToPoint(latLng) {
    
        var scale = Math.pow(2, map.getZoom());
        var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng());
        var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
        var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng);
    
        return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale));
    }
    
    function calcRoute() {
    
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
    
        directionsService.route(request, function (response, status) {
    
            if (status == google.maps.DirectionsStatus.OK) {
    
                directionsDisplay.setDirections(response);
    
                // Define route bounds for use in offsetMap function
                routeBounds = response.routes[0].bounds;
    
                // Write directions steps
                writeDirectionsSteps(response.routes[0].legs[0].steps);
    
                // Wait for map to be idle before calling offsetMap function
                google.maps.event.addListener(map, 'idle', function () {
    
                    // Offset map
                    offsetMap();
                });
    
                // Listen for directions changes to update bounds and reapply offset
                google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
    
                    // Get the updated route directions response
                    var updatedResponse = directionsDisplay.getDirections();
    
                    // Update route bounds
                    routeBounds = updatedResponse.routes[0].bounds;
    
                    // Fit updated bounds
                    map.fitBounds(routeBounds);
    
                    // Write directions steps
                    writeDirectionsSteps(updatedResponse.routes[0].legs[0].steps);
    
                    // Offset map
                    offsetMap();
                });
            }
        });
    }
    
    function writeDirectionsSteps(steps) {
    
        var overlayContent = document.getElementById("overlayContent");
        overlayContent.innerHTML = '';
    
        for (var i = 0; i < steps.length; i++) {
    
            overlayContent.innerHTML += '<p>' + steps[i].instructions + '</p><small>' + steps[i].distance.text + '</small>';
        }
    }
    
    function fitMap() {
    
        if (routeBounds !== false) {
    
            map.fitBounds(routeBounds);
        }
    }
    
    function fitAndOffsetMap() {
    
        if (routeBounds !== false) {
    
            map.fitBounds(routeBounds);
            offsetMap();
        }
    }
    
    initialize();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2013-01-01
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多