Erste Schritte
-
Paket installieren
Terminal-Fenster npm i @capgo/nativegeocoderTerminal-Fenster pnpm add @capgo/nativegeocoderTerminal-Fenster yarn add @capgo/nativegeocoderTerminal-Fenster bun add @capgo/nativegeocoder -
Mit nativen Projekten synchronisieren
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync -
Berechtigungen konfigurieren
Fügen Sie die Standortnutzungsbeschreibung zu Ihrer
Info.plisthinzu:<key>NSLocationWhenInUseUsageDescription</key><string>Um Adressen in Koordinaten umzuwandeln</string>Android
Section titled “Android”Fügen Sie Berechtigungen zu Ihrer
AndroidManifest.xmlhinzu:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Verwendung
Section titled “Verwendung”Importieren Sie das Plugin und verwenden Sie seine Geocoding-Methoden:
import { NativeGeocoder } from '@capgo/nativegeocoder';
// Forward Geocoding: Adresse zu Koordinatenconst 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('Breitengrad:', location.latitude); console.log('Längengrad:', location.longitude);};
// Reverse Geocoding: Koordinaten zu Adresseconst reverseGeocode = async () => { const results = await NativeGeocoder.reverseGeocode({ latitude: 37.4220656, longitude: -122.0840897, useLocale: true, maxResults: 1 });
const address = results.addresses[0]; console.log('Straße:', address.thoroughfare); console.log('Stadt:', address.locality); console.log('Land:', address.countryName);};API-Referenz
Section titled “API-Referenz”forwardGeocode(options)
Section titled “forwardGeocode(options)”Wandelt einen Adressstring in geografische Koordinaten um.
interface ForwardGeocodeOptions { addressString: string; useLocale?: boolean; maxResults?: number; apiKey?: string; // Nur Android}
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;}reverseGeocode(options)
Section titled “reverseGeocode(options)”Wandelt geografische Koordinaten in Adressinformationen um.
interface ReverseGeocodeOptions { latitude: number; longitude: number; useLocale?: boolean; maxResults?: number; apiKey?: string; // Nur Android}Vollständige Beispiele
Section titled “Vollständige Beispiele”Adresssuche mit Fehlerbehandlung
Section titled “Adresssuche mit Fehlerbehandlung”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 fehlgeschlagen:', 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 fehlgeschlagen:', 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(', '); }}Standortauswahl-Komponente
Section titled “Standortauswahl-Komponente”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 { // Aktuelle Koordinaten abrufen const position = await Geolocation.getCurrentPosition(); this.currentLocation = { lat: position.coords.latitude, lng: position.coords.longitude };
// Adresse für Koordinaten abrufen 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('Standort konnte nicht abgerufen werden:', 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('Suche fehlgeschlagen:', 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})` : ''); }}Best Practices
Section titled “Best Practices”-
Zuerst Berechtigungen anfordern
import { Geolocation } from '@capacitor/geolocation';const requestPermissions = async () => {const permissions = await Geolocation.requestPermissions();if (permissions.location !== 'granted') {throw new Error('Standortberechtigung erforderlich');}}; -
Fehler graceful behandeln
try {const results = await NativeGeocoder.forwardGeocode({addressString: address});} catch (error) {// Spezifische Fehlerfälle behandelnif (error.message.includes('network')) {console.error('Netzwerkfehler');} else if (error.message.includes('permission')) {console.error('Berechtigung verweigert');}} -
maxResults weise verwenden
- Für Benutzersuche: Verwenden Sie 5-10 Ergebnisse
- Für automatische Konvertierung: Verwenden Sie 1 Ergebnis
- Mehr Ergebnisse = langsamere Antwort
-
Ergebnisse wenn möglich cachen
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;}
Plattformunterschiede
Section titled “Plattformunterschiede”- Verwendet
CLGeocoderaus CoreLocation - Kein API-Schlüssel erforderlich
- Respektiert automatisch das Gebietsschema des Benutzers
Android
Section titled “Android”- Verwendet Android Geocoder API
- Optionaler Google API-Schlüssel für bessere Ergebnisse
- Kann auf den Webservice von Google zurückgreifen
API-Schlüssel-Konfiguration (Android)
Section titled “API-Schlüssel-Konfiguration (Android)”Für bessere Ergebnisse auf Android können Sie einen Google API-Schlüssel bereitstellen:
await NativeGeocoder.forwardGeocode({ addressString: address, apiKey: 'IHR_GOOGLE_API_SCHLÜSSEL' // Nur Android});Häufige Probleme
Section titled “Häufige Probleme”-
Keine Ergebnisse zurückgegeben
- Internetverbindung prüfen
- Adressformat überprüfen
- Mit allgemeinerer Adresse versuchen
-
Berechtigungsfehler
- Sicherstellen, dass Standortberechtigungen gewährt wurden
- Info.plist/AndroidManifest.xml prüfen
-
Ungenaue Ergebnisse
- Spezifischere Adressen verwenden
- Postleitzahlen einbeziehen, wenn verfügbar
- Koordinaten für präzise Standorte in Betracht ziehen