【发布时间】:2019-09-13 22:32:58
【问题描述】:
目前我有一个使用外部 API 并允许用户查询和返回 json 的简单应用程序。它返回所有键/值,但我只希望它在 json 中返回 lat 和 lon,或者至少我只想在我的视图中显示这两个。这是我的代码:
locationiq_api.rb
class LocationiqApi
include HTTParty
BASE_URI = "https://eu1.locationiq.com/v1/search.php"
attr_accessor :city
def initialize(api_key, format = "json")
@options = { key: api_key, format: format }
end
def find_coordinates(city)
self.class.get(BASE_URI, query: @options.merge({ q: city }))
end
def handle_error
if find_coordinates.code.to_i = 200
find_coordinates.parsed_response
else
raise "Couldn't connect to LocationIQ Api"
end
end
end
locations_controller.rb
class LocationsController < ApplicationController
def index
@search = LocationiqApi.new("pk.29313e52bff0240b650bb0573332121e").find_coordinates(params[:q])
end
end
locations.html.erb
<main>
<h1>Location Search</h1>
<!-- Button to search find coordinates -->
<%= form_tag(locations_path, method: :get) do %>
<%= label_tag(:q, "Search: ") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Find coordinates") %>
<% end %><br>
<h2>Search results:</h2>
</main>
<%= @search %>
返回的json:
[{"place_id":"100066","licence":"https:\/\/locationiq.com\/attribution","osm_type":"node","osm_id":"107775","boundingbox":["51.3473219","51.6673219","-0.2876474","0.0323526"],"lat":"51.5073219","lon":"-0.1276474","display_name":"London, Greater London, England, SW1A 2DX, United Kingdom","class":"place","type":"city","importance":0.9654895765402,"icon":"https:\/\/locationiq.org\/static\/images\/mapicons\/poi_place_city.p.20.png"}]
【问题讨论】:
-
API 返回的 JSON 是什么样的?
-
@jvillian 我现在已将其添加到问题中。
标签: ruby-on-rails ruby geocoding rails-api httparty