Pelias angular.js example

by Peter Johnson

HTML

<div ng-controller="MyCtrl">
  <ul id="errors">
    <li ng-repeat="error in errors track by $index">
        {{error}}
    </li>
  </ul>
  <ul id="results">
    <li ng-repeat="label in labels track by $index">
    {{label}}
    </li>
  </ul>
  <pre ng-bind="response"></pre>
</div>

CSS

#results,
#errors {
  font-family: Helvetica, Arial, Sans-Serif;
  font-size: 12px;
  list-style: none;
  padding: 0;
}
#results li,
#errors li{
  display:block;
  color:#000000;
  line-height:30px;
  border-bottom: solid 1px #CCCCCC;
  padding:0 10px;
  cursor: pointer;
}
#results li:hover {
  color:#FFFFFF;
  font-weight: bold;
  background-color: lightblue;
}
#errors li {
  color:#FF0000;
}

JavaScript

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope, $http) {
  $scope.labels = [];
  $scope.errors = [];
  $scope.response = '';

  $http({
    url: "https://search.mapzen.com/v1/search",
    method: "GET",
    headers: { "Accept": "application/json" },
    params: {
      "text": "London, UK",
      "api_key":'search-EEgHGcM'
    },
  })
  .success(function( data, status ) {
    console.log( status );
    displayResults( $scope, data, status );
  })
  .error(function( data, status ) {
    console.log( status );
    displayResults( $scope, data, status );
  });
});

function displayResults( $scope, data, status ){
  $scope.labels.length = 0;
  $scope.errors.length = 0;

  console.log( "api response!" );
  console.log( data );
  $scope.response = angular.toJson( data, true )

  // api_key error
  if( data.results && data.results.error ){
    $scope.errors.push( data.results.error.message );
  }
    
  // fatal error
  if( !data || !data.geocoding ){ return; }

  // error messages
  if( Array.isArray( data.geocoding.errors ) ){
    data.geocoding.errors.forEach(function(e){
      $scope.errors.push( e );
    });
  }

  // success
  data.features.forEach(function(feat){
    var label = feat.properties.label;
    $scope.labels.push( label );
  });
};