Sha256: ab465b1b4a15c17a4199a75a45da235b3faf99f8bdc6ea3e11afa4301e89fc20

Contents?: true

Size: 1.22 KB

Versions: 4

Compression:

Stored size: 1.22 KB

Contents

module Graticule #:nodoc:
  module Geocoder #:nodoc:
    class Mapbox < Base
      BASE_URL = "http://api.mapbox.com/geocoding/v5/mapbox.places"

      def initialize(api_key)
        @api_key = api_key
      end

      def locate(address)
        get :q => address
      end

      protected

      class Result
        attr_accessor :lat, :lon, :precision

        def initialize(attributes)
          self.precision = ::Graticule::Precision::Unknown
          self.lon = attributes["center"][0]
          self.lat = attributes["center"][1]
        end
      end

      def make_url(params)
        query = URI.escape(params[:q].to_s)
        url = "#{BASE_URL}/#{query}.json?access_token=#{@api_key}"

        URI.parse(url)
      end

      def check_error(response)
        raise AddressError, 'unknown address' if (response["features"].nil? || response["features"].empty?)
      end

      def prepare_response(response)
        JSON.parse(response)
      end

      def parse_response(response)
        # Pull data from the first result since we get a bunch
        result = Result.new(response["features"][0])

        Location.new(
          :latitude  => result.lat,
          :longitude => result.lon,
        )
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
graticule-2.7.2 lib/graticule/geocoder/mapbox.rb
graticule-2.7.1 lib/graticule/geocoder/mapbox.rb
graticule-2.7.0 lib/graticule/geocoder/mapbox.rb
graticule-2.6.0 lib/graticule/geocoder/mapbox.rb