%% Plot Geographic Position Using GPS Connected to Host Computer
% Get the geographic location using the GPS receiver connected to the host computer on a specific serial port and plot the location in a map.
%% Required Hardware
% To run this example, you need:
% UBlox Neo-6M GPS module
% GPS antenna
% USB to UART module
% USB cable
% Connecting wires
%% Hardware Connection
%
% Connect the pins on the UBlox Neo-6M GPS module to the pins on your USB to UART module. The connections are:
% VCC - +5V
% RX - TXO
% TX - RXI
% GND - GND
% Connect the GPS antenna to the GPS module. Connect the USB to UART module to the host computer with a USB cable. GPS Fix can be easily acquired in locations that have a clear view of the sky. Wait for the GPS module to acquire satelite signals (Fix).This can be verified by checking the Fix LED (D1) of your GPS module.
%
%% Create GPS Object
% Create a gpsdev object for the GPS module connected to a specific port.

gps = gpsdev('COM4')

%% Read the GPS data
% Read the GPS data and extract latitude, longitude, and time from it. GPS returns UTC datetime. Convert it to system time zone.

[gpsData,~] = read(gps);
latitude = gpsData.LLA(1);
longitude = gpsData.LLA(2);
gpsTime = gpsData.GPSReceiverTime;
gpsTime.TimeZone = 'local';

%% Plot the position in a map along with the timestamp
% Plot the position in geographic axes with the data obtained from the GPS module. GPS should have fix to get valid values for latitude, longitude and gpsTime.
% If the GPS module does not have fix, the above commands give NaNs for latitude and longitude and NaT for gpsTime. In this case, make sure the antenna is exposed to clear sky and wait for some time and try the above steps again.

if(~isnan(latitude) && ~isnan(longitude))
 % plot the position in geographic coordinates
 fig = geoplot(latitude,longitude,'Marker',"o",'MarkerSize',6,'Color','red','MarkerFaceColor','red');

 % Sets the latitude and longitude limits of the base Map   
 geolimits([latitude-0.05 latitude+0.05],[longitude-0.05 longitude+0.05]) ;

 % Selects the basemap   
 geobasemap streets;
 timeString = strcat("Timestamp: ",string(gpsTime));

 % Create annotation and display time received from GPS
 annotation('textbox',[0.005 0.98 0.6 0.01],'FitBoxToText','on','string',timeString,'Color','blue','FontSize',10);
end

%% Clean Up
% When the connection is no longer needed, clear the associated object.

delete(gps);
clear gps;

% Copyright 2020 The MathWorks, Inc.