файл javascript:
Код: Выделить всё
var EXPORTED_FUNCTIONS = ['_requestWebGLLocation'];
mergeInto(LibraryManager.library, {
requestWebGLLocation: function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
unityInstance.SendMessage('LocationProviderFactory',
'OnLocationReceived',
position.coords.latitude + ',' +
position.coords.longitude);
},
function(error) {
console.error('Error obtaining location: ', error);
}
);
} else {
console.error('Geolocation is not supported by this browser.');
}
}
})
Код: Выделить всё
#if !UNITY_EDITOR
#define NOT_UNITY_EDITOR
#endif
namespace Mapbox.Unity.Location
{
using UnityEngine;
using Mapbox.Unity.Map;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
///
/// Singleton factory to allow easy access to various LocationProviders.
/// This is meant to be attached to a game object.
///
public class LocationProviderFactory : MonoBehaviour
{
[SerializeField]
public AbstractMap mapManager;
[SerializeField]
[Tooltip("Provider using Unity's builtin 'Input.Location' service")]
AbstractLocationProvider _deviceLocationProviderUnity;
[SerializeField]
[Tooltip("Custom native Android location provider. If this is not set above
provider is used")]
DeviceLocationProviderAndroidNative _deviceLocationProviderAndroid;
[SerializeField]
AbstractLocationProvider _editorLocationProvider;
[SerializeField]
AbstractLocationProvider _transformLocationProvider;
[SerializeField]
bool _dontDestroyOnLoad;
[DllImport("__Internal")]
private static extern void requestWebGLLocation();
///
/// The singleton instance of this factory.
///
private static LocationProviderFactory _instance;
public static LocationProviderFactory Instance
{
get
{
return _instance;
}
private set
{
_instance = value;
}
}
ILocationProvider _defaultLocationProvider;
///
/// The default location provider.
/// Outside of the editor, this will be a .
/// In the Unity editor, this will be an
///
///
/// Fetch location to set a transform's position:
///
/// void Update()
/// {
/// var locationProvider =
LocationProviderFactory.Instance.DefaultLocationProvider;
/// transform.position =
Conversions.GeoToWorldPosition(locationProvider.Location,
///
MapController.ReferenceTileRect.Center,
///
MapController.WorldScaleFactor).ToVector3xz();
/// }
/// public ILocationProvider DefaultLocationProvider
{
get
{
return _defaultLocationProvider;
}
set
{
_defaultLocationProvider = value;
}
}
///
/// Returns the serialized .
///
public ILocationProvider TransformLocationProvider
{
get
{
return _transformLocationProvider;
}
}
///
/// Returns the serialized .
///
public ILocationProvider EditorLocationProvider
{
get
{
return _editorLocationProvider;
}
}
///
/// Returns the serialized
///
public ILocationProvider DeviceLocationProvider
{
get
{
return _deviceLocationProviderUnity;
}
}
///
/// Create singleton instance and inject the DefaultLocationProvider upon
Initialization of this component.
///
protected virtual void Awake()
{
if (Instance != null)
{
DestroyImmediate(gameObject);
return;
}
Instance = this;
if (_dontDestroyOnLoad)
{
DontDestroyOnLoad(gameObject);
}
InjectEditorLocationProvider();
InjectDeviceLocationProvider();
}
///
/// Injects the editor location provider.
/// Depending on the platform, this method and calls to it will be stripped
during compile.
///
[System.Diagnostics.Conditional("UNITY_EDITOR")]
void InjectEditorLocationProvider()
{
Debug.LogFormat("LocationProviderFactory: Injected EDITOR Location Provider
- {0}", _editorLocationProvider.GetType());
DefaultLocationProvider = _editorLocationProvider;
}
///
/// Injects the device location provider.
/// Depending on the platform, this method and calls to it will be stripped
during compile.
///
[System.Diagnostics.Conditional("NOT_UNITY_EDITOR")]
void InjectDeviceLocationProvider()
{
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
Debug.Log("Using WebGL Geolocation.");
requestWebGLLocation();
}
else
{
int AndroidApiVersion = 0;
var regex = new Regex(@"(? API version: {1}", SystemInfo.operatingSystem,
AndroidApiVersion);
if (Application.platform == RuntimePlatform.Android &&
AndroidApiVersion >= 24)
{
DefaultLocationProvider = _deviceLocationProviderAndroid;
}
else
{
DefaultLocationProvider = _deviceLocationProviderUnity;
}
}
}
public void OnLocationReceived(string locationData)
{
string[] coordinates = locationData.Split(',');
if (coordinates.Length == 2)
{
float latitude = float.Parse(coordinates[0]);
float longitude = float.Parse(coordinates[1]);
Debug.Log($"WebGL Location Received: Latitude: {latitude}, Longitude:
{longitude}");
// You can further process this location data as required
}
}
}
}
Ошибки сборки:
- Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js :
неопределенный символ: requestWebGLLocation (на который ссылается
скомпилированный код C/C++ верхнего уровня)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) - Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js:
Прерывание компиляция из-за предыдущих ошибок
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) - Сборка библиотеки\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js не удалась с выводом:
ошибка: неопределенный символ: requestWebGLLocation (на который ссылается скомпилированный код C/C++ верхнего уровня)
предупреждение: используйте ссылку -s LLD_REPORT_UNDEFINED, чтобы получить дополнительную информацию о неопределенных символах.
предупреждение: чтобы отключить ошибки для неопределенных символов. символы используют -s ERROR_ON_UNDEFINED_SYMBOLS=0
предупреждение: возможно, потребуется добавить _requestWebGLLocation в EXPORTED_FUNCTIONS, если он поступает из системной библиотеки.
Ошибка: Прерывание компиляции из-за предыдущих ошибок
emcc: ошибка: '"C:/Программа Файлы/Unity/Hub/Editor/2022.3.46f1/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/node/node.exe" "C:\Program Files\Unity\Hub\Editor\2022.3.46f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten\src\compiler.js" C:\Users\Nifty\AppData\Local\Temp\tmpmbvsgucj.json' не удалось (возвращено 1)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Подробнее здесь: https://stackoverflow.com/questions/793 ... tion-input
Мобильная версия