github.com/omniscale/go-osm@v0.3.1/parser/pbf/doc_test.go (about)

     1  package pbf_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"sync"
     9  
    10  	"github.com/omniscale/go-osm"
    11  	"github.com/omniscale/go-osm/parser/pbf"
    12  )
    13  
    14  func Example() {
    15  	// Open PBF file.
    16  	f, err := os.Open("./monaco-20150428.osm.pbf")
    17  	if err != nil {
    18  		log.Fatal(err)
    19  	}
    20  	defer f.Close()
    21  
    22  	// Create channels for the parsed elements.
    23  	nodes := make(chan []osm.Node)
    24  	ways := make(chan []osm.Way)
    25  	relations := make(chan []osm.Relation)
    26  
    27  	// Initialize PBF parser.
    28  	p := pbf.New(f, pbf.Config{
    29  		Nodes:     nodes,
    30  		Ways:      ways,
    31  		Relations: relations,
    32  	})
    33  
    34  	// ==========================================
    35  	// This is where you can place your own code.
    36  	// This example only counts nodes, ways and relations.
    37  
    38  	// We start a separate goroutine for each type. We use WaitGroup to make
    39  	// sure all elements are processed before we return the results.
    40  
    41  	// You can even start multiple goroutines for each type to distribute
    42  	// processing accross multiple CPUs.
    43  
    44  	var numNodes, numWays, numRelations int64
    45  	wg := sync.WaitGroup{}
    46  
    47  	go func() {
    48  		wg.Add(1)
    49  		for nds := range nodes {
    50  			numNodes += int64(len(nds))
    51  		}
    52  		wg.Done()
    53  	}()
    54  
    55  	go func() {
    56  		wg.Add(1)
    57  		for ways := range ways {
    58  			numWays += int64(len(ways))
    59  		}
    60  		wg.Done()
    61  	}()
    62  
    63  	go func() {
    64  		wg.Add(1)
    65  		for rels := range relations {
    66  			numRelations += int64(len(rels))
    67  		}
    68  		wg.Done()
    69  	}()
    70  	// ==========================================
    71  
    72  	// Create a new context. Can be used for cancelation, or timeouts.
    73  	ctx := context.Background()
    74  
    75  	// Start parsing.
    76  	err = p.Parse(ctx)
    77  	if err != nil {
    78  		log.Fatal(err)
    79  	}
    80  
    81  	// Wait till our custom goroutines are finished.
    82  	wg.Wait()
    83  
    84  	fmt.Printf("parsed %d nodes, %d ways and %d relations\n", numNodes, numWays, numRelations)
    85  	// Output: parsed 17233 nodes, 2398 ways and 108 relations
    86  }