Giter Site home page Giter Site logo

opentraffic / tangram-viz-experiments Goto Github PK

View Code? Open in Web Editor NEW
4.0 7.0 1.0 1.11 MB

OTv2: work-in-progress to visualize anonymized and aggregated traffic statics using Tangram

Home Page: http://opentraffic.io/tangram-viz-experiments/

License: MIT License

HTML 64.78% JavaScript 32.44% Python 2.78%

tangram-viz-experiments's Introduction

Open Traffic ~ Tangram Demo

This map can be used in two ways: against a live API or against a local cached copy of a GeoJSON extract.

To use against a live OTv2 API, you will need to specify two query parameters:

  • server - hostname for the API
  • secret_key - to authenticate against the API

For example: http://opentraffic.io/tangram-viz-experiments/?server=host.opentraffic.io&secret=password

To use against a local cached copy of a GeoJSON extract:

  1. Construct a query to the OTv2 API using the available query parameters.
  2. Save the response as a .geojson file to a local copy of this repository.
  3. Update the data source within the Tangram scene file to reference that file: scene.yaml#L9-L12
  4. Update the initial map start position: index.html#L190

How does it work?

The pipeline for this is:

  1. Interaction on the map
  2. Get map BoundingBox
  3. Do HTTP request to OpenTraffic server
  4. Load the GeoJSON Reply as a Tangram data source
  5. In Tangram scene YAML file, filter the data into a layer where the speed, drive_on_right and oneway properties are mapped to RGB channels of the geometry
  6. That geometry use a custom shader style that draws arrows in the right direction, and mapped the speed to a palette defined by a .png file (that can be generated by Spectrum App or any other software.)

1. On map Interaction

When the map changes position...

    map.on('moveend', debounce(function() {
        // Update the displayed information
        update();
    }, 1000));

Note: the call is debounced to avoid unnecessary multiple calls

2, 3 & 4. Request and load OpenTraffic data

Get the bounding box and present time to construct a HTTP call to OpenTraffic.

NOTE: the call have to be change to ask for a year of data instead of an hour. Also the query should be made for only one day of the week (using dow) to reduce stream of data. (Check all this with Kevin)

function update() {

    // Get the current boundaries of the displayed area on the map
    var bbox = map.getBounds();
    var day = moment().format('YYYY-MM-DD')
    var hour = moment().format('HH:MM:SS')

    // Make the URL for OpenWeatherMaps API, asking for all stations inside that area (bounding box)
    var url = 'https://localhost:3000/query?';
    url += '&start_date_time=' + day + 'T'+ moment().subtract(1,'hour').format('HH:MM:SS');
    url += '&end_date_time=' + day + 'T' + moment().format('HH:MM:SS');
    url += '&boundingbox=' + bbox.getSouthWest().lng + ',' +bbox.getSouthWest().lat + ',' + bbox.getNorthEast().lng + ',' + bbox.getNorthEast().lat;

    console.log('Fake call to:', url);

    // Make the request and wait for the reply
    fetch(url)
        .then(function (response) {
            // If we get a positive response...
            if (response.status !== 200) {
                console.log('Error getting data: ' + response.status);
                return;
            }
            // ... parse it to JSON
            return response.json();
        })
        .then(function(json) {
            var data = { " opentraffic": json };
            // Pass the POIs as a GeoJSON FeaturesCollection to tangram
            scene.setDataSource('opentraffic', {type: 'GeoJSON', data: json});
        })
        .catch(function(error) {
            console.log('Error parsing the GeoJSON.', error)
        })
}

5. Encode the data as color

Warning: the data on the valhalla tile that Kevin send me have a single float for speed. THIS WILL CHANGE there going to be multiple speed according to

layers:
    opentraffic:
        data: { source: opentraffic }
        draw:
            ot-roads:
                order: 10001
                width: [[10,2px],[15,5px],[20,5m]]
                color: |
                    function () {
                        return [ feature.speed/255, feature.drive_on_right, feature.oneway ]; 
                    }

6. Style the data in the line

Use the color to draw an chevron arrow pattern in the right direction, and for the speed color use a regular .png (that can be generated by Spectrum App or any other software.)

textures:
    palette:
        url: assets/palette-01.png
styles:
    ot-roads:
        base: lines
        mix: [functions-zoom, functions-aastep, generative-random]
        texcoords: true
        animated: true
        lighting: false
        blend: inlay
        shaders:
            defines:
                ZOOM_START: 15.
                ZOOM_END: 20.
                ZOOM_IN: .0
                ZOOM_OUT: .5
            uniforms:
                u_palette: palette
            blocks:
                width: |
                    // One or two lanes
                    width = mix(width*v_texcoord.x, width, a_color.b);
                color: |
                    // Speed to color from palette LUT 
                    color = texture2D(u_palette, vec2(smoothstep(0.,.3,v_color.r),.5));

                    // Draw arrows
                    vec2 st = v_texcoord.xy+vec2(.5,0.);

                    // Flip direction if the the drive is not on the right.
                    st.y = mix(1.-fract(st.y),st.y,v_color.g);
                    // Adjust the speed to the speed
                    st.y -= u_time*10.*v_color.r;

                    // Make chrevone arrow
                    color.a *= aastep(zoom(),fract(st.y+abs(st.x*.5-.5)));

tangram-viz-experiments's People

Contributors

patriciogonzalezvivo avatar drewda avatar nvkelso avatar

Stargazers

 avatar Sam Petulla avatar  avatar Will Skora avatar

Watchers

Randy Meech avatar Kevin Webb avatar Steven Ottens avatar Geraldine Sarmiento avatar James Cloos avatar  avatar Holly avatar

Forkers

sensescape

tangram-viz-experiments's Issues

Small roads look "stopped", but are actually moving

Many of the smaller roads in Manila (e.g. tertiary) just don't move as fast as motorway speeds, but our colors and the speed breaks are biased for the bigger express routes. This makes the neighborhood streets look "grid locked", but in fact traffic is probably moving like "normal" there with respect to city street speed regulations. On a highway it may be 100 km/hr, but on a surface road it may be 45 km/hr max regulation speed.

Maybe we can use the same "colors", but with different speed breaks per road class, in Tilezen kind syntax:

  • highways: highway = motorway
  • major road: highway = primary, secondary, tertiary
  • minor road: highway = residential ... and most others

@patriciogonzalezvivo what do you think? 2 or 3 different shaders, or one shader with a property we can toggle per kind of road?

Document time range on the map

Right now it's a default time range, but in the future there will be a dynamic time range so this should accommodate static and dynamic labels.

Overlapping traffic lines should be offset

On the road Maria Clara we have 2 features on top of each other – they should instead be pointing opposite directions and offset from each other. Notice how this works on Vicente Cruz "correctly", though maybe there is a difference of oneway=true versus oneway=false here.

Not sure if this is a Tangram problem or data problem on the server.

/cc @patriciogonzalezvivo @kevinkreiser

19/14.61743/120.99033

screen shot 2017-03-21 at 5 08 23 pm

screen shot 2017-03-21 at 5 10 41 pm

screen shot 2017-03-21 at 5 11 05 pm

Speed and color breaks

Regarding:

- Do we want to interpolate the colors? or have hard breaks between them?
- Style the rest of the geometry (highways, primary roads, etc) that we
  don't have in our sample data

Let's mock up:

  • fast above 100 km / hr
  • medium: between 60 and 100 km / hr
  • slow: between 30 and 60 km / hr
  • stopped: less than 30 km / hr

no color interpolation (just sharp breaks)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.