##Point in Polygon:
## sketch to test in point is within polygon, if so return and plot

setwd("X:/Claire/Lobster")
library(rgdal)
## Loading required package: sp
## rgdal: version: 0.9-2, (SVN revision 526)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
## Path to GDAL shared files: C:/Program Files/R/R-3.1.3/library/rgdal/gdal
## GDAL does not use iconv for recoding strings.
## Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
## Path to PROJ.4 shared files: C:/Program Files/R/R-3.1.3/library/rgdal/proj
library(sp)
##point in polygon

lobs <- readOGR(dsn="LobsterManagementAreas.shp",layer = "LobsterManagementAreas")
## OGR data source with driver: ESRI Shapefile 
## Source: "LobsterManagementAreas.shp", layer: "LobsterManagementAreas"
## with 60 features
## It has 3 fields
########
##note: in this exmample, the object "cent" will substitute
## for the coordinates from input$long and input$lat

## Get Centroids from lobster data for test
cent <- data.frame(coordinates(lobs)) 
cent$id <- 1:60
colnames(cent) <- c("x", "y", "id")
coordinates(cent) <- c("x", "y")
proj4string(cent) <- proj4string(lobs)

cent <- cent[1:1,]

inside <- !is.na(over(cent, as(lobs, "SpatialPolygons")))

cent$id <- over(cent, lobs)$ET_ID

lobsout <- subset(lobs, lobs$ET_ID==cent$id)

plot(lobsout, axes=TRUE)
plot(cent, add=TRUE)

###leaflet example
library(leaflet)

leaflet() %>%
  addTiles('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
           options = providerTileOptions(noWrap = TRUE)) %>%
  addTiles('http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/Mapserver/tile/{z}/{y}/{x}',
           options = providerTileOptions(noWrap = TRUE)) %>%
  
  #setView(-81.41, 26.15, zoom = 8) %>% 
  addPolygons(data=lobs, stroke=FALSE, smoothFactor=0.2, fillOpacity=1.0,
              color="yellow") %>% 
  addPolygons(data=lobsout, stroke=FALSE, smoothFactor=0.2, fillOpacity=1.0,
              color="red")