© Jeffrey Linwood 2020
J. LinwoodBuild Location Apps on iOS with Swifthttps://doi.org/10.1007/978-1-4842-6083-8_13

13. Working with Datasets in Mapbox Studio

Jeffrey Linwood1 
(1)
Austin, TX, USA
 

Using Mapbox Studio, we can add large datasets to our maps as new layers. In this chapter, we will build on top of the custom map style we created in Chapter 12. Once we load in the dataset, we can view it in the map view without changing anything. We’ll also see how to retrieve the underlying data features when a user interacts with the map.

This chapter uses the project we created in Chapter 12 with Mapbox Studio as a base. If you have not created the custom map style, and displayed in the map view, go ahead and follow those directions.

Earthquake map

This project involves collecting GeoJSON data about earthquakes, uploading that data as a dataset into Mapbox Studio, and then creating a tileset from the data. When we have a tileset, we can style the appearance of the data in Mapbox Studio, including increasing the size of the data point on the map to match the magnitude of the quake. Then we can display the data in our app and detect when a user taps on one of the earthquakes. When we are done with the project, we should have an app that looks like Figure 13-1.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig1_HTML.jpg
Figure 13-1

Earthquake data points in the app

Let’s get started with the first step and collect the data we need to show on our map.

Downloading the earthquake data

The earthquakes’ dataset we are using for visualization comes from the United States Geological Survey (USGS) . If you are curious and want to learn more about earthquake monitoring and research, visit their website at www.usgs.gov/natural-hazards/earthquake-hazards.

You can also visit https://earthquake.usgs.gov/earthquakes/map/ to find a map of earthquakes, refreshed frequently from the server. We will be creating something similar, but with historical earthquake data.

The Earthquake Catalog, which can be accessed at https://earthquake.usgs.gov/fdsnws/event/1/, lists all of the different APIs supported by the Earthquake Hazards Program. For our purposes, we are interested in querying historic earthquake information and then returning the results as GeoJSON. GeoJSON is a data encoding format for geographic features, including points, lines, and polygons, along with any associated properties.

The URL we will use to download the data is
https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2020-01-01&endtime=2020-01-02
We specify the start time as January 1, 2020, and the end time as January 2, 2020. We also request GeoJSON back from the server, instead of XML, CSV, or another format. You will see a large GeoJSON file, with 610 different features. Listing 13-1 contains an edited sample of the JSON file, with only one feature and only two of its properties.
{
  "type": "FeatureCollection",
  "metadata": {
    "generated": 1587256320000,
    "url": "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2020-01-01&endtime=2020-01-02",
    "title": "USGS Earthquakes",
    "status": 200,
    "api": "1.8.1",
    "count": 610
  },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "mag": 1.3,
        "title": "M 1.3 - 38km SE of Tanana, Alaska"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -151.59520000000001,
          64.892200000000003,
          2.5
        ]
      },
      "id": "ak02021ksej"
    }
  ],
  "bbox": [
    -179.2752,
    -53.0907,
    -1.75,
    175.8577,
    69.6006,
    392.48
  ]
}
Listing 13-1

Sample of GeoJSON response for earthquake API query

Make the API call, and then download the results to a GeoJSON file – try using a web browser or the curl command. The GeoJSON file is also included in the downloadable source code for the book, in Chapter 13 folder. Feel free to try other date ranges with the API, if you like. For this particular project, we will be using the mag property (the magnitude of the earthquake), so other GeoJSON sources may not be an exact match for the process. The concepts used here would translate well to other projects, however.

We will take the list of earthquakes that we just downloaded and then upload them to Mapbox Studio next.

Creating a dataset on Mapbox Studio

Mapbox Studio lets you save and edit collections of GeoJSON features in the cloud, such as the earthquake data we just downloaded. These datasets can be turned into tilesets, which then may be edited in the Mapbox Studio style editor we used in Chapter 12. We will go through this entire process, from uploading a dataset to styling the features in the editor.

Let’s start by creating a dataset on Mapbox Studio. Visit the Datasets page (Figure 13-2) on Mapbox Studio (https://studio.mapbox.com/datasets/), or click the Datasets link in the upper right-hand corner. You will see any datasets you have already created or the option to upload a new dataset.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig2_HTML.jpg
Figure 13-2

Mapbox Studio Datasets web page

Clicking the large blue New dataset button will pop up a dialog box offering the option of either creating a blank dataset or uploading a GeoJSON file. Choose Upload in the tab bar of the dialog box (Figure 13-3).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig3_HTML.jpg
Figure 13-3

Upload a new dataset to Mapbox Studio

Select the GeoJSON file you downloaded in the previous section of this chapter, and then upload it. Mapbox Studio will process the file and find all of the GeoJSON features (Figure 13-4).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig4_HTML.jpg
Figure 13-4

Confirm dataset upload to Mapbox Studio

If the number of features Mapbox found matches the number of features you would expect to see in your GeoJSON file, click the Confirm button. You may name your dataset to be whatever you like, but the default will be the name of the file you uploaded. In our case, that would be Earthquake2020-01-01. If that name works, click the Create button.

Mapbox Studio will import the features, and you will see a confirmation message, similar to the following dialog box in Figure 13-5.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig5_HTML.jpg
Figure 13-5

Dataset upload confirmation dialog box

If you start editing the dataset, you will see the dataset plotted against a simple map background (Figure 13-6). You can select any of the points in the dataset and either inspect or modify the data.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig6_HTML.jpg
Figure 13-6

Dataset editor showing an earthquake point

In our case, we are using clean data from the API, so we do not need to inspect the data for anomalies or to clear up missing values. We can also take a quick glance at the data and see if the dataset we just imported makes sense and matches where we would expect to see data points.

This dataset imported correctly, and we can create a tileset from this dataset. The difference between a dataset and a tileset is that we will be able to modify how the data appears in the map in a tileset, instead of editing the data values in the the dataset.

Click the blue Mapbox icon in the upper left-hand corner to go back to the Datasets screen (Figure 13-7) or navigate to https://studio.mapbox.com/datasets/ in your web browser. Select the three-dot pop-up menu next to the earthquake dataset you just uploaded, and then choose View details from the pop-up menu.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig7_HTML.jpg
Figure 13-7

Pop-up menu to view details for a dataset

The dataset details screen that appears in Figure 13-8 allows you to export this dataset to a tileset.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig8_HTML.jpg
Figure 13-8

Dataset details screen

In the next section, we will create a tileset. This tileset is what we use in the Mapbox Studio style editor to change the appearance of the data in the map.

Creating a tileset

From the details screen of a dataset, Mapbox Studio provides an easy way to create a tileset. Click the Export to tileset link in the right-hand column. A dialog box (Figure 13-9) appears asking if you want to export to a new tileset or to update a connected tileset.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig9_HTML.jpg
Figure 13-9

Export to tileset dialog box

We will export to a new tileset, so click that link. A text box will appear with a suggested name for the tileset (the same as the dataset). If that works, click Export, and then Mapbox will process the dataset into a tileset. After this conversion is complete, you will see that a connected tileset appears on the dataset details screen (Figure 13-10).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig10_HTML.jpg
Figure 13-10

Connected tileset along with processing notification on dataset details screen

If you click the tileset, you will get a preview of the data in the tileset, as it would be laid out on a map. This can be useful to make sure the dataset export processed correctly.

Our next step will be to add this tileset to the map style we created in Chapter 12. If you have not created a map style yet, go ahead and follow the directions in Chapter 12.

Adding the tileset to a style

We now need to open up our map style to add the tileset as a layer. Click the Styles tab in the upper right-hand corner of the web page or navigate to https://studio.mapbox.com/ to see the list of your styles. Choose the map style you created in the last chapter, and click it to enter the style editor.

In the style editor, choose the Layers tab in the left-hand sidebar. We need to add a new layer, so click the plus button in the upper right-hand side of the Layers tab. When the New layer window appears, a list of data sources will appear, including historical election results.

Type earthquake into the filter box, and you will see your tileset appear (Figure 13-11).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig11_HTML.jpg
Figure 13-11

Adding a tileset to the map style

Select the tileset in the search results window, and then zoom to a different part of the world that is tectonically active and has earthquakes, like Alaska. You will see the features from the GeoJSON we uploaded on your map, as in Figure 13-12. The green dots are for reference and are not how the tileset will initially display. They show that all of your data is going to display in the map – you can apply a filter that will not show certain data based on conditions. If a data point is filtered out, that data will appear as a red dot here.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig12_HTML.jpg
Figure 13-12

Added a tileset to the map studio, showing features as green dots

Now that we have added the tileset, we can change the way it displays in any map that uses this style.

Styling the features with Mapbox Studio

On the layers sidebar, find the earthquake tileset you just added. Click it, and you will see a layer style editing palette appear as a window (Figure 13-13).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig13_HTML.jpg
Figure 13-13

Default tiles for the earthquake layer

It may be hard to see, but each data point on the map is being shown as a 5 pixel circle, with a black fill, and no outline. This doesn’t provide very good contrast on a dark map, so let’s change the fill color (the property marked color). Select that color property, and a color picker appears. Choose a brighter color, such as red. You will immediately see your data points change color on the map, as in Figure 13-14, if you are looking at an area that had earthquakes.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig14_HTML.jpg
Figure 13-14

Data points with a red fill color

You can also change the stroke color and the stroke outline to give the data points even more contrast. Try setting the stroke color to the hexadecimal color value ece9e9 and adjusting the stroke width to 1 pixel. You can also choose your own colors here too, if you like; it won’t affect the project.

Next, let’s try and convey some information about the magnitude of the earthquake with the radius of the circle we use to display the point. Mapbox Studio lets you vary properties of the map style with the properties for each feature of the map. Select the radius, and then select the link that says Style across data range. You will see a data field chooser pop up that lets you find a numeric data field. Look for the mag data field, which is short for magnitude (Figure 13-15).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig15_HTML.jpg
Figure 13-15

Choosing the magnitude data field to vary the radius field

After choosing the magnitude field, you will have several options appear to vary the radius. We are going to do a simple linear interpolation between the lowest magnitude, with 5 pixels, and the largest magnitude with 15 pixels.

Figure 13-16 shows the radius setting for the circle, after choosing to style across the data range with the magnitude field.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig16_HTML.jpg
Figure 13-16

Editing the radius data settings for the earthquake data

This settings view can be somewhat confusing. There are two stops for a linear interpolation of the magnitude data point – the lowest value, at –0.5, and the highest value, at 5.4. Both have a circle radius of 5 pixels, so there is no variation.

What we want to do is to leave the lowest setting alone and change the highest value. Click the bottom value, 5.4, and then change the circle radius to 15 px, as in Figure 13-17. You will see the line chart immediately start to show the radius value rising from left to right. Do not modify the value with the slider that you see – unless you want to change one of the stop values.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig17_HTML.jpg
Figure 13-17

Adjusting the radius to vary with the magnitude linearly

Be sure to click Done to save the changes to the radius. You could add more stops here, in case you want to set the radius for an intermediate value.

You could also change the other values, such as color or stroke size to vary with magnitude, or one of the other properties in your dataset. Feel free to experiment with this.

Now, let’s publish our map style changes. Click the large blue Publish button in the upper right-hand side of the screen, as shown in Figure 13-17. After clicking Publish, a dialog box will appear to let you confirm your changes with a visual display of the differences (Figure 13-18).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig18_HTML.jpg
Figure 13-18

Publishing changes to the map style

You can see your data additions in this dialog box, with the new map styles you applied. If everything looks good, click Publish, and your changes will be live for any websites or mobile apps that use this map style. If you would like to publish a new version of this map style, for instance, to avoid changing the look and feel for existing users, you can do that as well through this dialog box.

You will get a nice confirmation message about your style being successfully published (Figure 13-19).
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig19_HTML.jpg
Figure 13-19

Publish confirmation message for map styles

We can now leave Mapbox Studio and open up Xcode to see our changes in the app.

Displaying the dataset in the app

Running the app from Chapter 12 should display the map style you just edited, with the earthquake data points. No code changes should be needed. If you do not see the earthquake data, make sure you published the map styles in Mapbox Studio, and you are viewing a part of the world that has earthquakes.

The following code snippet will show much of the state of Alaska in your map:
mapView.centerCoordinate = CLLocationCoordinate2D(
            latitude: 61.2,
            longitude: -149.9)
mapView.zoomLevel = 3
You may also want to double-check that your application is setting the map style correctly with the styleURL property . Your map’s style can be found from the Mapbox Studio home screen by clicking the pop-up menu next to the style and copying the style URL found there:
mapView.styleURL = URL(string: mapStyleURI)
After running your app in the Simulator, you should see something similar to Figure 13-20.
../images/485790_1_En_13_Chapter/485790_1_En_13_Fig20_HTML.jpg
Figure 13-20

Earthquake data points in the app

While these data points are not map markers like we used in Chapter 11, they are features we can detect when a user taps on the map. For the final part of this project, let’s print some information on the console when a user taps on a data point.

Detecting a tap on the features

To do something when a user taps on the map, we need to add a standard UIKit tap gesture recognizer to the map view. The MGLMapView class already has several tap recognizers that it uses to detect user input for map operations like scrolling and zooming. We need to add a tap gesture recognizer, and only have it do something if the built-in tap gesture recognizers do not handle the tap. This is a common pattern for Mapbox map views and not limited to the use case of detecting taps for data features.

Add the method in Listing 13-2 to your ViewController class, and then call the addGestureRecognizer() function from the view controller’s viewDidLoad() method.
func addGestureRecognizer() {
  let tapGR = UITapGestureRecognizer(target: self,
      action: #selector(mapTapped(sender:)))
  for recognizer in mapView.gestureRecognizers!
      where recognizer is UITapGestureRecognizer {
      tapGR.require(toFail: recognizer)
  }
  mapView.addGestureRecognizer(tapGR)
}
Listing 13-2

Adding a tap gesture recognizer to the map view

The tap gesture recognizer will call a method named mapTapped(sender:)) that we also need to implement. When the map is tapped, we will ask the map view to identify any features at that point, and then we will list them to the console. You can also ask the map view to only show you features in a certain layer or layers, if you want.

The mapTapped(sender:)) method will need an @objc annotation for the selector to work. The implementation of this method will look like Listing 13-3.
@objc func mapTapped(sender: UITapGestureRecognizer) {
  let mapPoint = sender.location(in: mapView)
  let features = mapView.visibleFeatures(at: mapPoint)
  print(features)
}
Listing 13-3

Looking up visible map features when a user taps the app

Add the preceding method to the app, and then run the app. Be sure to add a call to addGestureRecognizer() in your viewDidLoad() method as well. When you tap on one of the earthquake circles, you will see the properties of the feature output on the console in Xcode.

Conclusion

This is the simplest possible implementation here – we could easily extend this out to update labels in an in-app UI (such as a bottom toolbar) with information about the data point, for instance. The earthquake data features returned by the map would be MGLPointFeature objects. If we had uploaded GeoJSON data with polylines or polygons, those would have been other classes that implement the MGLFeature protocol, such as MGLPolylineFeature or MGLPolygonFeature.

This was a fairly involved project, but I hope you enjoyed working with some real data and building out a visualization using the Mapbox Studio.

In our next chapter, we step away from Mapbox Studio and turn our attention to providing driving directions with Mapbox. We will create an app that provides a turn-by-turn directions user experience with the Mapbox Navigation framework.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.125.7