Sha256: 20488031626850c4388a76119bf8e548000025caef60a08ec835aa40641e43f2

Contents?: true

Size: 1.34 KB

Versions: 19

Compression:

Stored size: 1.34 KB

Contents

require 'geocoder/lookups/base'
require "geocoder/results/mapbox"

module Geocoder::Lookup
  class Mapbox < Base

    def name
      "Mapbox"
    end

    def query_url(query)
      "#{protocol}://api.mapbox.com/geocoding/v5/#{dataset}/#{url_query_string(query)}.json?access_token=#{configuration.api_key}"
    end

    private # ---------------------------------------------------------------

    def results(query)
      return [] unless data = fetch_data(query)
      if data['features']
        sort_relevant_feature(data['features'])
      elsif data['message'] =~ /Invalid\sToken/
        raise_error(Geocoder::InvalidApiKey, data['message'])
      else
        []
      end
    end

    def url_query_string(query)
      require 'cgi' unless defined?(CGI) && defined?(CGI.escape)
      if query.reverse_geocode?
        lat,lon = query.coordinates
        "#{CGI.escape lon},#{CGI.escape lat}"
      else
        CGI.escape query.text.to_s
      end
    end

    def dataset
      configuration[:dataset] || "mapbox.places"
    end

    def supported_protocols
      [:https]
    end

    def sort_relevant_feature(features)
      # Sort by descending relevance; Favor original order for equal relevance (eg occurs for reverse geocoding)
      features.sort_by do |feature|
        [feature["relevance"],-features.index(feature)]
      end.reverse
    end
  end
end

Version data entries

19 entries across 19 versions & 3 rubygems

Version Path
geocoder-1.4.4 lib/geocoder/lookups/mapbox.rb
enju_leaf-1.2.1 vendor/bundle/ruby/2.3/gems/geocoder-1.4.3/lib/geocoder/lookups/mapbox.rb
geocoder-1.4.3 lib/geocoder/lookups/mapbox.rb
geocoder-1.4.2 lib/geocoder/lookups/mapbox.rb
geocoder-1.4.1 lib/geocoder/lookups/mapbox.rb
geocoder-1.4.0 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.7 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.6 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.5 lib/geocoder/lookups/mapbox.rb
broken-geocoder-1.3.6 lib/geocoder/lookups/mapbox.rb
broken-geocoder-1.3.5 lib/geocoder/lookups/mapbox.rb
broken-geocoder-1.3.4 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.4 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.3 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.2 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.1 lib/geocoder/lookups/mapbox.rb
geocoder-1.3.0 lib/geocoder/lookups/mapbox.rb
geocoder-1.2.14 lib/geocoder/lookups/mapbox.rb
geocoder-1.2.13 lib/geocoder/lookups/mapbox.rb