//This is the main coroutine where we ask for the data and retrive it
    private IEnumerator APICallRoutine()
    {
        // A block that will request the data and wait for its return
        using (UnityWebRequest request = UnityWebRequest.Get(URL))
        {
            // wait until you get a response
            yield return(request.SendWebRequest());

            // if there is an error, log it to the console
            if (request.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.LogError(request.error);
            }

            // otherwise
            else
            {
                //encode the data to UTF8 just in case it is not properly formated. This is needed to Json
                string result = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);

                //convert the Json object to a c# object
                Earthquakes data = JsonUtility.FromJson <Earthquakes>(result);

                //publish the event and the data to whoever is listening
                EarthquakeUpdated?.Invoke(data);
            }
        }
    }
    // The SetPoints method will be called every time the DataStreamer updates the data and publishes the event
    private void SetPoints(Earthquakes data)
    {
        //loop through all the features of the received earthquake data
        for (int i = 0; i < data.features.Length; i++)
        {
            // get the latitude and longitude
            float lon = data.features[i].geometry.coordinates[0];
            float lat = data.features[i].geometry.coordinates[1];

            //set the range for elevation to [0, PI]
            float theta = (Mathf.Deg2Rad * lat) + (Mathf.PI * 0.5f);

            //set tje range for azimuth to [0, 2PI]
            float phi = (Mathf.Deg2Rad * lon) + Mathf.PI;

            //Cartesian coordinates
            float x = VisualisationRadius * Mathf.Sin(theta) * Mathf.Cos(phi);
            float y = VisualisationRadius * Mathf.Sin(theta) * Mathf.Sin(phi);
            float z = VisualisationRadius * Mathf.Cos(theta);

            //resulting position as a vector
            Vector3 pos = new Vector3(x, y, z);

            //Emitting a single particle at each position
            Ps.Emit(new ParticleSystem.EmitParams {
                position = pos
            }, 1);
        }
    }
        private void UpdateEarthquakes()
        {
            List <EarthQuakeData> newQuakes = _allEarthquakes.
                                              Where(IsFilterMatch).ToList();

            if (Earthquakes == null || !Earthquakes.SequenceEqual(newQuakes))
            {
                Earthquakes = newQuakes;
            }
        }
 void Start()
 {
     lookAtTextall = GetComponent<LoadJSON>();
     lookAtText = GetComponent<Earthquakes>();
 }
        private async Task ProcessFeed(bool useLongFeed, bool disableNotice)
        {
            using var request = new HttpRequestMessage(HttpMethod.Get,
                                                       useLongFeed
                                ? "http://www.data.jma.go.jp/developer/xml/feed/eqvol_l.xml"
                                : "http://www.data.jma.go.jp/developer/xml/feed/eqvol.xml");

            DateTimeOffset?lastModified;

            if (useLongFeed)
            {
                lastModified = LongFeedLastModified;
            }
            else
            {
                lastModified = ShortFeedLastModified;
            }

            // 初回取得じゃない場合チェックしてもらう
            if (lastModified != null)
            {
                request.Headers.IfModifiedSince = lastModified;
            }
            using var response = await Client.SendAsync(request);

            if (response.StatusCode == HttpStatusCode.NotModified)
            {
                Logger.Debug("JMAXMLフィード - NotModified");
                return;
            }
            Logger.Debug($"JMAXMLフィード更新処理開始 Last:{lastModified:yyyy/MM/dd HH:mm:ss} Current:{response.Content.Headers.LastModified:yyyy/MM/dd HH:mm:ss}");

            using var reader = XmlReader.Create(await response.Content.ReadAsStreamAsync());
            var feed = SyndicationFeed.Load(reader);

            // 求めているものを新しい順で舐める
            var matchItems = feed.Items.Where(i => ParseTitles.Any(t => t == i.Title.Text));

            if (useLongFeed)
            {
                matchItems = matchItems.OrderByDescending(i => i.LastUpdatedTime);
            }
            else
            {
                matchItems = matchItems.OrderBy(i => i.LastUpdatedTime);
            }

            // URLにないものを抽出
            foreach (var item in matchItems)
            {
                if (ParsedMessages.Contains(item.Id))
                {
                    continue;
                }

                Logger.Trace($"処理 {item.LastUpdatedTime:yyyy/MM/dd HH:mm:ss} {item.Title.Text}");

                if (!Directory.Exists(CacheFolderName))
                {
                    Directory.CreateDirectory(CacheFolderName);
                }

                int retry = 0;
                // リトライループ
                while (true)
                {
                    var cresponse = await Client.SendAsync(new HttpRequestMessage(HttpMethod.Get, item.Links[0].Uri));

                    if (cresponse.StatusCode != HttpStatusCode.OK)
                    {
                        retry++;
                        if (retry >= 10)
                        {
                            Logger.Warning($"XMLの取得に失敗しました! Status: {cresponse.StatusCode} Url: {item.Links[0].Uri}");
                            break;
                        }
                        continue;
                    }
                    // TODO: もう少し綺麗にしたい
                    try
                    {
                        var cacheFilePath = Path.Join(CacheFolderName, Path.GetFileName(item.Links[0].Uri.ToString()));
                        if (!File.Exists(cacheFilePath))
                        {
                            using var wstr = File.OpenWrite(cacheFilePath);
                            await(await cresponse.Content.ReadAsStreamAsync()).CopyToAsync(wstr);
                        }
                        using var rstr = File.OpenRead(cacheFilePath);
                        var report = (Report)ReportSerializer.Deserialize(rstr);

                        // TODO: EventIdの異なる電文に対応する
                        var eq = Earthquakes.FirstOrDefault(e => e.Id == report.Head.EventID);
                        if (!useLongFeed || eq == null)
                        {
                            if (eq == null)
                            {
                                eq = new Earthquake
                                {
                                    Id        = report.Head.EventID,
                                    IsSokuhou = true,
                                    Intensity = JmaIntensity.Unknown
                                };
                                if (useLongFeed)
                                {
                                    Earthquakes.Add(eq);
                                }
                                else
                                {
                                    Earthquakes.Insert(0, eq);
                                }
                            }

                            switch (report.Control.Title)
                            {
                            case "震度速報":
                            {
                                if (!eq.IsSokuhou)
                                {
                                    break;
                                }
                                eq.IsSokuhou      = true;
                                eq.OccurrenceTime = report.Head.TargetDateTime;
                                eq.IsReportTime   = true;

                                var infoItem = report.Head.Headline.Informations.First().Items.First();
                                eq.Intensity = infoItem.Kind.Name.Replace("震度", "").ToJmaIntensity();
                                eq.Place     = infoItem.Areas.Area.First().Name;
                                break;
                            }

                            case "震源に関する情報":
                            {
                                eq.IsSokuhou      = false;
                                eq.OccurrenceTime = report.Body.Earthquake.OriginTime;
                                eq.IsReportTime   = false;

                                eq.Place     = report.Body.Earthquake.Hypocenter.Area.Name;
                                eq.Magnitude = report.Body.Earthquake.Magnitude.Value;
                                eq.Depth     = report.Body.Earthquake.Hypocenter.Area.Coordinate.GetDepth() ?? -1;
                                break;
                            }

                            case "震源・震度に関する情報":
                            {
                                eq.IsSokuhou      = false;
                                eq.OccurrenceTime = report.Body.Earthquake.OriginTime;
                                eq.IsReportTime   = false;

                                eq.Intensity = report.Body.Intensity?.Observation?.MaxInt?.ToJmaIntensity() ?? JmaIntensity.Unknown;
                                eq.Place     = report.Body.Earthquake.Hypocenter.Area.Name;
                                eq.Magnitude = report.Body.Earthquake.Magnitude.Value;
                                eq.Depth     = report.Body.Earthquake.Hypocenter.Area.Coordinate.GetDepth() ?? -1;
                                break;
                            }

                            default:
                                Logger.Error("不明なTitleをパースしました。: " + report.Control.Title);
                                break;
                            }
                            if (!disableNotice)
                            {
                                EarthquakeUpdatedEvent.Publish(eq);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("デシリアライズ時に例外が発生しました。 " + ex);
                    }
                    ParsedMessages.Add(item.Id);
                    break;
                }

                if (useLongFeed && Earthquakes.Count > 10)
                {
                    break;
                }
            }
            if (!useLongFeed && Earthquakes.Count > 20)
            {
                Earthquakes.RemoveRange(20, Earthquakes.Count - 20);
            }
            if (ParsedMessages.Count > 100)
            {
                ParsedMessages.RemoveRange(100, ParsedMessages.Count - 100);
            }

            if (useLongFeed)
            {
                LongFeedLastModified = response.Content.Headers?.LastModified?.UtcDateTime;
            }
            else
            {
                ShortFeedLastModified = response.Content.Headers?.LastModified?.UtcDateTime;
            }

            // キャッシュフォルダのクリーンアップ
            var cachedFiles = Directory.GetFiles(CacheFolderName, "*.xml");

            if (cachedFiles.Length < 20)             // 20件以内なら削除しない
            {
                return;
            }
            foreach (var file in cachedFiles)
            {
                if (DateTime.Now - File.GetCreationTime(file) > TimeSpan.FromDays(10))
                {
                    File.Delete(file);
                }
            }
        }