Bing Maps v8 API - 缩放级别以显示路线和图钉位置

时间:2018-04-20 18:49:49

标签: javascript bing-maps

我正在使用Bing Maps v8 API。我有一张显示行车路线的地图,以及另一个地点的图钉。我需要让地图缩小以显示航点位置和图钉位置。现在,我可以让地图缩放到图钉位置的航点。

我不知道如何让两者都在地图上显示缩放。我知道我需要使用LocationRect类。

var searchManager;
var startingPoint = document.getElementById('startPoint').value;
var address = $("#addressLine").val();
var loc;
var patAddLoc;
var waypointLoc;
var pinsLocs = [];

// GET ROUTE BASED ON DIRECTION
function GetMap() {    
    var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
        //BING API KEY VIA AZURE
        credentials: 'X',
        zoom: 10,        
    });   

    // geocode patient address
    geocodeQuery(address);  

// look for patient address
function geocodeQuery(query) {
    //If search manager is not defined, load the search module.
    if (!searchManager) {
        //Create an instance of the search manager and call the geocodeQuery function again.
        Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
            searchManager = new Microsoft.Maps.Search.SearchManager(map);
            geocodeQuery(query);
        });
    } else {
    var searchRequest = {
        where: query,
        callback: function (r) {
            //Add the first result to the map and zoom into it.
            if (r && r.results && r.results.length > 0) {
                var pin = new Microsoft.Maps.Pushpin(r.results[0].location);
                // get patient address location
                patAddLoc = r.results[0].location;
                map.entities.push(pin);
                // add patient location to pushpin array
                pinsLocs.push(patAddLoc);
                // view is set with route location
                //map.setView({ bounds: r.results[0].bestView });     
            }

            // directions manager
            // addWaypoint
            Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function addWaypoint() {
                var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

                // if less than 2 point on the map
                if (directionsManager.getAllWaypoints().length < 2) {
                    directionsManager.clearAll();

                    var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('startPoint').value });
                    directionsManager.addWaypoint(startWaypoint);

                    var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('endPoint').value });
                    directionsManager.addWaypoint(endWaypoint);
                }

                // Insert a waypoint
                if (document.getElementById('wayPoints').value !== null) {
                    var addressList = JSON.parse(document.getElementById('wayPoints').value);
                    var arrayLength = addressList.length;

                    // insert waypoints from schedule
                    for (var i = 0; i < arrayLength; i++) {
                        //alert(addressList[i]);
                        var hvaddress = addressList[i];
                        var newWP = new Microsoft.Maps.Directions.Waypoint({ address: hvaddress });
                        directionsManager.addWaypoint(newWP, 1);
                    }
                }


                // Set the element in which the itinerary will be rendered - set autoupdatemapview to false to override autozoom to route
                directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('printoutPanel'), autoUpdateMapView: false });
                directionsManager.calculateDirections();

                var allWaypoints = directionsManager.getAllWaypoints();                    

                // add way point to pinsLocs array
                for (var i = 0; i < allWaypoints.length; i++) {
                    // returns nulls
                    alert(allWaypoints);
                    loc = allWaypoints[i].getLocation();
                    var showMeLoc = loc;
                    // showMeLoc = undefined.....?
                    alert(showMeLoc);                         
                    pinsLocs.push(loc);              
                }
                // only the address search location is added to the array, waypoint locations are null
                alert(pinsLocs);

                //Create a LocationRect from array of locations and set the map view.
                map.setView({
                    bounds: Microsoft.Maps.LocationRect.fromLocations(pinsLocs),
                    padding: 100 //Add a padding to buffer map to account for pushpin pixel dimensions
                });
            });
        },
        errorCallback: function (e) {
            //If there is an error, alert the user about it.
            alert("No results found.");
        }
    };
        //Make the geocode request.
        searchManager.geocode(searchRequest);
    }

}

}

更新 - 这是有相同问题的人的工作代码!

var searchManager;
var startingPoint = document.getElementById('startPoint').value;
var address = $("#addressLine").val();
var patAddLoc;


// GET ROUTE BASED ON DIRECTION
function GetMap() {    
    var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
        //BING API KEY VIA AZURE
        credentials: 'XXXXX',
        zoom: 10,        
    });   

    // geocode patient address
    geocodeQuery(address);  

    // look for patient address
    function geocodeQuery(query) {
        //If search manager is not defined, load the search module.
        if (!searchManager) {
            //Create an instance of the search manager and call the geocodeQuery function again.
            Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
                searchManager = new Microsoft.Maps.Search.SearchManager(map);
                geocodeQuery(query);
            });
        } else {
        var searchRequest = {
            where: query,
            callback: function (r) {    
                //Add the first result to the map and zoom into it.
                if (r && r.results && r.results.length > 0) {
                    locs = [];
                    var pin = new Microsoft.Maps.Pushpin(r.results[0].location);

                    // get patient address location
                    patAddLoc = r.results[0].location;
                    map.entities.push(pin);

                    // add patient location to pushpin array
                    locs.push(r.results[0].location);

                    // view is set with route location
                    //map.setView({ bounds: r.results[0].bestView });     
                }

                // directions manager
                // addWaypoint
                Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function addWaypoint() {
                    var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

                    // if less than 2 point on the map
                    if (directionsManager.getAllWaypoints().length < 2) {
                        directionsManager.clearAll();

                        var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('startPoint').value });
                        directionsManager.addWaypoint(startWaypoint);

                        var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('endPoint').value });
                        directionsManager.addWaypoint(endWaypoint);
                    }

                    // Insert a waypoint
                    if (document.getElementById('wayPoints').value !== null) {
                        var addressList = JSON.parse(document.getElementById('wayPoints').value);
                        var arrayLength = addressList.length;

                        // insert waypoints from schedule
                        for (var i = 0; i < arrayLength; i++) {
                            //alert(addressList[i]);
                            var hvaddress = addressList[i];
                            var newWP = new Microsoft.Maps.Directions.Waypoint({ address: hvaddress });
                            directionsManager.addWaypoint(newWP, 1);
                        }
                    }                    

                    // Set the element in which the itinerary will be rendered - set autoupdatemapview to false to override autozoom to route
                    directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('printoutPanel'), autoUpdateMapView: false });

                    //Add event handlers to directions manager.
                    Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', directionsError);
                    Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', directionsUpdated);

                    // Calculate directions, which displays a route on the map
                    directionsManager.calculateDirections();

                    // get route boundaries
                    function directionsUpdated(e) {
                        //Get the current route index.
                        var routeIdx = directionsManager.getRequestOptions().routeIndex;
                        // get northeast bounding box corner
                        var bBoxNE = e.routeSummary[routeIdx].northEast;
                        locs.push(bBoxNE);
                        // get southwest bounding box corner
                        var bBoxSW = e.routeSummary[routeIdx].southWest;                       
                        locs.push(bBoxSW);   


                        //SET MAP VIEW
                        //Create a LocationRect from array of locations and set the map view.
                        map.setView({
                            bounds: Microsoft.Maps.LocationRect.fromLocations(locs),
                            padding: 50 //Add a padding to buffer map to account for pushpin pixel dimensions
                        });
                    }
                    function directionsError(e) {
                        alert('Error: ' + e.message + '\r\nResponse Code: ' + e.responseCode)
                    }   

                });                
            },
            errorCallback: function (e) {
                //If there is an error, alert the user about it.
                alert("No results found.");
            }
        };

            //Make the geocode request.
            searchManager.geocode(searchRequest);
        } 
    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想要一个可以看到整个路线和额外位置的视图吗?

如何使用directionsManager.getCurrentRoute().routePath获取路线上的所有位置,然后使用LocationRect.fromLocations()(可以接收一系列位置) - 在您的情况下,上面的所有位置加上额外的位置。

请注意,calculateDirectionsgeocode是异步的,因此您可能希望处理对patAddLoc的依赖(例如,将路线代码移至地理编码回调中)。

参考:

  1. https://msdn.microsoft.com/en-us/library/mt750375.aspx
  2. https://msdn.microsoft.com/en-us/library/mt750645.aspx
  3. https://msdn.microsoft.com/en-us/library/mt712644.aspx