BingMapsGeocoderService.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import BingMapsApi from './BingMapsApi.js';
  2. import Check from './Check.js';
  3. import defaultValue from './defaultValue.js';
  4. import defineProperties from './defineProperties.js';
  5. import Rectangle from './Rectangle.js';
  6. import Resource from './Resource.js';
  7. var url = 'https://dev.virtualearth.net/REST/v1/Locations';
  8. /**
  9. * Provides geocoding through Bing Maps.
  10. * @alias BingMapsGeocoderService
  11. * @constructor
  12. *
  13. * @param {Object} options Object with the following properties:
  14. * @param {String} [options.key] A key to use with the Bing Maps geocoding service
  15. */
  16. function BingMapsGeocoderService(options) {
  17. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  18. var key = options.key;
  19. this._key = BingMapsApi.getKey(key);
  20. this._resource = new Resource({
  21. url: url,
  22. queryParameters: {
  23. key: this._key
  24. }
  25. });
  26. }
  27. defineProperties(BingMapsGeocoderService.prototype, {
  28. /**
  29. * The URL endpoint for the Bing geocoder service
  30. * @type {String}
  31. * @memberof BingMapsGeocoderService.prototype
  32. * @readonly
  33. */
  34. url : {
  35. get : function () {
  36. return url;
  37. }
  38. },
  39. /**
  40. * The key for the Bing geocoder service
  41. * @type {String}
  42. * @memberof BingMapsGeocoderService.prototype
  43. * @readonly
  44. */
  45. key : {
  46. get : function () {
  47. return this._key;
  48. }
  49. }
  50. });
  51. /**
  52. * @function
  53. *
  54. * @param {String} query The query to be sent to the geocoder service
  55. * @returns {Promise<GeocoderService~Result[]>}
  56. */
  57. BingMapsGeocoderService.prototype.geocode = function(query) {
  58. //>>includeStart('debug', pragmas.debug);
  59. Check.typeOf.string('query', query);
  60. //>>includeEnd('debug');
  61. var resource = this._resource.getDerivedResource({
  62. queryParameters: {
  63. query: query
  64. }
  65. });
  66. return resource.fetchJsonp('jsonp').then(function(result) {
  67. if (result.resourceSets.length === 0) {
  68. return [];
  69. }
  70. var results = result.resourceSets[0].resources;
  71. return results.map(function (resource) {
  72. var bbox = resource.bbox;
  73. var south = bbox[0];
  74. var west = bbox[1];
  75. var north = bbox[2];
  76. var east = bbox[3];
  77. return {
  78. displayName: resource.name,
  79. destination: Rectangle.fromDegrees(west, south, east, north)
  80. };
  81. });
  82. });
  83. };
  84. export default BingMapsGeocoderService;