Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/current location nearest station #13 #18

Merged
merged 12 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions apps/backend/src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { poweredBy } from 'hono/powered-by'
import { prettyJSON } from 'hono/pretty-json'
import { trimTrailingSlash } from 'hono/trailing-slash'
import type OpenAI from 'openai'
import type { Client } from 'openapi-fetch'
import type { paths } from './lib/odptApiPath'
import type { OdptClient } from './lib/odptApiPath'
import { aiMiddleware } from './middlewares/ai'
import { corsMiddleware } from './middlewares/cors'
import { odptClientMiddleware } from './middlewares/odptClient'
Expand All @@ -19,8 +18,8 @@ export type BindingsType = {
type VariablesType = {
aiModel: LanguageModel
openaiClient: OpenAI
odptClient: Client<paths>
odptChallengeClient: Client<paths>
odptClient: OdptClient
odptChallengeClient: OdptClient
}

type HonoConfigType = {
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { honoFactory } from './factory'
import { healthRoute } from './routes/health'
import { nearestStationRoute } from './routes/nearestStation'
import { speechRoute } from './routes/speech'
import { transcriptionRoute } from './routes/transcription'

Expand All @@ -9,6 +10,7 @@ const routes = app
.route('/health', healthRoute)
.route('/transcription', transcriptionRoute)
.route('/speech', speechRoute)
.route('/nearestStation', nearestStationRoute)

export type HonoRoutes = typeof routes

Expand Down
5 changes: 4 additions & 1 deletion apps/backend/src/lib/odptApiPath.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { paths } from 'odpt-openapi-generated'
import type { Client } from 'openapi-fetch'

const API_KEY_PROPERTY_NAME = 'acl:consumerKey' as const

Expand All @@ -23,4 +24,6 @@ type OmitApiKey<Path extends object> = {

type OmitApiKeyFromPaths = OmitApiKey<paths>

export type { OmitApiKeyFromPaths as paths }
type OdptClient = Client<OmitApiKeyFromPaths>

export type { OmitApiKeyFromPaths as paths, OdptClient }
40 changes: 40 additions & 0 deletions apps/backend/src/routes/nearestStation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { vValidator } from '@hono/valibot-validator'
import { array, object, pipe, string, transform, union } from 'valibot'
import { honoFactory } from '../factory'
import { locationSchema } from '../types/location'
import { stationUseCases } from '../usecases/stationUseCase'

const getReqQuerySchema = object({
lat: pipe(
union([string(), array(string())]),
transform((input) => {
const value = Array.isArray(input) ? input[0] : input
const parsed = Number(value)
if (Number.isNaN(parsed)) throw new Error('lat must be a number')
return parsed
}),
locationSchema.entries.lat,
),
lon: pipe(
union([string(), array(string())]),
transform((input) => {
const value = Array.isArray(input) ? input[0] : input
const parsed = Number(value)
if (Number.isNaN(parsed)) throw new Error('lon must be a number')
return parsed
}),
locationSchema.entries.lon,
),
})

export const nearestStationRoute = honoFactory
.createApp()
.get('/', vValidator('query', getReqQuerySchema), async (c) => {
const { lat, lon } = c.req.valid('query')
try {
const nearestStation = await stationUseCases.getNearestStation({ lat, lon }, c.var.odptClient)
return c.json({ station: nearestStation }, 200)
} catch (e) {
return c.json({ error: e }, 500)
}
})
8 changes: 8 additions & 0 deletions apps/backend/src/types/location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type InferOutput, maxValue, minValue, number, object, pipe } from 'valibot'

export const locationSchema = object({
lat: pipe(number(), minValue(-90), maxValue(90)),
lon: pipe(number(), minValue(-180), maxValue(180)),
})

export type Location = InferOutput<typeof locationSchema>
28 changes: 28 additions & 0 deletions apps/backend/src/usecases/stationUseCase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { OdptClient } from '../lib/odptApiPath'
import type { Location } from '../types/location'
import { calculateSphericalDistance } from '../utils/calculateSphericalDistance'

export const stationUseCases = {
getNearestStation: async ({ lat, lon }: Location, odptClient: OdptClient) => {
const maxSearchRadius = 4000

const { data: stations } = await odptClient.GET('/places/{RDF_TYPE}', {
params: { path: { RDF_TYPE: 'odpt:Station' }, query: { lat, lon, radius: maxSearchRadius } },
})
if (stations === undefined) throw new Error('Failed to fetch stations')

const nearestStation = stations?.reduce((nearest, current) => {
const nearestDistance = calculateSphericalDistance(
{ lat, lon },
{ lat: nearest['geo:lat'], lon: nearest['geo:long'] },
)
const currentDistance = calculateSphericalDistance(
{ lat, lon },
{ lat: current['geo:lat'], lon: current['geo:long'] },
)
return currentDistance < nearestDistance ? current : nearest
})
imoken777 marked this conversation as resolved.
Show resolved Hide resolved

return nearestStation
},
}
20 changes: 20 additions & 0 deletions apps/backend/src/utils/calculateSphericalDistance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { Location } from '../types/location'

const degreeToRadian = (degree: number) => degree * (Math.PI / 180)
const EarthRadiusKm = 6371

export const calculateSphericalDistance = (from: Location, to: Location): number => {
const deltaLatitude = degreeToRadian(to.lat - from.lat)
const deltaLongitude = degreeToRadian(to.lon - from.lon)

const a =
Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) +
Math.cos(degreeToRadian(from.lat)) *
Math.cos(degreeToRadian(to.lat)) *
Math.sin(deltaLongitude / 2) *
Math.sin(deltaLongitude / 2)

const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

公式か何かを使った複雑な計算は、コメントアウトで補足しておいたほうがわかりやすそう

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数に切り出してJSDoc的なの書いておきたさがある

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数分けるとよりわかりずらそうだったから関数にjsdocと途中計算にはコメントアウトにした
それでもよくわからないけど


return EarthRadiusKm * c
}
13 changes: 13 additions & 0 deletions apps/frontend/src/hooks/useCurrentLocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useEffect, useState } from 'react'

export const useCurrentLocation = () => {
const [currentGeolocation, setGeolocation] = useState<GeolocationPosition | undefined>()

useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
setGeolocation(position)
})
}, [])

return { currentGeolocation }
}
Loading