Exporting a map with AngularJS and openlayers

By Eugenia Pérez | 14 April, 2015

In the previous post  I talked about how to create a map with AngularJS and openlayers. You see the directive created by  tombatossals and accesible on this link: https://github.com/tombatossals/angular-openlayers-directive

This directive provides a handful of very useful features. However in this post we will see how to download a layer rendered on the map. Which is something missing in the directive. To do so we start by creating a simple button group with bootstrap.

<div class="btn-group pull-right">
        <button type="button" class="btn btn-xs btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                Descargar <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu">
             <li ng-hide="isIeAndGpx"><a href="{{kmlDownload}}" download="mapa.kml" ng-click="exportAsKml()">Como KML</a></li>
             <li ng-hide="isIeAndKml"><a href="{{gpxDownload}}" download="mapa.gpx" ng-click="exportAsGpx()">Como GPX</a></li>
        </ul>
</div>

As you can see the links used to create the action buttons have an HTML5 attribute called ‘download’. This attribute is very useful to create files on the client and downladed them without using server-side logic. Once this is setup we just need a method to get the data layer of the map loop through its features and push them to a string, which will eventually encode it to a Base64 string. This Base64 has to be assigned to the href attribute of the downloads link.

$scope.exportAsGpx = function () {
         olData.getMap("expandedMap").then(function (map) {
             var features = MapUtils.getFeaturesFromLayer(map);
             var string = new ol.format.GPX().writeFeatures(features);
             if (BrowserUtils.detectIE() || BrowserUtils.isSafari()) {
                    window.open(MapUtils.courseFilesUrl + $scope.event.CourseFileName);
             } else {
                    var base64 = ConversionUtils.strToBase64(string);
                    $scope.gpxDownload = 'data:text/gpx+xml;base64,' + base64;
             }
         });
    };

In the screenshots below this feature is shown in action. The map has a button the user can click between GPX or KML formats to download the path printed on the map.

All this stuff has been developed to allow visitors to see and download the path of races in which they are interested. Keep in touch to find more about it. The project is intended to be released by this summer.

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather