public function build(Map $map, Assets $assets = null)
    {
        $prefix = 'var map, layers = {}, controls = {}, icons = {};' . "\n";

        if (!$assets) {
            return $prefix . $this->javascriptBuilder->encode($map, $this->jsonEncodeFlags);
        }

        $collector = new Collector($assets, $this->javascripts, $this->stylesheets);
        $this->eventDispatcher->addSubscriber($collector);

        $assets->setMap($prefix . $this->javascriptBuilder->encode($map, $this->jsonEncodeFlags));

        $this->eventDispatcher->removeSubscriber($collector);

        return $assets->getMap();
    }