2016-07-14 1 views
2

은 루비 엔드 포인트 사용자에지리적 쿼리 나는이 기능 <code>query.by_distance</code><code>by_distance</code> 등이 루비에서

def_dataset_method(:by_distance) do |from, meters| 
    point = Geocoding.as_point(from) 
    query = "ST_DWithin(location, ST_SetSRID(ST_Point(?, ?), 4326)::geography, ?)" 
    where(query, point.lng, point.lat, meters) 
    end 

같은 대부분 도시의 이름입니다 is_near_to이다이 개 값을 전달입니다 또는 국가를 통해 Geecoding이 포인트를 얻고 있으며이 값이 within_distance인데 distance 안에 카메라를 가져 오는 데는 meters입니다.

위가 루비에서 발생합니다. 그것을 복제 비약에 뭐하는 거지

defmodule EvercamMedia.Geocode do 

    def fetch(address) do 
    response = HTTPotion.get "http://maps.googleapis.com/maps/api/geocode/json?address=#{URI.encode(address)}&sensor=false" 

    {:ok, results} = Poison.decode response.body 

    get_in(results, ["results", Access.all(), "geometry", "location"]) 
    end 
end 

이 지금은 같은 시나리오를 가지고 위도 긴 뭐하는 거지 뭔가를 얻기를 위해

def by_distance(query, is_near_to, within_distance) do 
    [%{"lat" => lat, "lng" => lng}] = fetch(is_near_to) 
    latitude = lat 
    longitude = lng 
    query 
    |> where([cam], st_dwithin(cam.location, st_set_srid(st_point_from_text(^"#{latitude},#{longitude}"), 4326), ^within_distance)) 
    end 

입니다. 나는 is_near_towithin_distance 두 값을 가지고있다. 그러나 우리가이 프로젝트에서 geo을 사용하고있는 것과 같은 질문을 똑같은 방식으로 복제 할 수 있다는 점을 완전히 인식하지 못하고 있습니다. 분명히 가능하지만 문서 작성 방법이 없습니다.

답변

1

이것은 내가하고있는 응용 프로그램의 일부입니다. 필요한 부분을 수행한다고 생각합니다. 단편을 사용하여 ST_distance_sphere 호출을 postgis에 직접 전달합니다. 뷰에서 제어기

def near_by(conn, %{"latitude" => latitude, "longitude" => longitude, "distance" => distance}) do 
    point = %Geo.Point{coordinates: {String.to_float(latitude), String.to_float(longitude)}, srid: 4326} 
    places = Place 
    |> Place.near_by(point, String.to_float(distance)) 
    |> Repo.all 
    render(conn, "near_by.json", places: places) 
end 

에서 모델

def near_by(query, point, distance) do 
    from place in query, 
    where: fragment("ST_distance_sphere(?,?)", place.location, ^point) >= ^distance, 
    order_by: fragment("ST_distance_sphere(?,?)", place.location, ^point), 
    select: {place, fragment("ST_distance_sphere(?,?)", place.location, ^point)} 
end 

에서 라이브러리 https://github.com/bryanjos/geo 및 PostGIS와

사용

def render("near_by_place.json", %{place: place}) do 
    { place, distance } = place 
    {lat, lon} = place.location.coordinates 
    %{id: place.id, 
    name: place.name, 
    latitude: lat, 
    longitude: lon, 
    distance: distance} 
end 
관련 문제