SwiftUI-Dynamically pass location info to map.

Erik Kuipers
2 min readApr 2, 2021
Photo by Ruthie on Unsplash

Task: Display around 300 pointers on a map that are to be read from a server using SwiftUI.

After doing my fair share of Googling and testing, I still to today haven’t found a good solution for this, how hard can it be to download and ID, Latitude and Longitude information from a JSON file and plot that as pointers on a map, in the current version of SwiftUI (2.0) it doesn’t seem to be possible, if it is, i’d like to hear from you!

Take any SwiftUI Map tutorial, they all use hardcoded information or a local stored JSON file with the location information, or they use a non 100% SwiftUI solution. So how do I solve the fact my information needs to be read from a server and then display that information on the map?

I have come up with the following solution, probably it’s not the best but so far it seems to be working, with up to 500 unique pointers.

tl;dr: I download the ID, Latitude and Longitude information, saved that in a locally created JSON file and then used that file to parse the pointer information, and it works perfectly.

Up on writing this document I am not allowed yet to share any specific code in the open, I am under a strict data discloser contract, however I can help you if needed.

Steps I took to get it working:

  1. Make a connection to the backend.
  2. Parse the needed information and then (using a string append solution) write the data to a local saved json document.
  3. Make sure you have a location model created.
  4. Created a ObservableObject to fetch and decode your local stored JSON file.
  5. Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: fetcherForlonlat.fetchlatlon, annotationContent: { item in MapAnnotation(coordinate: item.location)

Again I can’t show more code, but always available to give a hand and if you have a better solution getting this to work I will like to hear from you. I hope Apple will give us better options to solve this issue when we get SwiftUI 3.0.

Happy coding!

--

--

Erik Kuipers

Developer and UI/UX designer with focus on Mobile Apps