C# 如何修复.Exception:';未找到特定pin的自定义pin

C# 如何修复.Exception:';未找到特定pin的自定义pin,c#,android,xamarin,xamarin.forms,C#,Android,Xamarin,Xamarin.forms,请帮我解决这个问题。 我使用本文在xamarin中制作了一个自定义渲染器: 在我将pin信息转换成JSON文件之前,一切都很顺利 因此,现在基本上LAT、LNG、label、名称和URL存储在JSON文件中,而不是存储在C#文件中。 为了测试,我做了3个临时引脚。但其中只有1个显示自定义渲染窗口。当我单击其他2个管脚时,会出现异常,因为未找到自定义管脚。但是最后一个pin找到了自定义pin,但第一个和第二个pin没有找到,这让我很困惑 我的代码: JSON文件: [ {"Label

请帮我解决这个问题。 我使用本文在xamarin中制作了一个自定义渲染器:

在我将pin信息转换成JSON文件之前,一切都很顺利

因此,现在基本上LAT、LNG、label、名称和URL存储在JSON文件中,而不是存储在C#文件中。 为了测试,我做了3个临时引脚。但其中只有1个显示自定义渲染窗口。当我单击其他2个管脚时,会出现异常,因为未找到自定义管脚。但是最后一个pin找到了自定义pin,但第一个和第二个pin没有找到,这让我很困惑

我的代码:

JSON文件:

[

{"Label"   :"Country1",
        "Address":"A multine paragraph",
        "Lat":"-12",
        "Lng":"14",
        "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
},


{ "Label"  :"Country2",
         "Address":"Multiline paragraph",
         "Lat":"-25", 
         "Lng":"45",
         "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
},

{ "Label"  :"Country3",
         "Address":"Multiline paragraph",
         "Lat":"-5", 
         "Lng":"45",
         "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
}

]
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using ----;
using ----.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace ----.Droid
{
    public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
    {
        List<CustomPin> customPins;

        public CustomMapRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                NativeMap.InfoWindowClick -= OnInfoWindowClick;
            }

            if (e.NewElement != null)
            {
                var formsMap = (CustomMap)e.NewElement;
                customPins = formsMap.CustomPins;
            }
        }

        protected override void OnMapReady(GoogleMap map)
        {
            base.OnMapReady(map);

            NativeMap.InfoWindowClick += OnInfoWindowClick;
            NativeMap.SetInfoWindowAdapter(this);
        }

        protected override MarkerOptions CreateMarker(Pin pin)
        {
            var marker = new MarkerOptions();
            marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
            marker.SetTitle(pin.Label);
            marker.SetSnippet(pin.Address);
            marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
            return marker;
        }

        void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
        {
            var customPin = GetCustomPin(e.Marker);
            if (customPin == null)
            {
                throw new Exception("Custom pin not found");
            }

            if (!string.IsNullOrWhiteSpace(customPin.Url))
            {
                var url = Android.Net.Uri.Parse(customPin.Url);
                var intent = new Intent(Intent.ActionView, url);
                intent.AddFlags(ActivityFlags.NewTask);
                Android.App.Application.Context.StartActivity(intent);
            }
        }

        public Android.Views.View GetInfoContents(Marker marker)
        {
            var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
            if (inflater != null)
            {
                Android.Views.View view;

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

                if (customPin.Name.Equals("Xamarin"))
                {
                    view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
                }
                else
                {
                    view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
                }

                var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
                var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);

                if (infoTitle != null)
                {
                    infoTitle.Text = marker.Title;
                }
                if (infoSubtitle != null)
                {
                    infoSubtitle.Text = marker.Snippet;
                }

                return view;
            }
            return null;
        }

        public Android.Views.View GetInfoWindow(Marker marker)
        {
            return null;
        }

        CustomPin GetCustomPin(Marker annotation)
        {
            var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
            foreach (var pin in customPins)
            {
                if (pin.Position == position)
                {
                    return pin;
                }
            }
            return null;
        }
    }
}
MapPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Newtonsoft.Json;
using System.IO;
using Xamarin.Forms.Xaml;
using System.Reflection;    

namespace Orbage
{
    public partial class MapPage : ContentPage
    {
        public MapPage()
        {
            CustomMap customMap = new CustomMap
            {
                MapType = MapType.Hybrid


            };

            Content = customMap;

            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
            Stream stream = assembly.GetManifestResourceStream("Orbage.Mydata.json");
            string json = "";
            using (var reader = new System.IO.StreamReader(stream))
            {
                json = reader.ReadToEnd();
            }
            var places = JsonConvert.DeserializeObject<List<Mydata>>(json);



            List<CustomPin> custompinList = new List<CustomPin>();
            foreach (var place in places)
            {
                CustomPin pin = new CustomPin
                {
                    Type = PinType.Place,
                    Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
                    Label = place.Label,
                    Address = place.Address,
                    Name = place.Name,
                    Url = place.Url
                };
                
                
                customMap.Pins.Add(pin);
                customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
                customMap.CustomPins = custompinList; 
            }
            

        }
    }
    public class Mydata
    {
        public string Label { get; set; }
        public string Address { get; set; }
        public string Lat { get; set; }
        public string Lng { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }


    }
}
自定义地图:

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms.Maps;

namespace Orbage
{
    public class CustomMap : Map
    {
        public List<CustomPin> CustomPins { get; set; }
    }
}

使用系统;
使用System.Collections.Generic;
使用系统文本;
使用Xamarin.Forms.Maps;
名称空间Orbage
{
公共类CustomMap:Map
{
公共列表CustomPins{get;set;}
}
}
CustomMapRenderer.cs:

[

{"Label"   :"Country1",
        "Address":"A multine paragraph",
        "Lat":"-12",
        "Lng":"14",
        "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
},


{ "Label"  :"Country2",
         "Address":"Multiline paragraph",
         "Lat":"-25", 
         "Lng":"45",
         "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
},

{ "Label"  :"Country3",
         "Address":"Multiline paragraph",
         "Lat":"-5", 
         "Lng":"45",
         "Name":"Xamarin",
         "Url": "http://xamarin.com/about/"
}

]
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using ----;
using ----.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace ----.Droid
{
    public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
    {
        List<CustomPin> customPins;

        public CustomMapRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                NativeMap.InfoWindowClick -= OnInfoWindowClick;
            }

            if (e.NewElement != null)
            {
                var formsMap = (CustomMap)e.NewElement;
                customPins = formsMap.CustomPins;
            }
        }

        protected override void OnMapReady(GoogleMap map)
        {
            base.OnMapReady(map);

            NativeMap.InfoWindowClick += OnInfoWindowClick;
            NativeMap.SetInfoWindowAdapter(this);
        }

        protected override MarkerOptions CreateMarker(Pin pin)
        {
            var marker = new MarkerOptions();
            marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
            marker.SetTitle(pin.Label);
            marker.SetSnippet(pin.Address);
            marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
            return marker;
        }

        void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
        {
            var customPin = GetCustomPin(e.Marker);
            if (customPin == null)
            {
                throw new Exception("Custom pin not found");
            }

            if (!string.IsNullOrWhiteSpace(customPin.Url))
            {
                var url = Android.Net.Uri.Parse(customPin.Url);
                var intent = new Intent(Intent.ActionView, url);
                intent.AddFlags(ActivityFlags.NewTask);
                Android.App.Application.Context.StartActivity(intent);
            }
        }

        public Android.Views.View GetInfoContents(Marker marker)
        {
            var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
            if (inflater != null)
            {
                Android.Views.View view;

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

                if (customPin.Name.Equals("Xamarin"))
                {
                    view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
                }
                else
                {
                    view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
                }

                var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
                var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);

                if (infoTitle != null)
                {
                    infoTitle.Text = marker.Title;
                }
                if (infoSubtitle != null)
                {
                    infoSubtitle.Text = marker.Snippet;
                }

                return view;
            }
            return null;
        }

        public Android.Views.View GetInfoWindow(Marker marker)
        {
            return null;
        }

        CustomPin GetCustomPin(Marker annotation)
        {
            var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
            foreach (var pin in customPins)
            {
                if (pin.Position == position)
                {
                    return pin;
                }
            }
            return null;
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用Android.Content;
使用Android.Gms.Maps;
使用Android.Gms.Maps.Model;
使用Android.Widget;
使用--;
使用---.Droid;
使用Xamarin.Forms;
使用Xamarin.Forms.Maps;
使用Xamarin.Forms.Maps.Android;
[程序集:ExportRenderer(typeof(CustomMap)、typeof(CustomMapRenderer))]
名称空间--.Droid
{
公共类CustomMapRenderer:MapRenderer,GoogleMap.IInfoWindowAdapter
{
列出客户PIN码;
公共CustomMapRenderer(上下文):基础(上下文)
{
}
受保护的覆盖无效OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs e)
{
基础。一个要素发生变化(e);
if(e.OldElement!=null)
{
NativeMap.InfoWindowClick-=OnInfoWindowClick;
}
if(例如NewElement!=null)
{
var formsMap=(CustomMap)e.NewElement;
customPins=formsMap.customPins;
}
}
受保护的覆盖无效OnMapReady(谷歌地图)
{
基础。已完成(地图);
NativeMap.InfoWindowClick+=OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(此);
}
受保护的覆盖标记选项CreateMarker(Pin)
{
var marker=新的MarkerOptions();
标记器设置位置(新板条(销位置纬度销位置经度));
标记.设置标题(pin.标签);
标记器固定接头(引脚地址);
SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
返回标记;
}
无效OnInfoWindowClick(对象发送者,GoogleMap.InfoWindowClickEventArgs e)
{
var customPin=GetCustomPin(即标记);
如果(customPin==null)
{
抛出新异常(“未找到自定义pin”);
}
如果(!string.IsNullOrWhiteSpace(customPin.Url))
{
var url=Android.Net.Uri.Parse(customPin.url);
var intent=新的intent(intent.ActionView,url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(标记器)
{
var inflater=Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService)作为Android.Views.LayoutInflater;
如果(充气机!=null)
{
Android.Views.View;
var customPin=GetCustomPin(标记);
如果(customPin==null)
{
抛出新异常(“未找到自定义pin”);
}
if(customPin.Name.Equals(“Xamarin”))
{
视图=充气机.Inflate(Resource.Layout.xamarinMapInfo窗口,null);
}
其他的
{
视图=充气机.Inflate(Resource.Layout.MapInfo窗口,null);
}
var infoTitle=view.findviewbyd(Resource.Id.InfoWindowTitle);
var infoSubtitle=view.findviewbyd(Resource.Id.InfoWindowSubtitle);
if(infoTitle!=null)
{
infoTitle.Text=marker.Title;
}
if(infoSubtitle!=null)
{
infoSubtitle.Text=marker.Snippet;
}
返回视图;
}
返回null;
}
public Android.Views.View GetInfoWindow(标记器)
{
返回null;
}
CustomPin GetCustomPin(标记注释)
{
变量位置=新位置(annotation.position.Latitude,annotation.position.Longitude);
foreach(customPins中的var pin)
{
如果(销位置==位置)
{
回位销;
}
}
返回null;
}
}
}
感谢您看到这一点,我希望这得到了回答,有人与相同的错误得到修复。 :)

我尝试过调试,下面是一幅可能有所帮助的图像:

更新效果如下:


首先,这不是系统异常,而是您在自己的代码中显式抛出的异常。您需要调试
GetCustomPin
,以查看当您单击它时,它为什么找不到pin。对此我深表歉意。我也错误地复制了系统部分。我会编辑它,但是如果它对同一数据列表中的一个管脚有效,但其他管脚不使用调试器,我将如何调试它。查看传入的位置值,并将其与数据中的值进行比较,以了解为什么找不到匹配项好的,我将尝试修复它。我
  List<CustomPin> custompinList = new List<CustomPin>();
  foreach (var place in places)
        {
            CustomPin pin = new CustomPin
            {
                Type = PinType.Place,
                Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
                Label = place.Label,
                Address = place.Address,
                Name = place.Name,
                Url = place.Url
            };
            custompinList.Add(pin);
            customMap.Pins.Add(pin);
            customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
        }
  customMap.CustomPins = custompinList;