跳转到内容

入门

  1. 安装软件包

    Terminal window
    npm i @capgo/nativegeocoder
  2. 与原生项目同步

    Terminal window
    npx cap sync
  3. 配置权限

    将位置使用说明添加到您的 Info.plist 中:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>To convert addresses to coordinates</string>

    向您的 AndroidManifest.xml 添加权限:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

导入插件并使用其地理编码方法:

import { NativeGeocoder } from '@capgo/nativegeocoder';
// Forward geocoding: Address to coordinates
const forwardGeocode = async () => {
const results = await NativeGeocoder.forwardGeocode({
addressString: '1600 Amphitheatre Parkway, Mountain View, CA',
useLocale: true,
maxResults: 1
});
const location = results.addresses[0];
console.log('Latitude:', location.latitude);
console.log('Longitude:', location.longitude);
};
// Reverse geocoding: Coordinates to address
const reverseGeocode = async () => {
const results = await NativeGeocoder.reverseGeocode({
latitude: 37.4220656,
longitude: -122.0840897,
useLocale: true,
maxResults: 1
});
const address = results.addresses[0];
console.log('Street:', address.thoroughfare);
console.log('City:', address.locality);
console.log('Country:', address.countryName);
};

将地址字符串转换为地理坐标。

interface ForwardGeocodeOptions {
addressString: string;
useLocale?: boolean;
maxResults?: number;
apiKey?: string; // Android only
}
interface GeocodeResult {
addresses: Address[];
}
interface Address {
latitude: number;
longitude: number;
countryCode?: string;
countryName?: string;
postalCode?: string;
administrativeArea?: string;
subAdministrativeArea?: string;
locality?: string;
subLocality?: string;
thoroughfare?: string;
subThoroughfare?: string;
}

将地理坐标转换为地址信息。

interface ReverseGeocodeOptions {
latitude: number;
longitude: number;
useLocale?: boolean;
maxResults?: number;
apiKey?: string; // Android only
}
import { NativeGeocoder } from '@capgo/nativegeocoder';
export class GeocodingService {
async searchAddress(address: string): Promise<{lat: number, lng: number} | null> {
try {
const results = await NativeGeocoder.forwardGeocode({
addressString: address,
useLocale: true,
maxResults: 5
});
if (results.addresses.length > 0) {
const location = results.addresses[0];
return {
lat: location.latitude,
lng: location.longitude
};
}
return null;
} catch (error) {
console.error('Geocoding failed:', error);
return null;
}
}
async getAddressFromCoordinates(lat: number, lng: number): Promise<string | null> {
try {
const results = await NativeGeocoder.reverseGeocode({
latitude: lat,
longitude: lng,
useLocale: true,
maxResults: 1
});
if (results.addresses.length > 0) {
const address = results.addresses[0];
return this.formatAddress(address);
}
return null;
} catch (error) {
console.error('Reverse geocoding failed:', error);
return null;
}
}
private formatAddress(address: Address): string {
const parts = [
address.subThoroughfare,
address.thoroughfare,
address.locality,
address.administrativeArea,
address.postalCode,
address.countryName
].filter(part => part != null && part !== '');
return parts.join(', ');
}
}
import { NativeGeocoder } from '@capgo/nativegeocoder';
import { Geolocation } from '@capacitor/geolocation';
export class LocationPicker {
currentLocation: { lat: number; lng: number } | null = null;
currentAddress: string = '';
async getCurrentLocation() {
try {
// Get current coordinates
const position = await Geolocation.getCurrentPosition();
this.currentLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// Get address for coordinates
const results = await NativeGeocoder.reverseGeocode({
latitude: this.currentLocation.lat,
longitude: this.currentLocation.lng,
useLocale: true,
maxResults: 1
});
if (results.addresses.length > 0) {
const address = results.addresses[0];
this.currentAddress = [
address.thoroughfare,
address.locality,
address.countryName
].filter(Boolean).join(', ');
}
} catch (error) {
console.error('Failed to get location:', error);
}
}
async searchLocation(query: string) {
try {
const results = await NativeGeocoder.forwardGeocode({
addressString: query,
useLocale: true,
maxResults: 10
});
return results.addresses.map(address => ({
coordinates: {
lat: address.latitude,
lng: address.longitude
},
displayName: this.formatDisplayName(address)
}));
} catch (error) {
console.error('Search failed:', error);
return [];
}
}
private formatDisplayName(address: Address): string {
const mainPart = [
address.thoroughfare,
address.locality
].filter(Boolean).join(', ');
const subPart = [
address.administrativeArea,
address.countryName
].filter(Boolean).join(', ');
return mainPart + (subPart ? ` (${subPart})` : '');
}
}
  1. 先请求权限

    import { Geolocation } from '@capacitor/geolocation';
    const requestPermissions = async () => {
    const permissions = await Geolocation.requestPermissions();
    if (permissions.location !== 'granted') {
    throw new Error('Location permission required');
    }
    };
  2. 优雅地处理错误

    try {
    const results = await NativeGeocoder.forwardGeocode({
    addressString: address
    });
    } catch (error) {
    // Handle specific error cases
    if (error.message.includes('network')) {
    console.error('Network error');
    } else if (error.message.includes('permission')) {
    console.error('Permission denied');
    }
    }
  3. 明智地使用 maxResults

    • 对于用户搜索:使用 5-10 个结果
    • 对于自动转换:使用 1 个结果
    • 结果越多 = 响应速度越慢
  4. 尽可能缓存结果

    const geocodeCache = new Map();
    async function geocodeWithCache(address: string) {
    if (geocodeCache.has(address)) {
    return geocodeCache.get(address);
    }
    const result = await NativeGeocoder.forwardGeocode({
    addressString: address
    });
    geocodeCache.set(address, result);
    return result;
    }
  • 使用 CoreLocation 中的 CLGeocoder
  • 无需 API 密钥
  • 自动尊重用户的区域设置
  • 使用 Android 地理编码器 API
  • 可选 Google API 键以获得更好的结果
  • 可能会退回到 Google 的网络服务

为了在 Android 上获得更好的结果,您可以提供 Google API 密钥:

await NativeGeocoder.forwardGeocode({
addressString: address,
apiKey: 'YOUR_GOOGLE_API_KEY' // Android only
});
  1. 没有返回结果

    • 检查互联网连接
    • 验证地址格式
    • 尝试使用更通用的地址
  2. 权限错误

    • 确保授予位置权限
    • 检查 Info.plist/AndroidManifest.xml
  3. 结果不准确

    • 使用更具体的地址
    • 包括可用的邮政编码
    • 考虑使用坐标来精确定位