LoginSignup
3
0

More than 3 years have passed since last update.

[Unity] Google Maps Static APIで得た画像をTexture2Dに変換する

Posted at

Google Maps Static API を使うと、

https://maps.googleapis.com/maps/api/staticmap?center=新宿&zoom=14&size=400x400&key=YOUR_API_KEY

のようにURLを指定するだけで、下のようなpng画像がかえってきます。
image.png

つまり、これをUnityの UnityWebRequest に渡せばテクスチャを得ることができます。

・・・と思ったのですが、公式サンプル通り

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class MyBehaviour : MonoBehaviour {
    void Start() {
        StartCoroutine(GetTexture());
    }

    IEnumerator GetTexture() {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture("https://maps.googleapis.com/maps/api/staticmap?center=新宿&zoom=14&size=400x400&key=YOUR_API_KEY");
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success) {
            Debug.Log(www.error);
        }
        else {
            Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
        }
    }
}

とすると

InvalidCastException: Specified cast is not valid.

というエラーが出てTextureに変換してくれません・・・。
(Unity2020.3,7f1)

www.downloadHandler.data にはちゃんとデータが入っているようなのですが、何のデータかわからずキャストできないようです。もしかしてURLの最後が.pngじゃないからとか?
自前でデータコンバーター書かなきゃダメなのか・・・と一瞬半泣きになったのですが、そういえばpngファイルからTexture2Dにする方法があったような、と調べたところ、

Texture2D texture = new Texture2D(400,400);
texture.LoadImage(webRequest.downloadHandler.data);

という方法が見つかりました。
400,400のところはgoogleMapsに渡したsize=400x400の値ですが、2,2など適当な値でもLoadImageが調整してくれるようです。
ということで、

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class MyBehaviour : MonoBehaviour {
    void Start() {
        StartCoroutine(GetTexture());
    }

    IEnumerator GetTexture() {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture("https://maps.googleapis.com/maps/api/staticmap?center=新宿&zoom=14&size=400x400&key=YOUR_API_KEY");
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success) {
            Debug.Log(www.error);
        }
        else {
            Texture2D texture = new Texture2D(2,2);
            texture.LoadImage(webRequest.downloadHandler.data);
        }
    }
}

で、無事テクスチャを取得することができました!

image.png

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0