You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin.Forms C#中通过经纬度获取区域名称?无法实现getlocality函数

How to Get Locality/Region Name from Latitude & Longitude in Xamarin.Forms C#

Hey there! I get it—trying to pull a city or region name from coordinates in Xamarin.Forms can feel tricky when you can't find a built-in getlocality function. The thing is, Xamarin.Forms doesn't have a native geocoding API out of the box, so we need to use dependency services to tap into each platform's native geocoding tools (Android and iOS each have their own way to handle reverse geocoding). Let's break this down step by step.

Step 1: Create a Shared Geocoding Interface

First, we'll define an interface in your shared Xamarin.Forms project so we can call platform-specific code from the shared layer.

public interface IGeocodingService
{
    // Returns locality (city/region) from lat/long
    Task<string> GetLocalityAsync(double latitude, double longitude);
}

Step 2: Implement the Service for Android

On Android, we'll use the Android.Locations.Geocoder class. First, make sure you have the right permissions set up:

  1. Add these permissions to your AndroidManifest.xml:
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    
  2. For Android 6.0+, you'll need to request location permissions at runtime (don't skip this—your app will crash otherwise!).

Now implement the interface in your Android project:

[assembly: Dependency(typeof(AndroidGeocodingService))]
namespace YourAppName.Droid
{
    public class AndroidGeocodingService : IGeocodingService
    {
        public async Task<string> GetLocalityAsync(double latitude, double longitude)
        {
            try
            {
                var geocoder = new Geocoder(Android.App.Application.Context);
                var addressList = await geocoder.GetFromLocationAsync(latitude, longitude, 1); // Get top 1 result

                if (addressList != null && addressList.Count > 0)
                {
                    var address = addressList[0];
                    // Locality corresponds to city/region name
                    return address.Locality;
                }
                return null;
            }
            catch (Exception ex)
            {
                // Handle exceptions (e.g., no network, permission denied)
                Console.WriteLine($"Geocoding error: {ex.Message}");
                return null;
            }
        }
    }
}

Step 3: Implement the Service for iOS

On iOS, we'll use CoreLocation.CLGeocoder. Again, permissions are key:

  1. Add this to your Info.plist to request location access:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>We need your location to get your city/region name</string>
    

Now implement the interface in your iOS project:

[assembly: Dependency(typeof(IosGeocodingService))]
namespace YourAppName.iOS
{
    public class IosGeocodingService : IGeocodingService
    {
        public async Task<string> GetLocalityAsync(double latitude, double longitude)
        {
            try
            {
                var geocoder = new CLGeocoder();
                var location = new CLLocation(latitude, longitude);
                var placemarks = await geocoder.ReverseGeocodeLocationAsync(location);

                if (placemarks != null && placemarks.Length > 0)
                {
                    var placemark = placemarks[0];
                    // Locality is the city/region name here too
                    return placemark.Locality;
                }
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Geocoding error: {ex.Message}");
                return null;
            }
        }
    }
}

Step 4: Use the Service in Your Xamarin.Forms App

Now you can call this service from your shared code (like a ViewModel or code-behind):

var geocodingService = DependencyService.Get<IGeocodingService>();
if (geocodingService != null)
{
    double lat = 40.7128; // Example: New York
    double lng = -74.0060;
    var locality = await geocodingService.GetLocalityAsync(lat, lng);
    
    if (!string.IsNullOrEmpty(locality))
    {
        // Do something with the city/region name, e.g., display it
        Console.WriteLine($"Locality: {locality}"); // Outputs "New York"
    }
    else
    {
        Console.WriteLine("Could not retrieve locality");
    }
}

Key Notes to Avoid Issues

  • Permissions: Always make sure you've set up runtime permissions for Android and added the plist entries for iOS. Without these, the geocoder will fail silently.
  • Network: Reverse geocoding requires an internet connection—handle cases where the user is offline.
  • Async/Await: All geocoding operations are asynchronous, so never call them without await (you'll get null results or freeze your UI).
  • Fallback: If Locality is null, you can try other properties like AdminArea (state/province) or SubLocality for more granular regions.

内容的提问来源于stack exchange,提问作者MrAshleyt28

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:10:54