Azure образец карты имеет только 2 остановки, хочу добавить третью - PullRequest
0 голосов
/ 18 марта 2020

образец работает только с двумя адресами, но я бы хотел добавить больше. Я получил текстовые поля для ввода адресов, но не вижу, как добавить остановку в середине.

Маршрут идет от начала до конца. Начните работу с fromCoord и завершите toCoord. Что должно произойти, если будет добавлена ​​еще одна остановка? То, что у меня есть ниже, показывает весь маршрут от начала до конца, но мне также нужен значок для обозначения остановки в середине маршрута. И предоставить возможность добавления дополнительных остановок.

<script type='text/javascript'>
    var map, datasource, routePoints = [], currentScenario;

    var coordinateRx = /^-?[0-9]+\.?[0-9]*\s*,+\s*-?[0-9]+\.?[0-9]*$/;
    var geocodeRequestUrl = 'https://atlas.microsoft.com/search/address/json?subscription-key={subscription-key}&api-version=1&query={query}&view=Auto';
    var carRoutingRequestUrl = 'https://atlas.microsoft.com/route/directions/json?subscription-key={subscription-key}&api-version=1&query={query}&routeRepresentation=polyline&travelMode=car&view=Auto';
    var truckRoutingRequestUrl = 'https://atlas.microsoft.com/route/directions/json?subscription-key={subscription-key}&api-version=1&query={query}&routeRepresentation=polyline&vehicleLength={vehicleLength}&vehicleHeight={vehicleHeight}&vehicleWidth={vehicleWidth}&vehicleWeight={vehicleWeight}&travelMode=truck&view=Auto';

    function GetMap() {
        //Initialize a map instance.
        map = new atlas.Map('myMap', {
            view: 'Auto',

            //Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
            authOptions: {
                authType: 'subscriptionKey',
                subscriptionKey: 'key'
            }
        });

        //Wait until the map resources are ready.
        map.events.add('ready', function () {
            //Create a data source to store the data in.
            datasource = new atlas.source.DataSource();
            map.sources.add(datasource);

            //Add a layer for rendering line data.
            map.layers.add(new atlas.layer.LineLayer(datasource, null, {
                strokeColor: ['get', 'strokeColor'],
                strokeWidth: 5
            }), 'labels');

            //Add a layer for rendering point data.
            map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
                iconOptions: {
                    image: ['get', 'icon']
                },
                textOptions: {
                    textField: ['get', 'title'],
                    size: 14,
                    font: ['SegoeUi-Bold'],
                    offset: [0, 1.2]
                },
                filter: ['any', ['==', ['geometry-type'], 'Point'], ['==', ['geometry-type'], 'MultiPoint']] //Only render Point or MultiPoints in this layer.
            }));

            //Load scenarios
            var scenarioHtml = [];

            for (var i = 0; i < scenarios.length; i++) {
                scenarioHtml.push('<input type="button" value="', scenarios[i].description, '" onclick="loadScenario(', i, ')" /> ');
            }

            document.getElementById('scenarios').innerHTML = scenarioHtml.join('');
        });
    }

    function calculateDirections() {
        routePoints = [];
        document.getElementById('output').innerHTML = '';
        datasource.clear();

        var from = document.getElementById('fromTbx').value;

        geocodeQuery(from, function (fromCoord) {
            var to = document.getElementById('toTbx01').value + ',' + document.getElementById('toTbx02').value;

            geocodeQuery(to, function (toCoord) {

                //Create pins for the start and end of the route.
                var startPoint = new atlas.data.Point(fromCoord);
                var startPin = new atlas.data.Feature(startPoint, {
                    title: 'Stop00',
                    icon: 'pin-round-blue'
                });

                var stop01Point = new atlas.data.Point(toCoord);
                var stop01Pin = new atlas.data.Feature(stop01Point, {
                    title: 'Stop01',
                    icon: 'pin-round-red'
                });

                var stop02Point = new atlas.data.Point(toCoord);
                var stop02Pin = new atlas.data.Feature(stop02Point, {
                    title: 'Stop02',
                    icon: 'pin-round-red'
                });                 

                //Fit the map window to the bounding box defined by the start and end points.
                map.setCamera({
                    bounds: atlas.data.BoundingBox.fromData([toCoord, fromCoord]),
                    padding: 50
                });

                //Add pins to the map for the start and end point of the route.
                datasource.add([startPin, stop01Pin, stop02Pin]);

                //Convert lon,lat into lat,lon.
                fromCoord.reverse();
                toCoord.reverse()

                var query = fromCoord.join(',') + ':' + toCoord.join(',');

                var carRequestUrl = carRoutingRequestUrl.replace('{subscription-key}', atlas.getSubscriptionKey()).replace('{query}', query);

                callRestService(carRequestUrl, function (r) {
                    addRouteToMap(r.routes[0], 'red');
                    document.getElementById('output').innerHTML += 'Car Distance: ' + Math.round(r.routes[0].summary.lengthInMeters / 10) / 100 + ' km<br/>';
                });

                var truckRequestUrl = truckRoutingRequestUrl.replace('{subscription-key}', atlas.getSubscriptionKey()).replace('{query}', query);

                var loadType = getSelectValues('vehicleLoadType');
                if (loadType && loadType !== '') {
                    truckRequestUrl += '&vehicleLoadType=' + loadType;
                }

                truckRequestUrl = setValueOptions(truckRequestUrl, ['vehicleWeight', 'vehicleWidth', 'vehicleHeight', 'vehicleLength']);

                callRestService(truckRequestUrl, function (r) {
                    addRouteToMap(r.routes[0], 'green');
                    document.getElementById('output').innerHTML += 'Truck Distance: ' + Math.round(r.routes[0].summary.lengthInMeters / 10) / 100 + ' km<br/>';
                });
            });
        });
    }

    //Geocode the query and return the first coordinate.
    function geocodeQuery(query, callback) {
        if (callback) {
            //Check to see if the query is a coordinate. if so, it doesn't need to be geocoded.
            if (coordinateRx.test(query)) {
                var vals = query.split(',');

                callback([parseFloat(vals[1]), parseFloat(vals[0])]);
            } else {
                var requestUrl = geocodeRequestUrl.replace('{subscription-key}', atlas.getSubscriptionKey()).replace('{query}', encodeURIComponent(query));

                callRestService(requestUrl, function (r) {
                    if (r && r.results && r.results.length > 0) {
                        callback([r.results[0].position.lon, r.results[0].position.lat]);
                    }
                });
            }
        }
    }

    function addRouteToMap(route, strokeColor) {
        var routeCoordinates = [];

        for (var legIndex = 0; legIndex < route.legs.length; legIndex++) {
            var leg = route.legs[legIndex];

            //Convert the route point data into a format that the map control understands.
            var legCoordinates = leg.points.map(function (point) {
                return [point.longitude, point.latitude];
            });

            //Combine the route point data for each route leg together to form a single path.
            routeCoordinates = routeCoordinates.concat(legCoordinates);
        }

        //Create a LineString from the route path points and add it to the line layer.
        datasource.add(new atlas.data.Feature(new atlas.data.LineString(routeCoordinates), {
            strokeColor: strokeColor
        }));

        //Fit the map window to the bounding box defined by the route points.
        routePoints = routePoints.concat(routeCoordinates);
        map.setCamera({
            bounds: atlas.data.BoundingBox.fromPositions(routePoints),
            padding: 50
        });
    }

    function callRestService(requestUrl, callback, errorCallback) {
        if (callback) {
            var xhttp = new XMLHttpRequest();
            xhttp.open('GET', requestUrl, true);
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        var response = JSON.parse(xhttp.responseText);
                        callback(response);
                    } else if (errorCallback) {
                        if (errorCallback) {
                            errorCallback(JSON.parse(xhttp.responseText));
                        }
                    }
                }
            };
            xhttp.send();
        }
    }

    // Return a set of the selected opion value for a multi-select as a comma delimited string.
    function getSelectValues(id) {
        var select = document.getElementById(id);
        var selected = [];

        for (var i = 0; i < select.length; i++) {
            if (select.options[i].selected) {
                selected.push(select.options[i].value);
            }
        }

        return selected.join(',');
    }

    function setValueOptions(requestUrl, valueOptions) {
        for (var i = 0; i < valueOptions.length; i++) {
            requestUrl = requestUrl.replace('{' + valueOptions[i] + '}', document.getElementById(valueOptions[i]).value);
        }

        return requestUrl;
    }

    function loadScenario(scenarioNum) {
        var scenario = scenarios[scenarioNum];

        document.getElementById('fromTbx').value = scenario.from;
        document.getElementById('toTbx01' + ',' + 'toTbx02').value  = scenario.to;

        document.getElementById('vehicleWidth').value = scenario.width;
        document.getElementById('vehicleHeight').value = scenario.height;
        document.getElementById('vehicleLength').value = scenario.length;
        document.getElementById('vehicleWeight').value = scenario.weight;

        var vehicleLoadTypeSelect = document.getElementById('vehicleLoadType');

        for (var i = 0; i < vehicleLoadTypeSelect.length; i++) {
            if (scenario.load.indexOf(vehicleLoadTypeSelect.options[i].value) > -1) {
                vehicleLoadTypeSelect.options[i].selected = 'selected';
            } else {
                vehicleLoadTypeSelect.options[i].selected = null;
            }
        }

        calculateDirections();

        document.getElementById('output').innerHTML = '<a href="' + scenario.streetsideLink + '" target="_blank">Streetside</a><br/>';
    }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...