首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Maps计算两个附件的距离,然后将每个距离保存到数据库

使用Maps计算两个附件的距离,然后将每个距离保存到数据库
EN

Stack Overflow用户
提问于 2018-02-22 16:03:45
回答 2查看 1K关注 0票数 1

我正在编写一个应用程序,根据距离将孩子们和幼儿园的孩子联系起来。

我正在尝试使用Maps API来计算多个嵌入之间的距离。我想用open

代码语言:javascript
复制
https://maps.googleapis.com/maps/api/distancematrix/json?origins=[address of child]&destinations=[adress of kindergarden]&key=XYZ

这将是对api的请求。

我的想法是向孩子的创造过程发送请求。我会从数据库中获取子地址和幼儿园地址,并构建请求。

回复的距离将保存在一个关系表为每个孩子和幼儿园,我如何能够访问数据库条目的儿童和幼儿园?然后把它保存到关系表中?

我的当前代码如下:

代码语言:javascript
复制
    def create
@child = Child.new child_params
@child.user = current_user
@child.save
origin = @child.adress
destination = @kiga.adress
response = open('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + [address of child] + '&destinations=' + [adress of kindergarden] + '&key=XYZ').read
relations.distance = response.rows.elements[0]

respond_to do |format|
  if @child.save
    format.html { redirect_to @child, notice: 'Child was successfully created.' }
    format.json { render :show, status: :created, location: @child }
  else
    format.html { render :new }
    format.json { render json: @child.errors, status: :unprocessable_entity }
  end
end

我会很感激你的帮助?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-22 19:13:34

这里的问题是,您试图以字符串的形式打开URL,因此它正在寻找一个名为该方式的文件,而且它并不存在。

你在这里有两个选择:

1.使用HTTP发出HTTParty请求

这是我最喜欢的方法。

将gem包含在Gemfile

代码语言:javascript
复制
gem 'HTTParty'

在控制器内发出请求:

代码语言:javascript
复制
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" \
      "#{@child.adress}&destinations=#{@kiga.adress}&key=XYZ"
response = HTTParty.get(url)

现在,如果要打印出response["rows"].first["elements"].first的结果,就会看到这样的输出:

代码语言:javascript
复制
{"distance"=>{"text"=>"15.4 km", "value"=>15405}, "duration"=>{"text"=>"17 mins", "value"=>1001}, "status"=>"OK"}

如您所见,您有距离和持续时间信息。我猜你所追求的是米的距离值,所以:

代码语言:javascript
复制
relations.distance = response["rows"].first["elements"].first["distance"]["value"]

备注1:我有意在单词地址(@child.adress,@kiga.adress)中复制错误,以便代码与您的设置一起工作,但考虑将其修复到@child.address和@kiga.address。

注释2:为了简单起见,我没有对响应进行任何错误检查,这是您绝对应该注意的事情。

注释3:记住将api键更改为有效密钥,为了简单起见,我将其硬编码为XYZ,就像您在问题中所做的那样。

2.使用open-uri将url解析为有效的URI。

您必须在控制器开始时要求库'open-uri''JSON'

代码语言:javascript
复制
require 'open-uri'
require 'JSON'

    def create
    @child = Child.new child_params
    @child.user = current_user
    @child.save
    origin = @child.adress
    destination = @kiga.adress
    
    # Parse the string url into a valid URI
    url = URI.parse(
        "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" \
        "#{@child.adress}&destinations=#{@kiga.adress}&key=XYZ"
    )
    # Open the URI just like you were doing
    response = open(url).read
    # Parse the string response in JSON format
    result = JSON.parse(response)

    # Extract the distance value in meters
    relations.distance = result["rows"].first["elements"].first["distance"]["value"]

    respond_to do |format|
        if @child.save
            format.html { redirect_to @child, notice: 'Child was successfully created.' }
            format.json { render :show, status: :created, location: @child }
        else
            format.html { render :new }
            format.json { render json: @child.errors, status: :unprocessable_entity }
    end
end

变量result的内容(解析后)如下所示:

代码语言:javascript
复制
{"destination_addresses"=>["Destination address"], "origin_addresses"=>["Origin address"], "rows"=>[{"elements"=>[{"distance"=>{"text"=>"15.4 km", "value"=>15405}, "duration"=>{"text"=>"17 mins", "value"=>1001}, "status"=>"OK"}]}], "status"=>"OK"}

如果采用HTTParty方式或open+ JSON解析方式,请确保检查响应状态代码。这两种方法都在我的计算机上进行了本地测试,并取得了成功的结果。

希望能帮上忙,干杯!

票数 3
EN

Stack Overflow用户

发布于 2018-02-22 23:46:28

另一种解决方案是查看这个Gem https://github.com/alexreisner/geocoder

如果你对你的孩子模型和基加模型进行地理编码,那么你可以很容易地从一个模型到另一个模型。

代码语言:javascript
复制
enter code here

这不需要进行任何API调用,GEM会为您执行此操作。

它也有一个非常方便的方法来返回附近的记录。

代码语言:javascript
复制
@kiga.near(@child.coordinates, 10)

将返回所有具有10公里@child坐标的基加

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48931948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档