How to insert or update a feature inside a dataset using Unity
@Hey guys. I need some help on this point as the Unity documentation for mapbox is quite light and I can't find any examples in the main api documentation.
I'm trying to insert a feature in to an already existing dataset which I have created in my mapbox account. The documentation shows how to achieve this using javascript and cURL here: https://www.mapbox.com/api-documentation/?language=JavaScript#insert-or-update-a-feature
But I would like to know how to do this inside Unity. Could you give some advice on how to construct the http put request in unity or point to an example. The goal of the app is that users can add in messages at a specific point on a map and that data would then appear to any other user using the app.
Thanks for any help guys, Martin
PS, I've managed to pull down the information from a dataset and display is using the 3dPoi prefab. Next step is to allow data to be added from unity to the dataset:

By the way, Louis is my dog incase you noticed that test message at the bottom ;)
Hey again all. I tried this below:
IEnumerator PostNewDatasetFeature()
{
string postURL = "https://api.mapbox.com/datasets/v1/[myID]/[myDatasetID]/features/[myFeatureID]?access_token=[myAccessToken]";
string geoJSONstring = "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-2.3626667261123657,53.45663959042344]}}]}";
//string jsonStringTrial = JsonUtility.ToJson(Resources.Load("knowsleyRoad1"));
UnityWebRequest www = UnityWebRequest.Put(postURL, geoJSONstring);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("www error: " + www.error);
}
else
{
Debug.Log("www = " + www.downloadHandler.text);
}
}
But I get a 'Generic/unknown HTTP error' response from the return.
Any ideas what the issue could be? Thanks for any advice.
Martin
@cobaltplay Studio maintains a web cache for 10-15 minutes and there is an indicator to show when it's been updated. This might help you with a workaround.
Studio has an indicator to show when it has been updated. I also know that there is web -cache maintained for 15 minutes.
As for your http request, maybe @bergwerkgis can provide a little insight on how to formulate that the proper way for you use case. Thank you!
@cobaltplay First thing I see is that you are inserting a full GeoJSON.
The docs state:
This should be one individual GeoJSON feature and not a GeoJSON FeatureCollection.
If you change geoJSONstring accordingly it should work.
Let me know if it doesn't.
Edited above - accidentally commented too early 🙈
@ jordy-isaac, @BergWerkGIS , Thanks for the reply guys :) I tried adjusting the string to just be a Feature, but it still gives me the error message and doesn't update the dataset. Here's the new code:
IEnumerator PostNewDatasetFeature()
{
string postURL = "https://api.mapbox.com/datasets/v1/[myID]/[myDatasetID]/features/[myFeatureID]?access_token=[myAccessToken]";
string geoJSONstring2 = "{\"type\":\"Feature\",\"properties\":{\"name\":\"Null Island\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[-2.3626667261123657,53.45663959042344]}";
UnityWebRequest www = UnityWebRequest.Put(postURL, geoJSONstring2);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("www error: " + www.error);
}
else
{
Debug.Log("www = " + www.downloadHandler.text);
}
}
I've also created a new private token which includes write permissions to datasets. Is there any other permission it might need to solve the problem? Does the code above look ok to you?
Thanks again for the help guys Martin
Looking into it now ...
1st observation: Your code produces HTTP response code 400 which means Invalid request.
I've also created a new private token which includes write permissions to datasets. Is there any other permission it might need to solve the problem?
No, DATASETS:WRITE is enough.
You are missing a curly brace } at the end of geoJSONstring2 - add that and it should work now:

@BergWerkGIS - Works great, thanks for the help :) I was able to upload the dataset feature and see the changes in my account dataset editor.
I'm wondering now how can I see those changes within unity without needing to 'export' the dataset to a tileset. Because in the mapbox editor i need to save and then export the changes to see them applied in a tileset. Is there a way to access the dataset directly from unity and so no export is needed? At the moment I'm using the PoiGeneration example and using the PoiVectorTileFactory like this:

The 'testDataset1' is the name of the dataset Im applying the poi markers to.
- Could you give some advice on how to either apply the dataset directly to the tileset (export) without me needing to go in to the editor and clicking the 'export' button?
- Or could you give some advice on how to just access the dataset directly in unity and apply a poi marker to them in the scene.
Thanks again for the help, super useful :) Martin
@BergWerkGIS . About the question above. I saw the section in the API documentation here (https://www.mapbox.com/api-documentation/?language=cURL#create-an-upload). I've tried to do this in Unity. Instead of uploading to an AWS S3 bucket, I'm just trying to apply a dataset to a tileset. Updating the dataset works well now, but next step is to apply that dataset to a tileset so I can see the changes applied in Unity. Here's what I came up with so far but I get a www error: Generic/unknown HTTP error.
IEnumerator ApplyDatasetToTileset()
{
string postURL = "https://api.mapbox.com/uploads/v1/[my mapbox ID]?access_token=[my access token]";
string datasetTilesetInfo = "{\"tileset\":\"[my mapbox id].[ID of the tileset I want to update]\",\"url\":\"mapbox://datasets/[my mapbox ID]/[ID of the dataset I want to apply to the tileset]\"}";
UnityWebRequest www = UnityWebRequest.Put(postURL, datasetTilesetInfo);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("ApplyDatasetToTileset www error: " + www.error);
}
else
{
Debug.Log("ApplyDatasetToTileset www = " + www.downloadHandler.text);
}
}
I've tried a few different combinations of tileset name, tileset ID, dataset ID, dataset name because the docs mention name as opposed to ID for the tileset property field. But I still get the same error.
Can you see any errors with what I'm doing above, or let me know if this approach is completely wrong.
Thanks Best regards Martin
Hm, there's something weird going on within Unity and I'm still investigating ...
But, at first make sure
- you use
UnityWebRequest.Postinstead ofPut - your access token has
TILESETS:WRITEandUPLOADS:WRITEpermissions It might take a few minutes till permissions update after you change them
If I use the code below from within Unity I still get HTTP response code 400.
But if I Debug.Log the variables postUrl and datasetTilesetInfo and use those strings on the console via curl as described in the API docs it works.
IEnumerator ApplyDatasetToTileset()
{
string postURL = string.Format(
"https://api.mapbox.com/uploads/v1/{0}?access_token={1}"
, myId
, accessToken
);
string datasetTilesetInfo = string.Format(
@"{{""tileset"":""{0}.{1}"",""url"":""mapbox://datasets/{0}/{2}""}}"
, myId
, tilesetId
, datasetId
);
UnityWebRequest www = UnityWebRequest.Post(postURL, datasetTilesetInfo);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("ApplyDatasetToTileset www error: " + www.error);
}
else
{
Debug.Log("ApplyDatasetToTileset www = " + www.downloadHandler.text);
}
}
I've tried a few different combinations of tileset name, tileset ID, dataset ID, dataset name because the docs mention name as opposed to ID for the tileset property field. But I still get the same error.
The tileset name refers to the name you see here: https://www.mapbox.com/studio/tilesets/
If you are exporting to an existing tileset and use a different name in the name property of the JSON this will overwrite/update the existing name.
Tileset id and dataset id are the strings you get when you click on Menu.

Oh boy, there really seems to be a Unity bug, but I was able to crack that nut and hack it:
Solution:
- use
UnityWebRequest.Put - pass JSON as byte array
- but override it to
POSTviawww.method = "POST"later on
This code works for me:
IEnumerator ApplyDatasetToTileset()
{
string postURL = string.Format(
"https://api.mapbox.com/uploads/v1/{0}?access_token={1}"
, myId
, accessToken
);
string datasetTilesetInfo = string.Format(
@"{{""tileset"":""{0}.{1}"",""url"":""mapbox://datasets/{0}/{2}""}}"
, myId
, tilesetId
, datasetId
);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(datasetTilesetInfo);
// initialize as PUT
UnityWebRequest www = UnityWebRequest.Put(postURL, bytes);
www.SetRequestHeader("content-type", "application/json");
// HACK!!! override method and convert to POST
www.method = "POST";
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("ApplyDatasetToTileset www error: " + www.error);
}
else
{
Debug.Log("ApplyDatasetToTileset www = " + www.downloadHandler.text);
}
}
@BergWerkGIS - Thanks again for the quick feedback. It's working on my side, great :) I would never have figured out that hack. The only edit I made was to not include my user name in the tilesetId field because we already include that in the myId field. So I just needed to copy the part which came after my user name and the '.' in my mapbox account.
I've now been able to update the tileset from Unity and see the changes applied. Next step is to allow users to place markers around the map as they walk along with a message field. I don't think this should be too hard as the main functionality is already in place. I'll let you know how it goes or if I come across any other issues. Thanks for all the help so far man, you've been awesome :)
Martin
Great that is works for you too. Happy we solved this. 😄
Next step is to allow users to place markers around the map as they walk along with a message field.
Just remember that those markers will not appear instantaneously: Updating the dataset might take a few minutes as well as exporting dataset to tileset.
Another caveat to be aware of: our SDK features ambient caching of tiles per default. Tiles are only re-requested when the maximum cache size has been reached thus you might not see your updates at all. We are working on improving that and are aiming for a auto-refreshing cache for (hopefully) the next release.
Till then I can think of two different ways to approach your scenario:
1.
Go to Mapbox -> Setup -> Configuration in Unity Editor and set both
Mem Cache Size- and
MBTiles Cache Size
to 0:

Although that comes with the disadvantage that no tiles are cached at all, which might slow things down - especially for mobile users with bad connections.
2.
Expose a Refresh button in your app that clears caches on demand.
See here: https://github.com/mapbox/mapbox-unity-sdk/issues/212#issuecomment-323806314
If you have questions about that please open dedicated issues.
@BergWerkGIS - thanks for the advice. Yeah this was something I also considered as it takes a few minutes for the tileset to update.
I tried the 'Mapbox.Unity.MapboxAccess.Instance.ClearCache();' call from script but it never shows the 'deleting /Users/[name]/Library/Application Support/DefaultCompany/MapboxTest/cache/' debug like when I clear caches from the menu in Unity. So at the moment I'm stopping Unity and then clearing through the menu, then Playing again to see the changes. Is this a normal issue or do I just need to wait longer for the tileset to be updated?
For a 'refresh' / 'clear caches' button I'm thinking of doing it automatically every 1 minute so that eventually any new data in a tileset would be applied to the map in Unity.
Looking forward to the new release :)
Interesting that you don't see the deleting ... message because the menu item also calls Mapbox.Unity.MapboxAccess.Instance.ClearCache() - so it should be the same.
So at the moment I'm stopping Unity and then clearing through the menu, then Playing again to see the changes.
You don't have to stop Play Mode, you can clear caches "on the fly". Then you'd just have to pan away from your current location and back again: for the tiles to be discarded and re-requested.
@BergWerkGIS - I see. I'll give that a try. Will let you know how it goes.
Martin
@BergWerkGIS and all. So far so good. I changed both the cache settings to zero and I'm also calling 'Mapbox.Unity.MapboxAccess.Instance.ClearCache()' on start just to be sure. Its working well. I've added the ability to write a message wherever the user is located (geotagging I believe its called). Then I walk the transform away from the tile until it unloads, then walk back a few minutes later and the new dataset markers appear.

In order to get a unique feature name each time I've used the 'SystemInfo.deviceUniqueIdentifier' and 'System.DateTime.Now.ToString();'. This way its a unique feature in the dataset each time as opposed to overwriting an old one. I'm not sure if it will continue this way as I'm not yet clear on what the app will do but the foundation is getting there.
Do you know if there's a manual way to get an updated dataset for a tile without needing to unload and reload the tilemap by walking away?
Thanks again, let me know if there's anything I can share guys. Martin
For checking if a tileset has been updated you could poll the TileJSON metadata API
https://www.mapbox.com/api-documentation/#retrieve-tilejson-metadata
and check the Modified property (it is null if the tileset hasn't been modified since it's creation).
The TileJSON wrapper is not yet merged into the SDK but you could carry over the new files and the changes (MapboxAccess.cs & UnixTimestampUtils.cs) to your project from this PR: https://github.com/mapbox/mapbox-unity-sdk/pull/493
using Mapbox.Platform.TilesetTileJSON;
MapboxAccess.Instance.TileJSON.Get(
"<YOUR_TILESET_ID>"
, (TileJSONResponse response) =>
{
if(response.Modified.HasValue){
{
// check against previous modified date and update if necessary
}
}
);
For in place updating of loaded tiles in Unity you could add and expose something like this in the factory your are using and call it after checking the tilesets metadata (TileJSON). Should work - haven't tested though.
@BergWerkGIS - thanks for the details, i'll give this a try soon. I've been looking in to the in-place loading more. At the moment I'm checking the DynamicZoom scene too so that users can navigate anywhere on the map to see markers. It looks all the necessary parts are there its just a case of putting them together in a single scene.
By the way, in the new unity sdk (ver 1.3) does it include in-place reloading already?
Thanks again Martin
@cobaltplay
By the way, in the new unity sdk (ver 1.3) does it include in-place reloading already?
No, SDK 1.3 doesn't have that yet.
Currently working on it in this branch: https://github.com/mapbox/mapbox-unity-sdk/tree/auto-cache-refresh
Highly experimental at the moment and it's probably going to take a few more weeks till we get it merged into develop.
