Comparing 2 Locations in Windows Phone 7

If you are using Microsoft.Phone.Controls.Maps.Platform.Location in your WP7 application and you want to see if 2 Locations refer to the same place (i.e. the same altitude, latitude and longitude are all equal) then using Location.Equals or == will not work.

This is because Location inherits from Object and doesn't override Equals method, which results in a simple reference equality check.

The extension method below can be used instead:

using Microsoft.Phone.Controls.Maps.Platform;
namespace DontCodeTired
{
    public static class LocationExtensionMethods
    {
        public static bool IsSamePlaceAs(this Location me, Location them)
        {
            return me.Latitude == them.Latitude &&
                   me.Longitude == them.Longitude &&
                   me.Altitude == them.Altitude;
        }
    }
}

 

Example usage:

    [TestFixture]
    public class LocationExtensionMethodsTest
    {
        [Test]
        public void ShouldRecogniseWhenTwoLocationsReferToTheSamePlace()
        {
            var l1 = new Location {Latitude = double.MinValue, Longitude = double.MaxValue};
            var l2 = new Location { Latitude = double.MinValue, Longitude = double.MaxValue };
            Assert.IsTrue(l1.IsSamePlaceAs(l2));
        }
        [Test]
        public void ShouldRecogniseWhenTwoLocationsReferToDifferentPlacess()
        {
            var l1 = new Location { Latitude = double.MinValue - double.MinValue, Longitude = double.MaxValue };
            var l2 = new Location { Latitude = double.MinValue, Longitude = double.MaxValue };
            Assert.IsFalse(l1.IsSamePlaceAs(l2));
        }
    }

 

 

SHARE:

Add comment

Loading