R/search_by_latlng.R

library(httr)
library(jsonlite)

search_lat_lng_api_call<- function(lat,lng)
{
  lat_lng <- paste(lat, ",", lng, sep = '' )
  request<- httr::GET("https://maps.googleapis.com/maps/api/geocode/json",
                      query = list(latlng = lat_lng,
                                   key = "AIzaSyCmwT443TY3ahX3eRskb4h_FPgaoVTR6EM"
                      ),
                      encode = "json"
  )
  r <- jsonlite::fromJSON(httr::content(request, "text"))
  return (r)
}
luid<- "samza595 and rabsh696"
name<- "saman zahid & rabnawaz jansher"

#' @title Google Place Search by lat lng
#' @name  search_by_latlng
#' @param lat i.e is latitdue is the double type numeric value
#' @param lng i.e is lngitutde is the double type numeric value
#' @return result dataframe response
#' @description search place by latitude and longitude api integration where you can get the location of any place by its latitude and longitude using geocoding api
#' @references \url{https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding}
#' @export


search_by_latlng<- function(lat,lng)
{
  if(!is.numeric(lat) || !is.numeric(lng) || !is.double(lat) || !is.double(lng) )
  {
    stop()
  }
  response <- search_lat_lng_api_call(lat,lng)

  if(response$status  == "OK")
  {
    result <- parse_lat_lng_response(response)
    return(result)
  }
  else if(response$status == "ZERO_RESULTS")
  {
    return("No match result found")
  }
  else if(response$status == "REQUEST_DENIED")
  {
    return("Api key expried Contact package owner")
  }
  else if(response$status == "OVER_QUERY_LIMIT")
  {
    return("your request limit is has been exceed")
  }


}


parse_lat_lng_response<- function(response)
{

  len <- length(response$results$place_id)
  place <- c()
  i<- 1
  for(x in response$results$address_components)
  {
    place[i] <- x[1]$long_name[1]
    i<- i + 1
    if(i > len) break
  }
  i <- 1
  type <- c()
  for(x in response$results$types)
  {
    type[i] <- x[1]
    i<- i +1
    if(i > len) break
  }


  result <- data.frame(
                       lat= response$results$geometry$location$lat,
                       lng = response$results$geometry$location$lng,
                        place = place,place_type= type,
                       address = response$results$formatted_address
  )
  return(result)
}
rjkhan/RCourse-lab5 documentation built on May 21, 2019, 2:26 a.m.