Topic: Map lost

i got this code from Smooth GPS move.cs from your reaply for some one and add some functions for car speed etc.
this code is going correct but suddenly the map or the instance of the map destroyed or disappeared , what causing that .

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LastPositionItem = OnlineMapsLocationService.LastPositionItem;

public class MarkerAtBottom : MonoBehaviour
{
    public GameObject RoomHandler, StartHandler, GpsHandler;
    public OnlineMapsControlBase3D control;
    public float zoomLevel = 16;
    public GameObject prefab;
    public Text text;
    public float rotationSpeed = 0.5f;
    public float resetDelay = 5f;

    private Vector2 currentLocation;
    public OnlineMapsMarker3D locationMarker;
    private float initialXRotation;
    private Coroutine resetPositionCoroutine;
    private OnlineMaps map;
    private bool isUserInteracting;
    OnlineMapsLocationService ls;

    public float sensitivity = 0.4f; // Controls how much the gyro input affects rotation
    public Text SpeedText;

    private float moveStartTime;


    public float lowPassFilterFactor = 0.1f; // Low-pass filter factor for additional stability


    Quaternion initialRotation; // To keep track of the initial orientation
    private Vector2 startPosition, endPosition;
    private float startTime;
    private float endTime;
    private float halfSecondTimer = 0f;
    private float oneSecondTimer = 0f;
    private float halfSecondInterval = 0.5f;
    private float oneSecondInterval = 1f;

    //-------------------------------------------------
    public float correctionTime = 0.5f;

    /// <summary>
    /// Should the map position be updated?
    /// </summary>
    public bool updateMapPosition = true;

    /// <summary>
    /// Smooth changes in compass values
    /// </summary>
    public bool lerpCompassValue = true;

    /// <summary>
    /// Reference to Location Service
    /// </summary>
    private OnlineMapsLocationService locationService;

    /// <summary>
    /// Current speed (km/h)
    /// </summary>
    private float speed;

    /// <summary>
    /// Compass true heading (degree)
    /// </summary>
    private float compass;

    /// <summary>
    /// Last known location
    /// </summary>
    private OnlineMapsVector2d lastKnownLocation;


    /// <summary>
    /// Correction vector
    /// </summary>
    private OnlineMapsVector2d correction;

    /// <summary>
    /// Reference to the marker
    /// </summary>
    private OnlineMapsMarker marker;

    /// <summary>
    /// List of last positions
    /// </summary>
    private List<LastPositionItem> lastPositions;

    /// <summary>
    /// The maximum number of items in the list of last positions
    /// </summary>
    private int maxPositionCount = 3;

    /// <summary>
    /// Progress of correction
    /// </summary>
    private float correctionProgress;

    /// <summary>
    /// Smoothed compass value (degree)
    /// </summary>
    private float smoothedCompass;
    //-------------------------------------------------
    public Button Btn;
    private void Start()
    {
        if (control == null) control = OnlineMapsControlBase3D.instance;
        if (control == null)
        {
            text.text = "You must use the 3D control (Texture or Tileset).";
            return;
        }
        if (SystemInfo.supportsGyroscope)
        {
            Input.gyro.enabled = true;
            initialRotation = Quaternion.Euler(90, 0, 0); // Adjust based on map orientation
        }

        map = OnlineMaps.instance;
        // Subscribe to map interaction events
        map.OnMapUpdated += OnMapInteraction;
        map.OnChangeZoom += OnMapInteraction;

         ls = OnlineMapsLocationService.instance;
        Input.location.Start();
        Input.compass.enabled = true;
        if (ls == null)
        {
            text.text = "Location Service not found.";
            return;
        }

        ls.OnLocationInited += OnLocationInited;

        // Store the initial X rotation of the map to preserve it
        initialXRotation = map.transform.eulerAngles.x;
        moveStartTime = Time.time;

    }

    private void OnLocationInited()
    {
        currentLocation = new Vector2(Input.location.lastData.longitude, Input.location.lastData.latitude);

        // Create the marker at the current location
        locationMarker = control.marker3DManager.Create(currentLocation, prefab);
        //locationMarker.transform.localScale = Vector3.one * 22f;  // Adjust scale for better visibility
        locationMarker.scale = 16f;

        ls.OnLocationChanged += OnLocationChanged;
        ls.OnCompassChanged += OnCompassChanged;
        lastKnownLocation = currentLocation = ls.position;
    }

    private void OnCompassChanged(float compassHeading)
    {
        // 888
        //////// Rotate the marker based on compass heading
        //////if (locationMarker != null)
        //////{
        //////    Transform markerTransform = locationMarker.transform;
        //////    if (markerTransform != null)
        //////    {
        //////        markerTransform.rotation = Quaternion.Euler(0, compassHeading, 0);
        //////    }
        //////}
        ///
        // Update compass value
        compass = compassHeading * 360;

        // If the marker rotation should not smooth, update the rotation
        if (!lerpCompassValue && locationMarker != null) locationMarker.rotationY = compassHeading;
    }

    private void Update()
    {
        // 88
        //////if (Input.gyro.enabled)
        //////{
        //////    // Get the Y-axis rotation rate from the gyroscope
        //////    float gyroY = Input.gyro.rotationRateUnbiased.y;

        //////    // Apply a low-pass filter to stabilize small movements
        //////    filteredYRotation = (1 - lowPassFilterFactor) * filteredYRotation + lowPassFilterFactor * gyroY;

        //////    // Apply smoothing to the filtered Y rotation rate and accumulate in yRotation
        //////    yRotation += filteredYRotation * sensitivity;

        //////    // Smooth the transition by using Lerp on the rotation itself
        //////    map.transform.rotation = Quaternion.Lerp(map.transform.rotation, Quaternion.Euler(0, yRotation, 0), smoothFactor);
        //////}

        if (speed < 1 || locationMarker == null) return;

        // Smooth changes of compass
        if (lerpCompassValue)
        {
            if (compass - smoothedCompass > 180) smoothedCompass += 360;
            else if (compass - smoothedCompass < -180) smoothedCompass -= 360;

            if (Math.Abs(compass - smoothedCompass) >= float.Epsilon)
            {
                if (Mathf.Abs(compass - smoothedCompass) < 0.003f) smoothedCompass = compass;
                else smoothedCompass = Mathf.Lerp(smoothedCompass, compass, 0.02f);

                locationMarker.rotationY = smoothedCompass;
            }
        }

        // Find the expected location
        float coveredDistance = Time.deltaTime * speed / 3600f;
        double lng, lat;
        OnlineMapsUtils.GetCoordinateInDistance(currentLocation.x, currentLocation.y, coveredDistance, compass, out lng, out lat);
        currentLocation.x = (float)lng;
        currentLocation.y = (float)lat;

        // If correction is required, do it
        if (correctionProgress < 1 && correction.SqrMagnitude() > 0)
        {
            float nextCorrectionProgress = correctionProgress + Time.deltaTime / correctionTime;
            if (nextCorrectionProgress > 1) nextCorrectionProgress = 1;

            float correctionDelta = nextCorrectionProgress - correctionProgress;
            currentLocation.x += (float)correction.x * correctionDelta;
            currentLocation.y += (float)correction.y * correctionDelta;

            correctionProgress = nextCorrectionProgress;
        }

        // Set marker position
        locationMarker.SetPosition(lng, lat);

        // Set map position
        if (updateMapPosition) OnlineMaps.instance.SetPosition(lng, lat);

        // Increment timers by the time passed since last frame
        halfSecondTimer += Time.deltaTime;
        oneSecondTimer += Time.deltaTime;

        // Call function every 0.5 seconds
        if (halfSecondTimer >= halfSecondInterval)
        {
            FunctionEveryHalfSecond();
            halfSecondTimer = 0f; // Reset the timer
        }

        // Call function every 1 second
        if (oneSecondTimer >= oneSecondInterval)
        {
            FunctionEverySecond();
            oneSecondTimer = 0f; // Reset the timer
        }

    }
    public void UpdateSpeed()
    {
        if (lastPositions == null) lastPositions = new List<LastPositionItem>();

        lastPositions.Add(new LastPositionItem((float)lastKnownLocation.x, (float)lastKnownLocation.y, Time.time));
        while (lastPositions.Count > maxPositionCount) lastPositions.RemoveAt(0);

        if (lastPositions.Count < 2)
        {
            speed = 0;
            return;
        }

        LastPositionItem p1 = lastPositions[0];
        LastPositionItem p2 = lastPositions[lastPositions.Count - 1];

        double dx, dy;
        OnlineMapsUtils.DistanceBetweenPoints(p1.lng, p1.lat, p2.lng, p2.lat, out dx, out dy);
        double distance = Math.Sqrt(dx * dx + dy * dy);
        double time = (p2.timestamp - p1.timestamp) / 3600;
        speed = Mathf.Abs((float)(distance / time));
    }
    void FunctionEveryHalfSecond()
    {
        Debug.Log("Function called every 0.5 seconds");
        SetStartPosition();
    }

    void FunctionEverySecond()
    {
        Debug.Log("Function called every 1 second");
        SetEndPosition();
        CalculateSpeed();
    }
    private void OnLocationChanged(Vector2 newLocation)
    {
        // 88
        //////if (locationMarker != null)
        //////{
        //////    locationMarker.position = position;

        //////    // Update the current location for display
        //////    currentLocation = position;
        //////    //text.text = "3-Longitude: " + currentLocation.x.ToString("F6") + " Latitude: " + currentLocation.y.ToString("F6");
        //////}
        ///
         // Save a new location
        lastKnownLocation = newLocation;

        // Calculating the correction vector
        correction = lastKnownLocation - currentLocation;

        // Update current speed
        UpdateSpeed();

        // Calculate a distance between new and old locations
        double dx, dy;
        OnlineMapsUtils.DistanceBetweenPoints(newLocation.x, newLocation.y, currentLocation.x, currentLocation.y, out dx, out dy);
        double d = Math.Sqrt(dx * dx + dy * dy);

        // If the distance is too long or the speed is too low, update the location
        if (d > 0.01 || speed < 1)
        {
            currentLocation = lastKnownLocation;
            correction = OnlineMapsVector2d.zero;
        }

        // Reset correction progress
        correctionProgress = 0;
    }

    private void OnMapInteraction()
    {
        // Flag to indicate user interaction to prevent compass-based rotation updates
        isUserInteracting = true;

        // Restart coroutine to reset position after delay
        if (resetPositionCoroutine != null) StopCoroutine(resetPositionCoroutine);
        resetPositionCoroutine = StartCoroutine(ResetPositionAfterDelay());
    }

    private IEnumerator ResetPositionAfterDelay()
    {
        // Wait for the delay
        yield return new WaitForSeconds(resetDelay);

        // Reset the map position and zoom level
        OnlineMaps.instance.SetPositionAndZoom(currentLocation.x, currentLocation.y, zoomLevel);

        // Reset user interaction flag to resume compass-based rotation
        isUserInteracting = false;
    }

    void SetStartPosition()
    {
        // Get the starting position (latitude, longitude)
        startPosition =new Vector2( locationMarker.position.x,locationMarker.position.y); // Example start position
        startTime = Time.time;
    }
    void SetEndPosition()
    {
        endTime = Time.time;
    }
    void CalculateSpeed()
    {
        // Calculate distance in kilometers between start and end positions
        double distanceKm = OnlineMapsUtils.DistanceBetweenPoints(startPosition, locationMarker.position).magnitude;

        // Calculate time taken in hours
        double timeHours = (endTime - startTime) / 3600.0;

        // Calculate speed in km/h
        double speed = distanceKm / timeHours;
        SpeedText.text = speed.ToString();
        Debug.Log($"Distance traveled: {distanceKm} km");
        Debug.Log($"Time taken: {timeHours} hours");
        Debug.Log($"Calculated Speed: {speed} km/h");

        // Reset start position for continuous speed tracking (optional)
        startPosition = endPosition;
        startTime = endTime;

    }
    public void GoToRoomChat()
    {
        float leftMargin = 0;
        float rightMargin = 0;
        RectTransform rectTransform = RoomHandler.GetComponent<RectTransform>();
        rectTransform.offsetMin = new Vector2(leftMargin, rectTransform.offsetMin.y);
        rectTransform.offsetMax = new Vector2(-rightMargin, rectTransform.offsetMax.y);

        rectTransform = StartHandler.GetComponent<RectTransform>();
        rectTransform.offsetMin = new Vector2(leftMargin, rectTransform.offsetMin.y);
        rectTransform.offsetMax = new Vector2(-rightMargin, rectTransform.offsetMax.y);

        GpsHandler.SetActive(false);
    }
}

Re: Map lost

I don't know why your map was destroyed.
This script does not destroy objects.
Check your other scripts.

Kind Regards,
Infinity Code Team.

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

3 (edited by tamim.ali.zoabi 2024-11-11 12:53:37)

Re: Map lost

I do a debug and a gps emulation 
So approximately when the map change position i got this error : Curl error 60: Cert verify failed: UNITYTLS_X509VERIFY_FLAG_USER_ERROR1

Re: Map lost

This is a known issue in Unity, and is solved this way:

using UnityEngine;
using UnityEngine.Networking;

public class X509Hook : MonoBehaviour
{
    public void Start()
    {
        OnlineMapsWWW.OnCreateRequest += r => r.request.certificateHandler = new AllowHandler();
    }
    
    private class AllowHandler : CertificateHandler
    {
        protected override bool ValidateCertificate(byte[] certificateData)
        {
            return true;
        }
    }
}
Kind Regards,
Infinity Code Team.

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

5 (edited by tamim.ali.zoabi 2024-11-11 21:49:23)

Re: Map lost

i add this script to GameObject in the hierarchy but i still got same error when i change compase value or Position Value"Longitude,Latitude" in gps emulater

Re: Map lost

It's very strange.
First of all, restart the editor.
I've heard that this sometimes helps with this problem.

If the problem persists, you need to isolate the request to which service is causing the problem.
Then send your request to me and I'll see what I can do about it.

Kind Regards,
Infinity Code Team.

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

Re: Map lost

i found the reason that make the map disappeared .
i have a
1-GameObject A with Panel as child
here i used a button to set gameobject with map as child ACTIVE
BUT I DONT DISACTIVE  GAMEOBJECT A.
i Make it out of focus :
float leftMargin = 9350f;  // Adjust the left margin
        float rightMargin = -9350f; // Adjust the right margin
        RectTransform rectTransform = RoomHandlr.GetComponent<RectTransform>();
        rectTransform.offsetMin = new Vector2(leftMargin, rectTransform.offsetMin.y);
        rectTransform.offsetMax = new Vector2(-rightMargin, rectTransform.offsetMax.y);

        rectTransform = StartHandlr.GetComponent<RectTransform>();
        rectTransform.offsetMin = new Vector2(leftMargin, rectTransform.offsetMin.y);
        rectTransform.offsetMax = new Vector2(-rightMargin, rectTransform.offsetMax.y);


CAUSE I NEED IT FOR GETTING VARIABLE
so having this situation causing map to be dragged.
if i desactive gameobject A its work perfectly . but i need gameobject A.