Adding data to geoscatter clicks

7 views (last 30 days)
Maddie Long
Maddie Long on 13 May 2022
Edited: Samya on 19 Jul 2023
Hi! I am using geoscatter to graph the counties in california. I would like the data when I click on the county display the county name and some other information as needed.
Is there a way to do this?
warning off
states = readgeotable('usastatehi.shp'); %
counties = shaperead('cb_2018_us_county_500k.shx'); %county shape file from cencus.gov
row = states.Name == 'California';
california = states(row,:);
% Extract the polygons in the .shp file
struct2poly = @(s) polyshape(s.X, s.Y);
p = arrayfun(struct2poly, states);
p2 = arrayfun(struct2poly, counties);
s = figure; hold on
geoshow(california)
plot(p)
plot(p2)

Answers (1)

Samya
Samya on 19 Jul 2023
Edited: Samya on 19 Jul 2023
Hi! To display additional information when clicking on a county in California, you can use the `datacursormode` function in MATLAB. Here's an example of how you can modify your code to achieve this:
% Load necessary shapefiles
states = readgeotable('usastatehi.shp');
counties = shaperead('cb_2018_us_county_500k.shx');
% Filter California state
row = states.Name == 'California';
california = states(row,:);
% Extract the polygons in the .shp file
struct2poly = @(s) polyshape(s.X, s.Y);
p = arrayfun(struct2poly, states);
p2 = arrayfun(struct2poly, counties);
% Plot the map
s = figure;
hold on
geoshow(california);
plot(p);
plot(p2);
% Enable data cursor mode
dcm_obj = datacursormode(s);
set(dcm_obj, 'UpdateFcn', @myUpdateFcn); % Set custom update function
Next, define the custom update function `myUpdateFcn` that will display the county name and other desired information when a county is clicked:
function txt = myUpdateFcn(~, event_obj)
% Get the clicked data point
pos = event_obj.Position;
% Find the corresponding county
county = counties(inpolygon(pos(1), pos(2), [counties.X], [counties.Y]));
% Extract desired information from the county structure
countyName = county.NAME; % Replace 'NAME' with the actual field name in the shapefile
% Construct the text to display
txt = {['County: ', countyName]};
end
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!