Невозможно нарисовать поллину на карте в openlayer3 с помощью службы направления

Я пытаюсь добавить службу направления на карту 1: мне нужно отобразить карту 2: как только я получу ответ от сервера или вызову метод, только тогда я должен нарисовать полилинию, которую я пытаюсь сделать, как показано ниже

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">-->
</head>
<body>
<div id="map" class="map"></div>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>

<script>
    var map;
    var vectorLayer;
    var extentToZoom;
    var geojsonObject;

   /* function addGeoObject(){
        geojsonObject ={"status":200,"hint_data":{"locations":["1DYUCf____89vE8AWwAAANkCAAAAAAAAcAAAAG_vKABaqAAATqcUAIO1MgYAAAEB","1DYUCf____89vE8AEAAAAHAAAADZAgAAAAAAAG_vKABaqAAAtZkUAPGvMgYBAAEB"],"checksum":4294707914},"route_name":["T3 Arrival Drive","T3 Arrival Drive"],"status_message":"Found route between points","route_geometry":"{srqAewyieEzrExuAtDhA","via_indices":[0,2],"route_instructions":[["10","T3 Arrival Drive",418,0,2,"418m","S",202,1,"N",22],["15","",0,2,0,"0m","N",0,"N",0]],"via_points":[[1.35355,103.986563],[1.350069,103.985137]],"found_alternative":false,"route_summary":{"total_distance":418,"total_time":65,"end_point":"T3 Arrival Drive","start_point":"T3 Arrival Drive"}}
        //console.log(geojsonObject.coordinates);
    }*/
    function drawPolyline(geoObject){
    var image = new ol.style.Circle({
        radius: 5,
        fill: null,
        stroke: new ol.style.Stroke({color: 'red', width: 1})
    });
    var styles = {
        'Point': new ol.style.Style({
            image: image
        }),
        'LineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 3
            })
        }),
        'MultiLineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 1
            })
        }),
        'MultiPoint': new ol.style.Style({
            image: image
        }),
        'MultiPolygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'yellow',
                width: 1
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 0, 0.1)'
            })
        }),
        'Polygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                lineDash: [4],
                width: 3
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
        }),
        'GeometryCollection': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'magenta',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: 'magenta'
            }),
            image: new ol.style.Circle({
                radius: 10,
                fill: null,
                stroke: new ol.style.Stroke({
                    color: 'magenta'
                })
            })
        }),
        'Circle': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 2
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255,0,0,0.2)'
            })
        })
    };
    var styleFunction = function(feature, resolution) {
        return styles[feature.getGeometry().getType()];
    };
        geojsonObject =geoObject;
    var routeGeom = new ol.format.Polyline(
            {
                factor: 1e6
            }).readGeometry(geojsonObject.route_geometry, {
                dataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            });
    var routeFeature = new ol.Feature({
        geometry:routeGeom
    })
     extentToZoom = routeGeom.getExtent();
    var vectorSource = new ol.source.Vector({
        features: [routeFeature]
    });
        map = new ol.Map({
            layers: [
                new ol.layer.Vector({
                    source: vectorSource,
                    style: styleFunction
                })
            ],
            target: 'laneMap'
        });
}

    function initMap(){
        map = new ol.Map({
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            target: 'map',
            controls: ol.control.defaults({
                attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
                    collapsible: false
                })
            }),
            view: new ol.View({
                center: ol.proj.fromLonLat([103.986908, 1.353199]),
                rotation: 68*Math.PI/180,
                zoom: 18
            })
        });

    }
    initMap();
    geojsonObject ={"status":200,"hint_data":{"locations":["1DYUCf____89vE8AWwAAANkCAAAAAAAAcAAAAG_vKABaqAAATqcUAIO1MgYAAAEB","1DYUCf____89vE8AEAAAAHAAAADZAgAAAAAAAG_vKABaqAAAtZkUAPGvMgYBAAEB"],"checksum":4294707914},"route_name":["T3 Arrival Drive","T3 Arrival Drive"],"status_message":"Found route between points","route_geometry":"{srqAewyieEzrExuAtDhA","via_indices":[0,2],"route_instructions":[["10","T3 Arrival Drive",418,0,2,"418m","S",202,1,"N",22],["15","",0,2,0,"0m","N",0,"N",0]],"via_points":[[1.35355,103.986563],[1.350069,103.985137]],"found_alternative":false,"route_summary":{"total_distance":418,"total_time":65,"end_point":"T3 Arrival Drive","start_point":"T3 Arrival Drive"}};
    drawPolyline(geojsonObject);
   /* var geoobject2={"status":200,"hint_data":{"locations":["UiQkCf____-ljiMAEAAAABgAAAAAAAAAAAAAAP____-jqAAAt5gUAG2wMgYAAAEB","c8gaCf____8AAAAAMgAAALAAAAAAAAAAHQEAAOviEAajqAAAdqQUABy3MgYAAAEB"],"checksum":4089551480},"route_name":["East Coast Parkway (ECP)",""],"status_message":"Found route between points","route_geometry":"mjkqAyewieEsHuB_m@qWoYwJuDoDoAqBoFaJkCsD}H_Hai@{Pw`@iM","via_indices":[0,10],"route_instructions":[["10","East Coast Parkway (ECP)",18,0,2,"18m","N",21,1,"S",201],["1","",308,1,24,"307m","NE",28,1,"SW",208],["1","",65,9,5,"65m","NE",23,1,"SW",203],["15","",0,10,0,"0m","N",0,"N",0]],"via_points":[[1.349815,103.985261],[1.352822,103.986972]],"found_alternative":false,"route_summary":{"total_distance":391,"total_time":29,"end_point":"","start_point":"East Coast Parkway (ECP)"}};
    drawPolyline(geoobject2);*/
    initMap();
    map.getView().fit(extentToZoom,map.getSize())
</script>

</body>
</html>

В приведенном выше коде метод initMap будет рисовать простую карту, как только я вызову метод drawPolyline, он должен показать график (это потому, что я получу данные из zmq, как только я получу данные, которые я должен построить)

Я долго пытался это сделать, пожалуйста, помогите, опубликовав правильный код для этого, или предложите способ сделать это.


person DhanaLaxshmi    schedule 12.01.2016    source источник
comment
Векторные слои можно загружать намного проще. См. openlayers.org/en/v3.12.1/examples/vector-layer .html. Ниже я публикую ответ, в котором предполагается, что вы можете вызвать свою службу маршрутизации с помощью запроса AJAX GET.   -  person ahocevar    schedule 13.01.2016


Ответы (1)


Предполагая, что ваша служба маршрутизации отвечает на простой запрос AJAX GET, вы можете сэкономить много усилий, используя встроенную загрузку слоев OpenLayers. Что-то типа

function drawPolyline(url) {
  map.addLayer(new ol.layer.Vector({
    source: new ol.source.Vector({
      format: new ol.format.Polyline(),
      url: url
    }),
    style: styleFunction
  }));
}

Аргумент url в приведенной выше функции — это URL-адрес, который вы используете для получения трека от службы маршрутизации.

person ahocevar    schedule 13.01.2016