Topic: Setting access token when changing mapType dynamically

Hi ! I just got this asset yesterday, and it's pretty great.

However, I've got a problem with the access token for MapBox.

What I'm doing is changing map.mapType between osm.mapnik and mapbox.satellite with the press of a UI button. The change works, but the problem is that I can't seem to be able to set the access token for mapbox this way. The field doesn't stay serialized and I can't find a property of method to set it from the code when switching to it.

How could I achieve this behaviour ?

Thanks in advance

Re: Setting access token when changing mapType dynamically

Hi.

Unfortunately, you didn't specify which version of Online Maps you are using.
Here is an example for Online Maps v4. It can be easily ported for v3.

using System.Linq;
using OnlineMaps;
using UnityEngine;

public class DynamicToken : MonoBehaviour
{
    public Map map;
    public string mapboxAccessToken;

    public string[] mapTypes = {
        "osm.mapnik",
        "mapbox.satellite",
    };
    
    private void OnGUI()
    {
        for (int i = 0; i < mapTypes.Length; i++)
        {
            string mapType = mapTypes[i];
            if (GUILayout.Button(mapType))
            {
                SetMapType(mapType);
            }
        }
    }
    
    private void Start()
    {
        if (!map) map = GetComponent<Map>();
        if (string.IsNullOrEmpty(mapboxAccessToken))
        {
            Debug.LogError("Mapbox Access Token is required.");
            return;
        }

        SetMapType(mapTypes[0]);
    }

    private void SetMapType(string mapType)
    {
        map.mapType = mapType;
        if (!mapType.StartsWith("mapbox.")) return;
        
        TileProvider.ExtraField tokenField = TileSources.mapbox.extraFields.FirstOrDefault(f =>
        {
            TileProvider.ExtraField ef = f as TileProvider.ExtraField;
            return ef != null && ef.title == "Access Token";
        }) as TileProvider.ExtraField;

        if (tokenField != null) tokenField.value = mapboxAccessToken;
    }
}
Kind Regards,
Infinity Code Team.

Boost your productivity a lot and immediately using Ultimate Editor Enhancer. Trial and non-commerce versions available.

Re: Setting access token when changing mapType dynamically

Thanks a lot, that did the trick. When using the debugger, I saw that the ExtraField property was null. Probably put a breakpoint too soon, so I didn't look into the ExtraField. Thanks again !