как вставить линию между точками - PullRequest
0 голосов
/ 11 февраля 2019

Здравствуйте, я добавляю свои данные json в карту, как показано в коде ниже.Теперь я хочу вставить линию между точками.Я искал что-то похожее, но безуспешно.у меня есть и другой, когда я изменяю свои данные, точки на карте не обновляются, отображаются только первые данные, полученные в начале.ЕСЛИ это так, пожалуйста, оставьте свой ответ.

 geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
          styleMap: new OpenLayers.StyleMap({
              "default": new OpenLayers.Style({
              pointRadius: 2,
              fillColor: "red",
              fillOpacity: 1,
              strokeColor: "black",
              strokeWidth: 0.1,
              strokeOpacity: 1 } ),
              "select": { fillColor: "#8aeeef",
              strokeColor: "#32a8a9",
              labelYOffset:13,
              label:"${name}"} //Text entspricht feature.attributes.name
          }),
          projection: new OpenLayers.Projection("EPSG:4326"),
          strategies: [new OpenLayers.Strategy.Fixed()],
          protocol: new OpenLayers.Protocol.HTTP({
              url: 'https://api.myjson.com/bins/1gw97c',
              //url:'https://api.myjson.com/bins/sqri8',
              format: new OpenLayers.Format.GeoJSON()

          })
      });
      map.addLayer(geojson_layer); 




I am using a function like this to make a api call. 
HTML:
 <h:commandButton style= "width:120px; height:100px; padding-left:50px;" partialSubmit="true" immediate="true"  onclick="loadDoc()" image="/imgs_box/start.png" ></h:commandButton>
JS:
    function loadDoc() {
                var urlFielda = document.getElementById('urla');
                var urlFieldb = document.getElementById('urlb');
                var urlFieldc = document.getElementById('urlc');
                var urlFieldd = document.getElementById('urld');
               alert("filloi");
               fetch('http://apiexample.org/api/startgetpoint=' + urlFielda.value + '&start1=' + urlFieldb.value + '&end1=' + urlFieldc.value + '&end2='+ urlFieldd.value + '&NaviMethod=1&AllowedAreas=7')
               .then(function(response) {


                   return response.json();
                  // var convertedResponse = convertFormat(response);
                //return convertedResponse.json();
               })
               .then(function(myJson) {
                console.log(JSON.stringify(myJson));
                alert(JSON.stringify(myJson));
               });
             };

И я получаю ответ, подобный этому: "Путевые точки": [{"Lon": 19.455128, "Lat": 41.310575}, {"Lon": 19.455128, "Шир": 41.310574}, { "Lon": 19.457388, "Шир": 41.300442}, { "Lon": 19.413507, "Шир": 41.295189}, { "Lon": 16.871931, "Шир": 41.175926}, Возможно преобразовать эти данные json в geojson и показать на карте, как мой первый запрос, но получение данных из этого ответа не по этому URL: 'https://api.myjson.com/bins/sqri8',

Мне жаль, что я спрашиваюВы снова за этот вопрос.

Ответы [ 2 ]

0 голосов
/ 12 февраля 2019
.then(function(myJson) {
 geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
      styleMap: new OpenLayers.StyleMap({
          "default": new OpenLayers.Style({
          pointRadius: 2,
          fillColor: "red",
          fillOpacity: 1,
          strokeColor: "black",
          strokeWidth: 0.1,
          strokeOpacity: 1 } ),
          "select": { fillColor: "#8aeeef",
          strokeColor: "#32a8a9",
          labelYOffset:13,
          label:"${name}"} //Text entspricht feature.attributes.name
      }),
      //projection: new OpenLayers.Projection("EPSG:4326"),
      //strategies: [new OpenLayers.Strategy.Fixed()],
      //protocol: new OpenLayers.Protocol.HTTP({
         // url: 'https://api.myjson.com/bins/1gw97c',
          //url:'https://api.myjson.com/bins/sqri8',
          //format: new OpenLayers.Format.GeoJSON()
     // })
  });
  map.addLayer(geojson_layer); 

  //setTimeout(function() {
      //var points = [];
      //geojson_layer.features.forEach(function(feature) { points.push(feature.geometry); });
       //geojson_layer.addFeatures([
           //new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), {}, {})
       //]);
 //}, 5000);
 var features = [];
var points = [];
myJson.Waypoints.forEach(function(wp) {
   var point = new OpenLayers.Geometry.Point(wp.Lon, wp.Lat).transform(
        new OpenLayers.Projection("EPSG:4326"),
        map.getProjectionObject()
   );
   features.push(new OpenLayers.Feature.Vector(point));
   points.push(point);
})
features.push(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), {}, {}));
geojson_layer.addFeatures(features);

            console.log(JSON.stringify(myJson));
            alert(JSON.stringify(myJson));
           });
         }
0 голосов
/ 11 февраля 2019

Добавление линии между вашими точками работает для меня.Возможно, данные не были загружены до того, как вы попытались добавить строку (я использовал тайм-аут ожидания 2 секунды), или, возможно, ширина штриха 0,1 в таблице стилей сделала линию очень трудной для просмотра.Я использовал {} как стиль для строки, чтобы переопределить это и использовать OpenLayers по умолчанию.

  var map, layer;
  map = new OpenLayers.Map('map');
  layer = new OpenLayers.Layer.OSM("OSM Map");
  map.addLayer(layer);
  map.setCenter(
      new OpenLayers.LonLat(19.455128, 41.310575).transform(
          new OpenLayers.Projection("EPSG:4326"),
          map.getProjectionObject()
      ), 8
  );   

  geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
      styleMap: new OpenLayers.StyleMap({
          "default": new OpenLayers.Style({
          pointRadius: 2,
          fillColor: "red",
          fillOpacity: 1,
          strokeColor: "black",
          strokeWidth: 0.1,
          strokeOpacity: 1 } ),
          "select": { fillColor: "#8aeeef",
          strokeColor: "#32a8a9",
          labelYOffset:13,
          label:"${name}"} //Text entspricht feature.attributes.name
      }),
      projection: new OpenLayers.Projection("EPSG:4326"),
      strategies: [new OpenLayers.Strategy.Fixed()],
      protocol: new OpenLayers.Protocol.HTTP({
          url: 'https://api.myjson.com/bins/1gw97c',
          //url:'https://api.myjson.com/bins/sqri8',
          format: new OpenLayers.Format.GeoJSON()
      })
  });
  map.addLayer(geojson_layer); 
 
  setTimeout(function() {
       var points = [];
       geojson_layer.features.forEach(function(feature) { points.push(feature.geometry); });
       geojson_layer.addFeatures([
           new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), {}, {})
       ]);
  }, 2000);
html, body, #map, #background { height: 100%; margin: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js"></script>
<div id="map"></div>

Для вашего другого json вам понадобится перебрать маршрутные точки, чтобы построить объекты из данных и добавить их в слой самостоятельно, и вы могли быпостройте линейную линию в то же время.Слой не нуждается в стратегиях или протоколе.

var features = [];
var points = [];
myJson.Waypoints.forEach(function(wp) {
   var point = new OpenLayers.Geometry.Point(wp.Lon, wp.Lat).transform(
        new OpenLayers.Projection("EPSG:4326"),
        map.getProjectionObject()
   );
   features.push(new OpenLayers.Feature.Vector(point));
   points.push(point);
}
features.push(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), {}, {}));
geojson_layer.addFeatures(features);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...