marcusyoung / opentripplanner

An API wrapper for OpenTripPlanner (OTP) as an R package
11 stars 5 forks source link

Create A Generic "Plan Route" Function #12

Closed mem48 closed 5 years ago

mem48 commented 6 years ago

Is your feature request related to a problem? Please describe. The first part of the otpTripDistance and otpTripTime are the same as would any other function that uses the /plan API.

Describe the solution you'd like To avoid code duplication I suggest an internal function that covers just the connecting and retrieving of raw data, and error handling. Then otpTripDistance etc are wrappers that change the output at the R end. The function can then handle all the different variables that the user may wish to pass the OTP API, and that will greatly simplify the writing of all the other functions.

E.g.

otpTripDistance(otpcon, from, to, modes)

Only supports the bare minimum of options, but with an internal function we could have

otpTripDistance(otpcon, from, to, modes, ... )

Where ... is any valid OTP API parameter that the user wishes.

Describe alternatives you've considered None

Additional context

Simple Example: Basically just otpTripTime with some bits stripped out, but we would add all the variables you can think of.

otpPlanInternal <-
  function(otpcon,
           from,
           to,
           modes,
           detail = FALSE,
           date,
           time,
           maxWalkDistance = 800,
           walkReluctance = 2,
           arriveBy = 'false',
           transferPenalty = 0,
           minTransferTime = 0)
  {
    # convert modes string to uppercase - expected by OTP
    modes <- toupper(modes)

    routerUrl <- paste(otpcon, '/plan', sep = "")

    req <- GET(
      routerUrl,
      query = list(
        fromPlace = from,
        toPlace = to,
        mode = modes,
        date = date,
        time = time,
        maxWalkDistance = maxWalkDistance,
        walkReluctance = walkReluctance,
        arriveBy = arriveBy,
        transferPenalty = transferPenalty,
        minTransferTime = minTransferTime
      )
    )

    # convert response content into text
    text <- content(req, as = "text", encoding = "UTF-8")
    # parse text to json
    asjson <- jsonlite::fromJSON(text)

    # Check for errors - if no error object, continue to process content
    if (!is.null(asjson$error$id)) {
      # there is an error - return the error code and message
      response <-
        list("errorId" = asjson$error$id,
             "errorMessage" = asjson$error$msg)
      return (response)
    }else{
      return (asjson)
  }
marcusyoung commented 6 years ago

Ok, so if I understand correctly, there would be a function otp_trip_distance(), for example, which would first call otp_plan_internal() which would return the json, and then otp_trip_distance() would do the necessary parsing of the returned json to return the distance in km?