简体   繁体   English

单击 Pin 时尝试从 API 加载数据 (CustomMap) 错误:指定的转换无效。 - xamarin.forms.maps

[英]Trying to load data from API when Pin is clicked (CustomMap) error: Specified cast is not valid. - xamarin.forms.maps

I'm trying to load the data from API in custom map (xamarin.forms.maps) when user click on pin to send (index + 1) on the pin like as parameter.当用户单击 pin 以在 pin 上发送(索引 + 1)作为参数时,我正在尝试从 API 加载自定义 map (xamarin.forms.maps) 中的数据。

1. Here I set index + 1 on the Address property on the pin : 1. 在这里,我在引脚的地址属性上设置了索引 + 1

         List<CustomPin> pins = new List<CustomPin>();

            for (int i = 0; i < HardcodedLocations.Positions.Count; i++)
            {
                CustomPin pin = new CustomPin
                {
                    Type = PinType.Place,
                    Position = HardcodedLocations.Positions[i],
                    Label = "Xamarin San Francisco Office",
                    Address = $"{i + 1}",
                    Name = "Xamarin",
                    Url = "http://xamarin.com/about/"
                };

                pins.Add(pin);
                customMap.Pins.Add(pin);
                customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(42.8742, 25.3187), Distance.FromKilometers(250.0)));

            }

            customMap.CustomPins = pins;

2. In CustomMKAnnotationView class I create property Address: 2.在CustomMKAnnotationView class我创建属性地址:

public class CustomMKAnnotationView : MKAnnotationView
{
    public string Name { get; set; }

    public string Url { get; set; }

    public string Address { get; set; }

    public CustomMKAnnotationView(IMKAnnotation annotation, string id)
        : base(annotation, id)
    {
    }

3. In GetViewForAnnotation method in CustomMapRenderer class I appropriate annotationView.Address to be equal on customPin.Address 3. 在 CustomMapRenderer class 的 GetViewForAnnotation 方法中,我将 annotationView.Address 设置为与 customPin.Address 相等

protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
    {
        MKAnnotationView annotationView = null;

        if (annotation is MKUserLocation)
            return null;

        var customPin = GetCustomPin(annotation as MKPointAnnotation);
        if (customPin == null)
        {
            throw new Exception("Custom pin not found");
        }

        annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
        if (annotationView == null)
        {
            annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
            annotationView.Image = UIImage.FromFile("pin.png");
            annotationView.CalloutOffset = new CGPoint(0, 0);
            annotationView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("monkey.png"));
            annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
            ((CustomMKAnnotationView)annotationView).Name = customPin.Name;
            ((CustomMKAnnotationView)annotationView).Url = customPin.Url;
            ((CustomMKAnnotationView)annotationView).Address = customPin.Address;
        }
        annotationView.CanShowCallout = true;

        return annotationView;
    }

4. I create a method to get the data from API in CustomMapRenderer class: 4. 我在 CustomMapRenderer class 中创建了一个从 API 获取数据的方法:

string GenerateRequestUri(string endpoint, string date, string id)
    {
        string requestUri = endpoint;
        requestUri += $"?date={date}";
        requestUri += $"&id={id}";
        requestUri += $"&daysForward=8";

        return requestUri;
    }

    public async Task<IEnumerable<AladinModel>> GetDataFromAPI(string indexOnClick)
    {
        DateTime dtNow = DateTime.Now;
        var dtNowAPI = dtNow.ToString("yyyy-MM-dd");

        var listData = new List<AladinModel>();

        var result = await _restServiceAPI.GetAladinData(GenerateRequestUri(ConstantsAPI.EndPoint, dtNowAPI, indexOnClick));

        foreach (var item in result)
        {
            var currentData = new AladinModel()
            {
                
                Dats = item.Dats,
                Ta = item.Ta,
                Rh = item.Rh,
                Ws = item.Ws,
                Rr = item.Rr,
                Sr = item.Sr,
                Apres = item.Apres

        };
            listData.Add(currentData);
        }

        return listData;
    }

5. In OnDidSelectAnnotationView method I trying to send the data with MessagingCenter: 5. 在 OnDidSelectAnnotationView 方法中,我尝试使用 MessagingCenter 发送数据:

void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
    {
        CustomMKAnnotationView customView = e.View as CustomMKAnnotationView;
        customPinView = new UIView();

        if (customView.Name.Equals("Xamarin"))
        {
            customPinView.Frame = new CGRect(0, 0, 200, 84);
            var image = new UIImageView(new CGRect(0, 0, 200, 84));
            image.Image = UIImage.FromFile("xamarin.png");
            customPinView.AddSubview(image);
            customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
            e.View.AddSubview(customPinView);
        }

        string addressIndex = customView.Address;

        var result = GetDataFromAPI(addressIndex);

        MessagingCenter.Send<object, IEnumerable<AladinModel>>(this, "PinSelected", (IEnumerable<AladinModel>)result);
    }

6. In MainPage I trying to receive the data like that: 6. 在 MainPage 中,我尝试接收这样的数据:

        protected override void OnAppearing()
        {
            base.OnAppearing();

            MarkerPressed();

        }

        public void MarkerPressed()
        {
            MessagingCenter.Subscribe<object, IEnumerable<AladinModel>>(this, "PinSelected", (sender, arg) =>
            {
                var test = arg;
            });
        }

When I click on the marker I receive error: Specified cast is not valid on this line:当我单击标记时,我收到错误消息:指定的转换在此行无效:

MessagingCenter.Send<object, IEnumerable<AladinModel>>(this, "PinSelected", (IEnumerable<AladinModel>)result);

Тhis is my object class:这是我的 object class:

    using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace pizhevsoft.Models
{
    public class ItemsAPI
    {
        public partial class RootAladinModel
        {
            [JsonProperty("aladinModel")]
            public AladinModel[] AladinModel { get; set; }
        }

        public partial class AladinModel
        {
            [JsonProperty("DATS")]
            public DateTime Dats { get; set; }

            [JsonProperty("TA")]
            public double Ta { get; set; }

            [JsonProperty("RH")]
            public double Rh { get; set; }

            [JsonProperty("WS")]
            public double Ws { get; set; }

            [JsonProperty("RR")]
            public double Rr { get; set; }

            [JsonProperty("SR")]
            public double Sr { get; set; }

            [JsonProperty("APRES")]
            public double Apres { get; set; }
        }
    }
}

The main goal when clicking on the marker is to take its index + 1, to pass it as a parameter to API to get the data?点击标记时的主要目标是取其索引+1,将其作为参数传递给 API 以获取数据?

If there is an easier option or way to deal with the problem please share how to do it?如果有更简单的选择或方法来处理问题,请分享如何做?

According to my logic, a method GetDataFromAPI must be created in the CustomMapRenderer class, to be called in OnDidSelectAnnotationView, and data to be sending to the Main project with messaging center?根据我的逻辑,必须在 CustomMapRenderer class 中创建一个方法 GetDataFromAPI,以便在 OnDidSelectAnnotationView 中调用,并将数据发送到带有消息中心的主项目?

GetDataFromAPI is an async method and needs to be called using await GetDataFromAPI异步方法,需要使用await调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么从 sqlite db 中选择会显示错误“指定的强制转换无效”。 在 Xamarin 表单中? - Why does select from sqlite db shows error 'Specified cast is not valid.' in Xamarin Forms? 在Xamarin.Forms.Maps上添加图钉 - Add pin on click Xamarin.Forms.Maps Xamarin 形式:System.InvalidCastException:“指定的强制转换无效。” - Xamarin forms: System.InvalidCastException: 'Specified cast is not valid.' Xamarin 表单与 Firebase。 数据检索抛出 System.InvalidCastException: &#39;指定的转换无效。&#39; - Xamarin Forms with Firebase. Data retrival throwing System.InvalidCastException: 'Specified cast is not valid.' 有没有办法为 Xamarin.Forms.Maps 图钉运动设置动画 - Is there a way to animate Xamarin.Forms.Maps pin movement Xamarin.Forms:使用 Picker 时错误指定的强制转换无效 - Xamarin.Forms: Error Specified cast is not valid when using Picker 没有记录时,ExecuteScalar()返回错误“指定的转换无效”。 - ExecuteScalar() return error “Specified cast is not valid.” when there is no record 如何解决“指定的演员表无效”。 错误 - How to resolve the “Specified cast is not valid.” error 自动映射器显示错误“指定的转换无效。” - automapper showing error “Specified cast is not valid.” 指定演员表无效。 在创建图表时 - Specified cast is not valid. when creating chart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM