谷歌静态地图无法在iOS设备上加载

本文关键字:加载 iOS 静态 地图 谷歌 | 更新日期: 2023-09-27 18:04:24

我正在用Unity编写一款游戏,我需要加载一个静态地图。地图在编辑器和Android设备中正确显示,但在iOS设备中不正确显示。它说网址不正确…我不知道怎么解决。有人能帮帮我吗?

我用下面的代码调用这个map:

url= "http://maps.google.com/maps/api/staticmap?center="+fixLat+","+fixLon+"&zoom="+zoom+"&scale=2&size=640x640&style=feature:all|element:geometry|hue:0x00fff0|lightness:0|gamma:0.21|visibility:on&style=feature:all|element:labels|visibility:off&style=feature:landscape.man_made|element:geometry|color:0x133f42|visibility:on&style=feature:landscape.natural|element:geometry.fill|visibility:on|hue:0x00ffd2|saturation:35|lightness:0|gamma:0.5&style=feature:poi|element:geometry.fill|lightness:0|gamma:0.6|visibility:on&style=feature:poi.park|element:geometry|visibility:on|saturation:0|color:0x2e9470&style=feature:road|element:geometry.fill|visibility:on|color:0x05111a&style=feature:road|element:geometry.stroke|visibility:off&style=feature:transit|element:geometry|visibility:off"+key;
这是调用url的完整代码:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Gpsconnect : MonoBehaviour 
{
public Transform user;                  
public bool simGPS = true;                          
public float userSpeed = 5.0f;                  
public bool realSpeed = false;                  
public float fixLat = 42.3627f;     
public float fixLon = -71.05686f;           
public float altitude;          
public float heading;           
public float accuracy;                  
public int maxZoom = 18;        
public int minZoom = 1;                 
public int zoom = 17;           
private float multiplier;   
public string key = "";         
public string[] maptype;            
public int[] mapSize;                   
public int index;                
public int indexSize;            
public float camDist = 15.0f;       
public int camAngle = 40;           
public int initTime = 3;                    
public int maxWait = 30;        
public bool buttons = true;     
public string dmsLat;                       
public string dmsLon;                           
public float updateRate = 0.1f;     
public bool autoCenter = true;  
public string status;           
public bool gpsFix;                  
public Vector3 iniRef;                   
public bool info;           
public bool triDView = false;   
public bool ready;              
public bool freeCam = false;        
public bool pinchToZoom = true;             
public bool dragToPan = true;           
public bool mapDisabled;                
public bool mapping = false;    
public Transform cam;   
public float userLon;   
public float userLat;
private float levelHeight;
private float smooth = 1.3f;                                
private float yVelocity = 0.0f;  
private float speed;
private Camera mycam;
private float currentOrtoSize;
private LocationInfo loc;
private Vector3 currentPosition;
private Vector3 newUserPos; 
private Vector3 currentUserPos;
private float download;
private WWW www;
private string url = ""; 
private double longitude;
private double latitude;
private Rect rect;
private float screenX;
private float screenY;
private Renderer maprender;
private Transform mymap;
private float initPointerSize;
private double tempLat;
private double tempLon;
private bool touchZoom;
private string centre;
private bool centering;
private Texture centerIcon;
private Texture topIcon;
private Texture bottomIcon;
private Texture leftIcon;
private Texture rightIcon;
private GUIStyle arrowIcon;
private float dot;
private bool centered = true;
private int borderTile = 0;
private bool tileLeft;
private bool tileRight;
private bool tileTop;
private bool tileBottom;
private Rect topCursorPos;
private Rect rightCursorPos;
private Rect bottomCursorPos;
private Rect leftCursorPos;

void Awake(){
    //Set the map's tag to GameController
    transform.tag = "GameController";
    cam = Camera.main.transform;
    mycam = Camera.main;
    user = GameObject.FindGameObjectWithTag("Player").transform;
    //Store most used components and values into variables for faster access.
    mymap = transform;
    maprender = GetComponent<Renderer>();
    screenX = Screen.width;
    screenY = Screen.height;    
    //Add possible values to maptype and mapsize arrays (GOOGLE)
    maptype = new string[]{"satellite","roadmap","hybrid","terrain"};
    mapSize = new int[]{640}; //in pixels
    //Set GUI "center" button label
    if(triDView){
        centre = "refresh";
    }
    //Enable autocenter on 2D-view (default)
    else{
        autoCenter = true;
    }
    //Load required interface textures
    centerIcon = Resources.Load("centerIcon") as Texture2D;
    topIcon = Resources.Load("cursorTop") as Texture2D;
    bottomIcon = Resources.Load("cursorBottom") as Texture2D;
    leftIcon = Resources.Load("cursorLeft") as Texture2D;
    rightIcon = Resources.Load("cursorRight") as Texture2D;
    //Resize GUI according to screen size/orientation 
    if(screenY >= screenX){
        dot = screenY/800.0f;
    }else{
        dot = screenX/800.0f;
    }
}

IEnumerator Start () {
    //Setting variables values on Start
    gpsFix=false;
    rect = new Rect (screenX/10, screenY/10, 8*screenX/10, 8*screenY/10);
    topCursorPos = new Rect(screenX/2-25*dot, 0, 50*dot, 50*dot);
    rightCursorPos = new Rect(screenX-50*dot, screenY/2-25*dot, 50*dot, 50*dot);
    if(!buttons)
        bottomCursorPos = new Rect(screenX/2-25*dot, screenY-50*dot, 50*dot, 50*dot);
    else
        bottomCursorPos = new Rect(screenX/2-25*dot, screenY-50*dot-screenY/12, 50*dot, 50*dot);
    leftCursorPos = new Rect(0, screenY/2-25*dot, 50*dot, 50*dot);
    Vector3 tmp = mymap.eulerAngles;
    tmp.y=180;
    mymap.eulerAngles = tmp;
    initPointerSize = user.localScale.x;
    user.position = new Vector3(0, user.position.y, 0);
    //Initial Camera Settings
    //3D 
    if(triDView){
        mycam.orthographic = false;
        pinchToZoom = false;
        dragToPan = false;
        //Set the camera's field of view according to Screen size so map's visible area is maximized.
        if(screenY > screenX){
            mycam.fieldOfView = 72.5f;
        }else{
            mycam.fieldOfView = 95-(28*(screenX/screenY));
        }
    }
    //2D
    else{
        mycam.orthographic = true;
        mycam.nearClipPlane = 0.1f;
        mycam.farClipPlane = cam.position.y+1;  
        if(screenY >= screenX){
            mycam.orthographicSize = mymap.localScale.z*5.0f;
        }else{
            mycam.orthographicSize = (screenY/screenX)*mymap.localScale.x*5.0f;     
        }
    }
    //The "ready" variable will be true when the map texture has been successfully loaded.
    ready = false; 
    //STARTING LOCATION SERVICES
    // First, check if user has location service enabled
    #if (UNITY_IOS && !UNITY_EDITOR)
    if (!Input.location.isEnabledByUser){
        //This message prints to the Editor Console
        print("Ha sido imposible iniciar los servicios de localizacion.'nComprueba los ajustes de localización de tu teléfono");
        //You can use this "status" variable to show messages in your custom user interface (GUIText, etc.)
        status = "Ha sido imposible iniciar 'nlos servicios de localizacion.'nComprueba los ajustes de 'nlocalización de tu teléfono";
        yield return new WaitForSeconds(4);
        Application.LoadLevel("0_Login");
    }
    #endif
    // Start service before querying location
    Input.location.Start (3.0f, 3.0f); 
    Input.compass.enabled = true;
    print("Iniciando servicios de localización...");
    status = "Iniciando servicios de localización...";
    // Wait until service initializes
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
        yield return new WaitForSeconds (1);
        maxWait--;
    }
    // Service didn't initialize in 30 seconds
    if (maxWait < 1) {
        print("Ha sido imposible iniciar los servicios de localizacion.'nComprueba los ajustes de localización de tu teléfono");
        status = "Ha sido imposible iniciar 'nlos servicios de localizacion.'nComprueba los ajustes de 'nlocalización de tu teléfono";
        yield return new WaitForSeconds(4);
        Application.LoadLevel("0_Login");
    }
    // Connection has failed
    if (Input.location.status == LocationServiceStatus.Failed) {
        print("Ha sido imposible determinar tu localización'nComprueba los ajustes de localización de tu teléfono");
        status = "Ha sido imposible determinar 'ntu localización.'nComprueba los ajustes de 'nlocalización de tu teléfono";
        yield return new WaitForSeconds(4);
        Application.LoadLevel("0_Login");
    }
    // Access granted and location value could be retrieved
    else {
        if(!mapDisabled){
            print("GPS conectado. Ajustando posición...");
            status = "GPS conectado!'n Ajustando posición...";
        }
        else{
            print("GPS conectado.");
            status = "GPS conectado!";
        }
        if(!simGPS){
            //Wait in order to find enough satellites and increase GPS accuracy
            yield return new WaitForSeconds(initTime);
            //Set position
            loc  = Input.location.lastData;          
            iniRef.x = ((loc.longitude*20037508.34f/180)/100);
            iniRef.z = (float)(System.Math.Log(System.Math.Tan((90+loc.latitude)*System.Math.PI/360))/(System.Math.PI/180));
            iniRef.z = ((iniRef.z*20037508.34f/180)/100);  
            iniRef.y = 0;
            fixLon = loc.longitude;
            fixLat = loc.latitude; 
            //Successful GPS fix
            gpsFix = true;
            //Update Map for the current location
             StartCoroutine(MapPosition());
        }  
        else{
            //Simulate initialization time
            yield return new WaitForSeconds(initTime);
            //Set Position
            iniRef.x = ((fixLon*20037508.34f/180)/100);
            iniRef.z = (float)(System.Math.Log(System.Math.Tan((90+fixLat)*System.Math.PI/360))/(System.Math.PI/180));
            iniRef.z = (iniRef.z*20037508.34f/180)/100;  
            iniRef.y = 0;
            //Simulated successful GPS fix
            gpsFix = true;
            //Update Map for the current location
            StartCoroutine(MapPosition());
        }    
    }
    //Rescale map, set new camera height, and resize user pointer according to new zoom level
     StartCoroutine(ReScale()); 
    //Set player's position using new location data (every "updateRate" seconds)
    //Default value for updateRate is 0.1. Increase if necessary to improve performance
    InvokeRepeating("MyPosition", 1, updateRate); 
    //Read incoming compass data (every 0.1s)
    InvokeRepeating("Orientate", 1, 0.1f);
    //Get altitude and horizontal accuracy readings using new location data (Default: every 2s)
    InvokeRepeating("AccuracyAltitude", 1, 2);
    //Auto-Center Map on 2D View Mode 
    InvokeRepeating("Check", 1, 0.2f);
}

void MyPosition(){
    if(gpsFix){
        if(!simGPS){
            loc = Input.location.lastData;
            newUserPos.x = ((loc.longitude*20037508.34f/180)/100)-iniRef.x;
            newUserPos.z = (float)(System.Math.Log(System.Math.Tan((90+loc.latitude)*System.Math.PI/360))/(System.Math.PI/180));
            newUserPos.z = ((newUserPos.z*20037508.34f/180)/100)-iniRef.z;   
            dmsLat = convertdmsLat(loc.latitude);
            dmsLon = convertdmsLon(loc.longitude);
            userLon = loc.longitude;
            userLat = loc.latitude;
        }
        else{
            userLon = (18000*(user.position.x+iniRef.x))/20037508.34f;
            userLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(user.position.z+iniRef.z))))-90;
            dmsLat = convertdmsLat(userLat);
            dmsLon = convertdmsLon(userLon);
        }
    }   
} 

void Orientate(){
    if(!simGPS && gpsFix){
        heading = Input.compass.trueHeading;
    }
    else{
        heading = user.eulerAngles.y;
    }
}
void AccuracyAltitude(){
    if(gpsFix)
        altitude = loc.altitude;
        accuracy = loc.horizontalAccuracy;
}
void Check(){
    if(autoCenter && triDView == false){
        if(ready == true && mapping == false && gpsFix){
            if (rect.Contains(Vector2.Scale(mycam.WorldToViewportPoint (user.position), new Vector2(screenX, screenY)))){
                //DoNothing
            }
            else{
                centering=true;
                 StartCoroutine(MapPosition());
                 StartCoroutine(ReScale()); 
            }
        }
    }
}
//Auto-Center Map on 3D View Mode when exiting map's collider
void OnTriggerExit(Collider other){
    if(other.tag == "Player" && autoCenter && triDView){
         StartCoroutine(MapPosition());
         StartCoroutine(ReScale());
    }
}
//Update Map with the corresponding map images for the current location ============================================
IEnumerator MapPosition(){
    //The mapping variable will only be true while the map is being updated
    mapping = true;
    CursorsOff();
    //CHECK GPS STATUS AND RESTART IF NEEDED
    if (Input.location.status == LocationServiceStatus.Stopped || Input.location.status == LocationServiceStatus.Failed){
        // Start service before querying location
        Input.location.Start (3.0f, 3.0f);
        // Wait until service initializes
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
            yield return new WaitForSeconds (1);
            maxWait--;
        }
        // Service didn't initialize in 20 seconds
        if (maxWait < 1) {
            print ("Timed out");
            //use the status string variable to print messages to your own user interface (GUIText, etc.)
            status = "Timed out";
        }
        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed) {
            print ("Unable to determine device location");
            //use the status string variable to print messages to your own user interface (GUIText, etc.)
            status = "Unable to determine device location";
        }
    }
   //------------------------------------------------------------------ //
    www = null; 
    //Get last available location data
    loc = Input.location.lastData;
    //Make player invisible while updating map
    user.gameObject.GetComponent<Renderer>().enabled = false;

    //Set target latitude and longitude
    if(triDView){
        if(simGPS){
            fixLon = (18000*(user.position.x+iniRef.x))/20037508.34f;
            fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(user.position.z+iniRef.z))))-90;   
        }else{
            fixLon = loc.longitude;
            fixLat = loc.latitude;
        }
    }else{
        if(centering){
            if(simGPS){
                fixLon = (18000*(user.position.x+iniRef.x))/20037508.34f;
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(user.position.z+iniRef.z))))-90;   
            }else{
                fixLon = loc.longitude;
                fixLat = loc.latitude;
            }
        }
        else{
            if(borderTile == 0){
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(cam.position.z+iniRef.z))))-90;    
                fixLon = (18000*(cam.position.x+iniRef.x))/20037508.34f;
            }
            //North tile
            if (borderTile == 1){
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(cam.position.z+3*mycam.orthographicSize/2+iniRef.z))))-90; 
                fixLon = (18000 *(cam.position.x+iniRef.x))/20037508.34f;
                borderTile=0;   
                tileTop=false;
            }
            //East Tile
            if (borderTile == 2){
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(cam.position.z+iniRef.z))))-90;    
                fixLon = (18000*(cam.position.x+3*(screenX*mycam.orthographicSize/screenY)/2+iniRef.x))/20037508.34f;
                borderTile = 0;
            }
            //South Tile
            if (borderTile == 3){
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(cam.position.z-3*mycam.orthographicSize/2+iniRef.z))))-90; 
                fixLon = (18000*(cam.position.x+iniRef.x))/20037508.34f;
                borderTile=0;
            }
            //West Tile
            if (borderTile == 4){
                fixLat = ((360/Mathf.PI)*Mathf.Atan(Mathf.Exp(0.00001567855943f*(cam.position.z+iniRef.z))))-90;    
                fixLon = (18000*(cam.position.x-3*(screenX*mycam.orthographicSize/screenY)/2+iniRef.x))/20037508.34f;
                borderTile=0;
            }
        }
    }

    //MAP ================================================================================
    //Build a valid Google Maps tile request for the current location 
    url= "https://maps.google.com/maps/api/staticmap?center="+fixLat+","+fixLon+"&zoom="+zoom+"&scale=2&size=640x640&style=feature:all|element:geometry|hue:0x00fff0|lightness:0|gamma:0.21|visibility:on&style=feature:all|element:labels|visibility:off&style=feature:landscape.man_made|element:geometry|color:0x133f42|visibility:on&style=feature:landscape.natural|element:geometry.fill|visibility:on|hue:0x00ffd2|saturation:35|lightness:0|gamma:0.5&style=feature:poi|element:geometry.fill|lightness:0|gamma:0.6|visibility:on&style=feature:poi.park|element:geometry|visibility:on|saturation:0|color:0x2e9470&style=feature:road|element:geometry.fill|visibility:on|color:0x05111a&style=feature:road|element:geometry.stroke|visibility:off&style=feature:transit|element:geometry|visibility:off"+"&sensor=false&key="+key;
    tempLat = fixLat;
    tempLon = fixLon;
    //=================================================================================================
    //Proceed with download if a Wireless internet connection is available 
    if(Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork){
        StartCoroutine(Online());
    }   
    //Proceed with download if a 3G/4G internet connection is available 
    else if(Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork){
         StartCoroutine(Online());
    }
    //No internet connection is available. Switching to Offline mode.    
    else{
        Offline();
    }   
}
//ONLINE MAP DOWNLOAD
IEnumerator Online(){
    if(!mapDisabled){
        // Start a download of the given URL
        www = new WWW(url); 
        // Wait for download to complete
        download = (www.progress);
        while(!www.isDone){
            print("Actualizando mapa "+System.Math.Round(download*100)+" %");
            //use the status string variable to print messages to your own user interface (GUIText, etc.)
            status="Actualizando mapa "+System.Math.Round(download*100)+" %";
            yield return null;
        }
        //Show download progress and apply texture
        if(www.error == null){
            print("Actualizando mapa 100 %");
            print("Mapa preparado!");
            //use the status string variable to print messages to your own user interface (GUIText, etc.)
            status = "Actualizando mapa 100 %'nMapa preparado!";
            yield return new WaitForSeconds (0.5f);
            maprender.material.mainTexture = null;
            Texture2D tmp;
            tmp = new Texture2D(1280, 1280, TextureFormat.RGB24, false);
            maprender.material.mainTexture = tmp;
            www.LoadImageIntoTexture(tmp);  
        }
        //Download Error. Switching to offline mode
        else{
            print("Error en el mapa:"+www.error);
            //use the status string variable to print messages to your own user interface (GUIText, etc.)
            status = "Error en el mapa:"+www.error;
            yield return new WaitForSeconds (4);
            maprender.material.mainTexture = null;
            Offline();
        }
        maprender.enabled = true;
    }
    ReSet();
    user.gameObject.GetComponent<Renderer>().enabled = true;
    ready = true;
    mapping = false;
}
//USING OFFLINE BACKGROUND TEXTURE
void Offline(){
    if(!mapDisabled){
        maprender.material.mainTexture=Resources.Load("offline") as Texture2D;
        maprender.enabled = true;
    }
    ReSet();
    ready = true;
    mapping = false;
    user.gameObject.GetComponent<Renderer>().enabled = true;
}
//Re-position map and camera using updated data
void ReSet(){
    Vector3 tmp = transform.position;
    tmp.x = (float)((tempLon*20037508.34f/180)/100)-iniRef.x;
    tmp.z = (float)(System.Math.Log(System.Math.Tan((90+tempLat)*System.Math.PI/360))/(System.Math.PI/180));
    tmp.z = ((tmp.z*20037508.34f/180)/100)-iniRef.z;
    transform.position = tmp;
    if(!freeCam){
        cam.position = new Vector3(transform.position.x, cam.position.y, transform.position.z);
    }
    if(triDView == false && centering){
        centered = true;
        autoCenter = true;
        centering = false;
    }
}

void Update(){
    //Rename GUI "center" button label
    if(!triDView){
        if(cam.position.x != user.position.x || cam.position.z != user.position.z)
            centre ="center";
        else
            centre ="refresh";
    }
    //User pointer speed
    if(realSpeed){
        speed = userSpeed*0.05f;
    }
    else{
        speed = userSpeed*10000/(Mathf.Pow(2, zoom)*1.0f);
    }
    //3D-2D View Camera Toggle (use only while game is stopped) 
    if(triDView && !freeCam){
        cam.parent = user;
        if(ready)
            cam.LookAt(user);
    }   
    if(ready){  
        if(!simGPS){
            //Smoothly move pointer to updated position
            currentUserPos.x = user.position.x;
            currentUserPos.x = Mathf.Lerp (user.position.x, newUserPos.x, 2.0f*Time.deltaTime);
            currentUserPos.z = user.position.z;
            currentUserPos.z = Mathf.Lerp (user.position.z, newUserPos.z, 2.0f*Time.deltaTime);
            user.position = new Vector3(currentUserPos.x, user.position.y, currentUserPos.z);
            //Update rotation
            if(System.Math.Abs(user.eulerAngles.y-heading) >= 5){
                float newAngle = Mathf.SmoothDampAngle(user.eulerAngles.y, heading, ref yVelocity, smooth);
                user.eulerAngles = new Vector3(user.eulerAngles.x, newAngle, user.eulerAngles.z);
            }
        }
        else{
            //When GPS Emulator is enabled, user position is controlled by keyboard input.
            if(mapping == false){
                //Use keyboard input to move the player
                if (Input.GetKey ("up") || Input.GetKey ("w")){
                    user.transform.Translate(Vector3.forward*speed*Time.deltaTime);
                }
                if (Input.GetKey ("down") || Input.GetKey ("s")){
                    user.transform.Translate(-Vector3.forward*speed*Time.deltaTime);
                }
                //rotate pointer when pressing Left and Right arrow keys
                user.Rotate(Vector3.up, Input.GetAxis("Horizontal")*80*Time.deltaTime);
            }
        }   
    }
    if(mapping && !mapDisabled){
        //get download progress while images are still downloading
        if(www != null)
            download = www.progress;
    }   
    //Enable/Disable map renderer 
    if(mapDisabled)
        maprender.enabled = false;
    else
        maprender.enabled = true;

void CheckBorders(){
    //Reached left tile border
    if(Mathf.Round((mycam.ScreenToWorldPoint(new Vector3(0, 0.5f, cam.position.y)).x)*100.0f)/100.0f <= Mathf.Round((mymap.position.x-mymap.localScale.x*5)*100.0f)/100.0f){
        //show button for borderTile=4;
        tileLeft = true;
    }else{
        //hide button
        tileLeft = false;
    }
    //Reached right tile border
    if(Mathf.Round((mycam.ScreenToWorldPoint(new Vector3(mycam.pixelWidth, 0.5f, cam.position.y)).x)*100.0f)/100.0f >= Mathf.Round((mymap.position.x+mymap.localScale.x*5)*100.0f)/100.0f){
        //show button for borderTile=2;
        tileRight = true;
    }else{
        //hide button
        tileRight = false;
    }
    //Reached bottom tile border
    if(Mathf.Round((mycam.ScreenToWorldPoint(new Vector3(0.5f, 0, cam.position.y)).z)*100.0f)/100.0f <= Mathf.Round((mymap.position.z-mymap.localScale.z*5)*100.0f)/100.0f){
        //show button for borderTile=3;
        tileBottom = true;
    }else{
        //hide button
        tileBottom = false;
    }
    //Reached top tile border
    if(Mathf.Round((mycam.ScreenToWorldPoint(new Vector3(0.5f, mycam.pixelHeight, cam.position.y)).z)*100.0f)/100.0f >= Mathf.Round((mymap.position.z+mymap.localScale.z*5)*100.0f)/100.0f){
        //show button for borderTile=1;
        tileTop = true;
    }else{
        //hide button
        tileTop = false;
    }
}
//Disable surrounding tiles cursors
void CursorsOff(){
    tileTop = false;
    tileBottom = false;
    tileLeft = false;
    tileRight = false;
}
//Clamp the camera position
void ClampCam(){
    Vector3 tmp = cam.position;
    tmp.x = Mathf.Clamp(cam.position.x, 
                        mymap.position.x-(mymap.localScale.x*5)+(mycam.ScreenToWorldPoint(new Vector3(mycam.pixelWidth, 0.5f, cam.position.y)).x-mycam.ScreenToWorldPoint(new Vector3(0, 0.5f, cam.position.y)).x)/2, 
                        mymap.position.x+(mymap.localScale.x*5)-(mycam.ScreenToWorldPoint(new Vector3(mycam.pixelWidth, 0.5f, cam.position.y)).x-mycam.ScreenToWorldPoint(new Vector3(0, 0.5f, cam.position.y)).x)/2 );
    tmp.z = Mathf.Clamp(cam.position.z, 
                        mymap.position.z-(mymap.localScale.z*5)+(mycam.ScreenToWorldPoint(new Vector3(0.5f, mycam.pixelHeight, cam.position.y)).z-mycam.ScreenToWorldPoint(new Vector3(0.5f, 0, cam.position.y)).z)/2, 
                        mymap.position.z+(mymap.localScale.z*5)-(mycam.ScreenToWorldPoint(new Vector3(0.5f, mycam.pixelHeight, cam.position.y)).z-mycam.ScreenToWorldPoint(new Vector3(0.5f, 0, cam.position.y)).z)/2 );                
    cam.position = tmp;
}
}

这些是屏幕截图。编辑器和Android设备

iOS设备

谷歌静态地图无法在iOS设备上加载

运行问题中的代码,并能够复制您的问题。这是由于iOS上使用http连接而不是https的新限制。就像我在评论中提到的,用UnityWebRequest代替WWW解决了这个问题。

另外,每次执行new Texture2D(1280, 1280, TextureFormat.RGB24, false);时都不必要地创建新的纹理。这应该用Unity的UI组件RawImage来完成。在这种情况下,没有不必要的内存分配。

你所要做的就是删除WWW API并使用UnityWebRequest。也删除RendererTexture2D,并使用RawImage来显示您的地图。下面是我用来测试这一点的一个简单的测试脚本。它可以在Editor, iOS和可能的所有其他平台上运行。

public class Gpsconnect : MonoBehaviour
{
    public RawImage imageDisp;
    public float fixLat = 42.3627f;
    public float fixLon = -71.05686f;
    public int zoom = 4;
    public string key = "";
    public Vector3 iniRef;
    public Transform cam;
    private Camera mycam;
    private string url = "";
    //Update Map with the corresponding map images for the current location ============================================
    IEnumerator load()
    {
        yield return null;
        mycam = Camera.main;
        fixLat = ((360 / Mathf.PI) * Mathf.Atan(Mathf.Exp(0.00001567855943f * (cam.position.z - 3 * mycam.orthographicSize / 2 + iniRef.z)))) - 90;
        fixLon = (18000 * (cam.position.x + iniRef.x)) / 20037508.34f;
        //MAP ================================================================================
        //Build a valid Google Maps tile request for the current location 
        url = "https://maps.google.com/maps/api/staticmap?center=" + fixLat + "," + fixLon + "&zoom=" + zoom + "&scale=2&size=640x640&style=feature:all|element:geometry|hue:0x00fff0|lightness:0|gamma:0.21|visibility:on&style=feature:all|element:labels|visibility:off&style=feature:landscape.man_made|element:geometry|color:0x133f42|visibility:on&style=feature:landscape.natural|element:geometry.fill|visibility:on|hue:0x00ffd2|saturation:35|lightness:0|gamma:0.5&style=feature:poi|element:geometry.fill|lightness:0|gamma:0.6|visibility:on&style=feature:poi.park|element:geometry|visibility:on|saturation:0|color:0x2e9470&style=feature:road|element:geometry.fill|visibility:on|color:0x05111a&style=feature:road|element:geometry.stroke|visibility:off&style=feature:transit|element:geometry|visibility:off" + "&sensor=false&key=" + key;
        UnityWebRequest www = UnityWebRequest.GetTexture(url);
        yield return www.Send();
        Debug.Log("Done: ");
        if (www.isError)
        {
            Debug.Log("Error while downloading image: " + www.error);
        }
        else
        {
            imageDisp.texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
        }
    }
    void Start()
    {
        StartCoroutine(load());
    }
}