Problem in positioning the location points in google map using R - r

I am facing problem in creating map. I have downloaded a shape file from-
location link: "https://data.humdata.org/dataset/80920682-bbb5-421e-b7ac-f89b7b640a5c/resource/c545d196-bc2c-44ed-9028-316ab080a41c"
zip file link: https://data.humdata.org/dataset/80920682-bbb5-421e-b7ac-f89b7b640a5c/resource/c545d196-bc2c-44ed-9028-316ab080a41c/download/bgd_poi_healthfacilities_lged.zip
After extracting the data I have found a shape file. I am trying to plot this shape file in google map using R code. But It is not showing anything?
library(maptools)
library(ggmap)
counties.mpl <- readShapePoints("bgd_poi_healthfacilities_lged")
#Coordinates looks like:
counties.mpl#coords
coords.x1 coords.x2
0 531533.8 2524464
1 531004.7 2531410
2 533228.5 2525061
3 531723.1 2488972
4 532347.8 2492098
5 518104.8 2520361
#map code:
mymap <- get_map(location="Bangladesh", zoom=6)
ggmap(mymap)+
geom_point(data=counties.mpl#coords,
aes(x=counties.mpl#coords[,1], y=counties.mpl#coords[,2]))
Could anybody please help me to solve this? Thanks in advance.

As the others have noted, your shapefile uses a different coordinate system, & you'll need to transform it to lat / lon before the geom_point() layer can sit nicely over mymap.
Your shapefile's .prj file begins with:
PROJCS["BangladeshTM WGS1984",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984", ...
The link here explains what each part means, but for our purpose, you just need to know that the shapefile's projected coordinate system is "BangladeshTM WGS1984", i.e. Bangladesh Transverse Mercator, coded as EPSG:3106.
The typical lat / lon coordinate system that ggmap() expects is WGS 84, coded as EPSG:4326.
TLDR: Convert your data's projection from EPSG:3106 to EPSG:4326, and plot accordingly.
counties.mpl <- readShapePoints("bgd_poi_healthfacilities_lged")
# define current projection
proj4string(counties.mpl) <- CRS("+init=epsg:3106") # Bangladesh Transverse Mercator system
# remap to lat / long projection
counties.mpl.remapped <- spTransform(counties.mpl, CRS("+init=epsg:4326"))
# extract the coordinates as a data frame.
df <- as.data.frame(counties.mpl.remapped#coords)
colnames(df) <- c("lon", "lat")
# plot results
mymap <- get_map(location="Bangladesh", zoom=6)
ggmap(mymap) +
geom_point(data = df)

Related

The points of occurrence (gbif) and the maps don't coincide when i use worldclim data

i'm new in the R world and i'm trying to do a species distribution model, but when i plot my result, the points stay out from my map, i tried to change CRS but i didn't solve my problem, now i'll go to show you my code
library(dismo)
library(raster)
library(dplyr)
library(rnaturalearth)
Here i downloaded my species from gbif
gbif("Miniopterus", "schreibersii" , download=F)
minio<- gbif("Miniopterus", "schreibersii" , download=T) #you need 2 min approximately
i saw the basis of record and then i selected 2 different types
table(minio$basisOfRecord)
#Filter data minio----
minio<- minio%>%
filter(!is.na(lat))%>%
filter(!is.na(lon))%>%
filter(year>1980)%>%
filter(basisOfRecord %in% c("HUMAN_OBSERVATION", "OBSERVATION"))
class(minio)
nrow(minio)
i selected only longitude and latitude
miniogeo<-minio%>%
select(lon,lat)
head(miniogeo)
miniogeo$species<-1
head(miniogeo)
nrow(miniogeo)
And i created the coordinates and set the crs
coordinates(miniogeo) <-c("lon","lat")
crs(miniogeo) <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
proj4string(miniogeo) <- CRS("+init=epsg:4326")
Here start problems for me, i tried a lot of type of function for create a map but this is the most efficient (the most efficient of those functions I have found). I need to have a zoom of spain and portugal, and i need to exclude "Africa".
Europe <- ne_countries(scale="medium", type="map_units", returnclass="sf", continent="Europe")
Worldclim<-raster::getData('worldclim', var='bio', res=2.5)
Europe <- Europe %>%
dplyr::select(geometry,name_long) %>%
filter(name_long!='Russian Federation')
plot(Worldclim[[1]]) #or plot(worldclim$bio1)
plot(st_geometry(Europe))
points(miniogeo, cex=0.1)
envData<-crop(Worldclim, Europe)
EuropePred <- mask(envData, Europe) #we create a new raster without NA value
And here i plotted my points but, as you can see, my points went out of my map
plot(EuropePred[[1]]) #example
points(miniogeo, cex=0.2)
then i tried to do a zoom to Spain and Portugal.
extSpnPrt<-extent(c(-11,10,35,56))
miniogeo<-crop(miniogeo,extSpnPrt)
SpainPort<-crop(EuropePred,extSpnPrt)
plot(SpainPort$bio2)
points(miniogeo, cex=0.1)
There is someone that can understand my problem? i'm really really sorry, i tried a lot of time for undestand better but my level in R is so basics for now.
I say thank you to all that dedicate the time for read this. I hope you have a good day
This is the result of my map with only geometry and with worldclim data
enter image description here
One way to create a SpatialPointsDataFrame from your data.frame minio is:
coordinates(minio) <- ~ lon + lat
crs(minio) <- "+proj=longlat"
This is NOT correct:
coordinates(minio) <- c("lon", "lat")
Result:
plot(minio, cex=.5, col="red")
lines(as(Europe, "Spatial"))

Plotting UTM / Coordinates

I am new to R programming, I have a csv/excel file of 20 towns in a country which contains the in the below format,
Towns UTM Cordinates UTM Cordinaetes
xxxxxxxx 1377777 249514
yyyyyyyy 142145 228942
I am unable to plot them into a map, Does anyone have any idea of how t plot these UTM Cordinates.
Is it possible to plot towns in R programming with UTM? If so can anyone help me out here.
I have the shape file for the country with me as well. But I am not sure how to process.
myfilepath <- file.choose()
Cordinates<-read.csv(myfilepath,header=TRUE)
Cordinates
str(Cordinates)
library(rgdal)
library(sp)
library(data.table)
library(ggplot2)
library(tibble)
myfilepath <- file.choose()
Shapefile<-readOGR(myfilepath)
plot(Shapefile)
ggmap(Shapefile)+geom_point(aes(x=Easting,y=Northing,col=Cordinates))
Any help would be appreciated.
Here is a sf-solution, making use of all the hard work from #Dave2e to find the correct coordinate system used...
#convert to simple feature
library( sf )
mysf <- sf::st_as_sf( mydata, coords = c("Easting", "Northing"), crs = 29902)
#plot for visual inspection
mapview::mapview(mysf)
The trick is to determine the grid system used. After much searching the code for standard Republic of Ireland grid is epsg:29902
The first step is to transform the Irish grid coordinates to a standard latitude and longitude. This is accomplished with the "rgdal" library.
library(rgdal)
points <- read.table(header=TRUE, text = "Towns Easting Northing
Belclare 137777 249514
Carnmore 142145 228942")
#Pull out the location columns and rename
point <- points[,2:3]
names(point) <-c('x', 'y')
#convert to corrdinates and define initial coordinates systems
coordinates(point) <- c('x', 'y')
proj4string(point)=CRS("+init=epsg:29902") #29903 is the grid for Ireland
#Transform the Ireland's grid to longitude & latitude
coord<-spTransform(point,CRS("+init=epsg:4326"))
coord
This will transform your list of coordinates, please search this site on how to plot to a map. There are many options available.

Label a point depending on which polygon contains it (NYC civic geospatial data)

I have the longitude and latitude of 5449 trees in NYC, as well as a shapefile for 55 different Neighborhood Tabulation Areas (NTAs). Each NTA has a unique NTACode in the shapefile, and I need to append a third column to the long/lat table telling me which NTA (if any) each tree falls under.
I've made some progress already using other point-in-polygon threads on stackoverflow, especially this one that looks at multiple polygons, but I'm still getting errors when trying to use gContains and don't know how I could check/label each tree for different polygons (I'm guessing some sort of sapply or for loop?).
Below is my code. Data/shapefiles can be found here: http://bit.ly/1BMJubM
library(rgdal)
library(rgeos)
library(ggplot2)
#import data
setwd("< path here >")
xy <- read.csv("lonlat.csv")
#import shapefile
map <- readOGR(dsn="CPI_Zones-NTA", layer="CPI_Zones-NTA", p4s="+init=epsg:25832")
map <- spTransform(map, CRS("+proj=longlat +datum=WGS84"))
#generate the polygons, though this doesn't seem to be generating all of the NTAs
nPolys <- sapply(map#polygons, function(x)length(x#Polygons))
region <- map[which(nPolys==max(nPolys)),]
plot(region, col="lightgreen")
#setting the region and points
region.df <- fortify(region)
points <- data.frame(long=xy$INTPTLON10,
lat =xy$INTPTLAT10,
id =c(1:5449),
stringsAsFactors=F)
#drawing the points / polygon overlay; currently only the points are appearing
ggplot(region.df, aes(x=long,y=lat,group=group))+
geom_polygon(fill="lightgreen")+
geom_path(colour="grey50")+
geom_point(data=points,aes(x=long,y=lat,group=NULL, color=id), size=1)+
xlim(-74.25, -73.7)+
ylim(40.5, 40.92)+
coord_fixed()
#this should check whether each tree falls into **any** of the NTAs, but I need it to specifically return **which** NTA
sapply(1:5449,function(i)
list(id=points[i,]$id, gContains(region,SpatialPoints(points[i,1:2],proj4string=CRS(proj4string(region))))))
#this is something I tried earlier to see if writing a new column using the over() function could work, but I ended up with a column of NAs
pts = SpatialPoints(xy)
nyc <- readShapeSpatial("< path to shapefile here >")
xy$nrow=over(pts,SpatialPolygons(nyc#polygons), returnlist=TRUE)
The NTAs we're checking for are these ones (visualized in GIS): http://bit.ly/1A3jEcE
Try simply:
ShapeFile <- readShapeSpatial("Shapefile.shp")
points <- data.frame(long=xy$INTPTLON10,
lat =xy$INTPTLAT10,
stringsAsFactors=F)
dimnames(points)[[1]] <- seq(1, length(xy$INTPTLON10), 1)
points <- SpatialPoints(points)
df <- over(points, ShapeFile)
I omitted transformation of shapefile because this is not the main subject here.

Applying d3.js Density map of homicides example to own data fails

We tried to reproduce the beautiful example of bl.ocks.org/diegovalle/5166482, using d3.js and leaflet, but with our own data, which is on a regular lon-lat grid.
In R, we first retrieve the data from a mysql table, and write them to a shapefile:
lonmin <- -10; lonmax <- 10
latmin <- 30; latmax <- 50
dlon <- dlat <- 0.5
lon <- seq(from=lonmin, to=lonmax, by=dlon)
lat <- seq(from=latmin, to=latmax, by=dlat)
nlon <- length(lon); nlat <- length(lat)
# cl <- a mysql request
solRad <- matrix(cl$solRad, ncol=nlon, nrow=nlat)
# Plot the data
levels=seq(from=-40, to=1000, by=40)
filled.contour(solRad, x=lon, y=lat, levels=levels, col=col)
# Write a shapefile
require(maptools); require(rgdal)
writeOGR(ContourLines2SLDF(contourLines(lon, lat, solRad, levels=levels)),
"solRad.shp", "contours", "ESRI Shapefile")
You can look at the filled.contour output ![here] http://www.jonxion.ch/5166482/solRad.png. We then transform the shape file to a topojson file, which you can find by replacing the .png in the above link by .json.
Finally, we render it with D3.js and Leaflet, leading to this faulty result [here] http://www.jonxion.ch/5166482/
We browsed many tutorials and other examples without finding the cue to our problem. What are we doing wrong?
Might it be a d3.js limitation? We recognise that our data is more complex, but Diegovalle's data contains unclosed contours too (see its upper left corner). Would writing ContourPolygones instead of ContourLines solve our problem? Does such routines exist? Or, is there an alternative technique to d3.js? Thank's in advance for your help!

Plotting spatial data when two spatial objects have different CRS

I have a spatial polygon object and a spatial points object. The latter was created from xy latlong data vectors (called latitude and longitude, respectively) in a dataframe, while the former was simply read into R directly using rgdal. My code is as follows:
boros <- readOGR(dsn = ".", "nybb")
rats <- read.csv("nycrats_missing_latlong_removed_4.2.14.csv", header = TRUE)
coordinates(rats) <- ~longitude + latitude
At this point neither spatial object is projected. If I project these objects as follows:
proj4string(boros) <- CRS("+proj=lcc")
proj4string(rats) <- CRS("+proj=lcc")
Both objects are now projected, and both will successfully map with the plot() function as follows:
plot(boros)
plot(rats)
However when I try to plot them together:
plot(boros)
plot(rats, add = TRUE)
I get the first plot only, without the rats object superimposed over boros. However, and this is the big problem, I get NO error message, so I have been unable to determine where the disconnection is between these two spatial objects being able to speak to each other. Both commands run smoothly without error or warning, yet I am left with just the single plot. And when I check the projections of each object with proj4string() I get the same projection returned for each object.
I have now spent many, many hours over several days trying various ways of creating two spatial objects whose CRS and projections match such that they can be mapped together using plot(). Incidentally, one approach I took was to create a shapefile in ArcGIS for the rats object, which worked fine to create the file. But I am still left with the same inability of the two spatial objects to work together in R. I have tried many different projections for both objects, spTransform on both objects, nothing seems to work.
Any help would be most appreciated. I have also included a dropbox link with the 2 data files I have described above:
https://www.dropbox.com/sh/x0urdo6guprnw8y/tQdfzSZ384
So, as some of the comments point out, the problem is that your data and your maps have different projections.
It looks like your map comes from the NYC Department of City Planning. The shapefile is definitely not in WGS84 (longlat), but the CRS is not included in the file (which is very disappointing by the way...). Nevertheless, there is a metadata file which indicates that the shapefile is projected as EPSG 2263.
In order to make use of this in R we need a projection string. The idiomatic way to get this in R is:
library(rgdal)
EPSG <- make_EPSG()
NY <- with(EPSG,EPSG[grepl("New York",note) & code==2263,]$prj4)
NY
# [1] "+proj=lcc +lat_1=41.03333333333333 +lat_2=40.66666666666666 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000.0000000001 +y_0=0 +datum=NAD83 +units=us-ft +no_defs"
Now we can either take your map and reproject that into WGS84, or take your data and reproject that into the map CRS.
setwd("< directory with all your files >")
data <- read.csv("nycrats_missing_latlong_removed_4.2.14.csv")
# First approach: reproject map into long-lat
wgs.84 <- "+proj=longlat +datum=WGS84"
map <- readOGR(dsn=".",layer="nybb",p4s=NY)
map.wgs84 <- spTransform(map,CRS(wgs.84))
map.wgs84.df <- fortify(map.wgs84)
library(ggplot2)
ggplot(map.wgs84.df, aes(x=long,y=lat,group=group))+
geom_path()+
geom_point(data=data, aes(x=longitude,y=latitude, group=NULL),
colour="red", alpha=0.2, size=1)+
ggtitle("Projection: WGS84 longlat")+
coord_fixed()
# Second approach: reproject data
map.df <- fortify(map)
rats <- SpatialPoints(data[,c("longitude","latitude")],proj4string=CRS(wgs.84))
rats <- spTransform(rats,CRS(NY))
rats.df <- data.frame(coordinates(rats))
ggplot(map.df, aes(x=long,y=lat,group=group))+
geom_path()+
geom_point(data=rats.df, aes(x=longitude,y=latitude, group=NULL),
colour="red", alpha=0.2, size=1)+
ggtitle("Projection: NAD83.2263")+
coord_fixed()
No rats in Central Park?

Resources