3D-экструзия с mapbox на основе локального файла geojson - PullRequest
0 голосов
/ 17 сентября 2018

Я видел этот пример в Интернете, который выполняет экструзию здания на основе данных , но не предоставляет код вообще.

Я бы очень хотел добиться того же.У меня есть файл geojson с каким-то атрибутом, который я хотел бы отобразить на высоту здания.Знаете ли вы, как это возможно?

Я рассмотрел рекомендуемую альтернативу : делать 3D-выталкивания на кругах, которые уже созданы на основе моих данных.Код этого сообщения в блоге не предоставляется, и поэтому я подал в суд на код этого ТАКОГО сообщения .

Код выглядит так:

<html>
<head>
    <meta charset='utf-8' />
    <title>Display buildings in 3D</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.css' rel='stylesheet' />
    <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script> 
    <style>
        body {
          margin: 0;
          padding: 0;
        }

        #map {
          position: absolute;
          top: 0;
          bottom: 0;
          width: 100%;
        }
    </style>
</head>
<body>

<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoicXVlMzIxNiIsImEiOiJjaWhxZmMxMDUwMDBzdXhsdWh0ZDkyMzVqIn0.sz3lHuX9erctIPE2ya6eCw';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [8.538961, 47.372476],
  zoom: 16,
  pitch: 40,
  hash: true
});

var url = 'http://127.0.0.1:62940/test2.json';

mapboxgl.accessToken = 'pk.eyJ1IjoicXVlMzIxNiIsImEiOiJjaWhxZmMxMDUwMDBzdXhsdWh0ZDkyMzVqIn0.sz3lHuX9erctIPE2ya6eCw';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [8.538961, 47.372476],
  zoom: 16,
  pitch: 40,
  hash: true
});

map.on('load', function() {

  map.addLayer({
    'id': 'extrusion',
    'type': 'fill-extrusion',
    "source": {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": []
      }
    },
    'paint': {
      'fill-extrusion-color': '#00f',
      'fill-extrusion-height': ['get', 'frequency'],
      'fill-extrusion-base': 0,
      'fill-extrusion-opacity': 0.9
    }
  });

  map.addLayer({
    "id": "total",
    'type': 'circle',
    'paint': {
      'circle-radius': {
        'base': 1.75,
        'stops': [
          [12, 2],
          [22, 180]
        ]
      },
      'circle-color': '#ff7770'
    },
    "source": {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [8.538961, 47.372476]
            },
            "properties": {
              "frequency": 100
            }
          },
          {
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [8.539961, 47.372476]
            },
            "properties": {
              "frequency": 44
            }
          }
        ]
      }
    }
  });


  map.on('sourcedata', function(e) {
    if (e.sourceId !== 'total') return
    if (e.isSourceLoaded !== true) return

    var data = {
      "type": "FeatureCollection",
      "features": []
    }
    e.source.data.features.forEach(function(f) {
      var object = turf.centerOfMass(f)
      var center = object.geometry.coordinates
      var radius = 10;
      var options = {
        steps: 16,
        units: 'meters',
        properties: object.properties
      };
      data.features.push(turf.circle(center, radius, options))
    })
    map.getSource('extrusion').setData(data);
  })
});


</script>

Так что это работает просто отлично.

Однако, когда я пытаюсь получить то же самое с локальным файлом геоджона, который содержит точно такие же данные, он не работает вообще.

Здесьмой json:

{"type": "FeatureCollection", "features": [{"id": 1, "type": "Feature", "properties": {"frequency":44}, "geometry": {"type": "Point", "coordinates": [8.538961, 47.372476]}}, {"id": 2, "type": "Feature", "properties": {"frequency":200}, "geometry": {"type": "Point", "coordinates": [8.539961, 47.372476]}}]}

А вот мой код:

<html>
<head>
    <meta charset='utf-8' />
    <title>Display buildings in 3D</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.css' rel='stylesheet' />
    <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script> 
    <style>
        body {
          margin: 0;
          padding: 0;
        }

        #map {
          position: absolute;
          top: 0;
          bottom: 0;
          width: 100%;
        }
    </style>
</head>
<body>

<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoicXVlMzIxNiIsImEiOiJjaWhxZmMxMDUwMDBzdXhsdWh0ZDkyMzVqIn0.sz3lHuX9erctIPE2ya6eCw';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [8.538961, 47.372476],
  zoom: 16,
  pitch: 40,
  hash: true
});

var url = 'http://127.0.0.1:62940/test2.json';

mapboxgl.accessToken = 'pk.eyJ1IjoicXVlMzIxNiIsImEiOiJjaWhxZmMxMDUwMDBzdXhsdWh0ZDkyMzVqIn0.sz3lHuX9erctIPE2ya6eCw';

var url = 'http://127.0.0.1:62940/test2.json';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [8.538961, 47.372476],
  zoom: 16,
  pitch: 40,
  hash: true
});

map.on('load', function() {

  map.addLayer({
    'id': 'extrusion',
    'type': 'fill-extrusion',
    "source": {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": []
      }
    },
    'paint': {
      'fill-extrusion-color': '#00f',
      'fill-extrusion-height': ['get', 'frequency'],
      'fill-extrusion-base': 0,
      'fill-extrusion-opacity': 0.9
    }
  }); 

 map.addSource("data", {
        type: "geojson",
        data: url,
    });

  map.addLayer({
    "id": "total",
    'type': 'circle',
    'paint': {
      'circle-radius': {
        'base': 1.75,
        'stops': [
          [12, 2],
          [22, 180]
        ]
      },
      'circle-color': '#ff7770'
    },
    "source": "data",
    /*"source": {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [8.538961, 47.372476]
            },
            "properties": {
              "frequency": 100
            }
          },
          {
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [8.539961, 47.372476]
            },
            "properties": {
              "frequency": 44
            }
          }
        ]
      }
    }*/
  });


  map.on('sourcedata', function(e) {
    if (e.sourceId !== 'total') return
    if (e.isSourceLoaded !== true) return

    var data = {
      "type": "FeatureCollection",
      "features": []
    }
    e.source.data.features.forEach(function(f) {
      var object = turf.centerOfMass(f)
      var center = object.geometry.coordinates
      var radius = 10;
      var options = {
        steps: 16,
        units: 'meters',
        properties: object.properties
      };
      data.features.push(turf.circle(center, radius, options))
    })
    map.getSource('extrusion').setData(data);
  })
});


</script>

Я предполагаю, что есть что-то, чего я не понял в обратном вызове, сделанном для обработки данных с помощью дерна, ноЯ просто не могу понять, что именно, и я не нахожу много примеров картографических карт, которые могут помочь с документацией.

Вот ожидаемый результат: image_expected output

А вот мой вывод: my_output

Любая помощь будет оценена.

1 Ответ

0 голосов
/ 17 сентября 2018

Поскольку вы добавили удаленный файл geojson, вам нужно изменить проверки и способ получения и обработки данных:

  map.on('sourcedata', function(e) {

    // if (e.sourceId !== 'total') return
    if (e.sourceId !== 'data') return
    if (e.isSourceLoaded !== true) return

    var data = {
      "type": "FeatureCollection",
      "features": []
    }

    // e.source.data.features.forEach(function(f) {
    map.querySourceFeatures('data').forEach(function(f) {
      var object = turf.centerOfMass(f)
      var center = object.geometry.coordinates
      var radius = 10;
      var options = {
        steps: 16,
        units: 'meters',
        properties: object.properties
      };
      data.features.push(turf.circle(center, radius, options))
    })
    map.getSource('extrusion').setData(data);
  })

[https://jsfiddle.net/vd2crsob/]

...