d3读取json,实现路径的跟踪

d3.json的用法:

d3.json(datauri).then(function(data){ do someting here }).catch(function(error){something wrong})

1.d3.json异步读取json

2.json是一个geojson,类型是Point,需要把它的经纬度全部读取出来,转换成LineString。

3.数据源从只有一个coordinate,每1000毫秒增加一个coordinate,layer自动绘制数据源。

4.使用了map.jumpto({}),map.panto()成员变量。

map.on('load', function() {
        // We use D3 to fetch the JSON here so that we can parse and use it separately
        // from GL JS's use in the added source. You can use any request method (library
        // or otherwise) that you want.
        d3.json('http://192.168.10.103:8080/test.geojson')
            .then(function(data) {
		        var geojson = {
					'type': 'FeatureCollection',
					'features': []
				};
                var linestring = {
					'type': 'Feature',
					'geometry': {
						'type': 'LineString',
						'coordinates': []
					}
				};

				for (var n = 0 ; n < data.features.length; n++){				linestring.geometry.coordinates.push(data.features[n].geometry.coordinates);	
				};
				geojson.features.push(linestring);


                // save full coordinate list for later
                var coordinates = geojson.features[0].geometry.coordinates;
 
                // start by showing just the first coordinate
                geojson.features[0].geometry.coordinates = [coordinates[0]];
 
                // add it to the map
                map.addSource('trace', { type: 'geojson', data: geojson });
                map.addLayer({
                    'id': 'trace',
                    'type': 'line',
                    'source': 'trace',
                    'paint': {
                        'line-color': 'red',
                        'line-opacity': 0.75,
                        'line-width': 5
                    }
                });
 
                // setup the viewport
                map.jumpTo({ 'center': coordinates[0], 'zoom': 12 });
                map.setPitch(50);
 
                // on a regular basis, add more coordinates from the saved list and update the map
                var i = 0;
                //timer是window.setInterval()函数返回的intervalId,通过它可以实现暂停和启动。
                var timer = window.setInterval(function() {
                    if (i < coordinates.length) {
                        geojson.features[0].geometry.coordinates.push(
                            coordinates[i]
                        );
                        map.getSource('trace').setData(geojson);
                        map.panTo(coordinates[i],{duration: 5000});
                        i++;
                    } else {
                        window.clearInterval(timer);
                    }
                }, 1000);
            })
            .catch(function(error){
            	console.log('something wrong');
            });
    });

猜你喜欢

转载自blog.csdn.net/aganliang/article/details/107327430
D3