Zum Inhalt springen

Erste Schritte

  1. Paket installieren

    Terminal-Fenster
    npm i @capgo/nativegeocoder
  2. Mit nativen Projekten synchronisieren

    Terminal-Fenster
    npx cap sync
  3. Berechtigungen konfigurieren

    Fügen Sie die Standortnutzungsbeschreibung zu Ihrer Info.plist hinzu:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Um Adressen in Koordinaten umzuwandeln</string>

    Fügen Sie Berechtigungen zu Ihrer AndroidManifest.xml hinzu:

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

Importieren Sie das Plugin und verwenden Sie seine Geocoding-Methoden:

import { NativeGeocoder } from '@capgo/nativegeocoder';
// Forward Geocoding: Adresse zu Koordinaten
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('Breitengrad:', location.latitude);
console.log('Längengrad:', location.longitude);
};
// Reverse Geocoding: Koordinaten zu Adresse
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('Straße:', address.thoroughfare);
console.log('Stadt:', address.locality);
console.log('Land:', address.countryName);
};

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;
}

Wandelt geografische Koordinaten in Adressinformationen um.

interface ReverseGeocodeOptions {
latitude: number;
longitude: number;
useLocale?: boolean;
maxResults?: number;
apiKey?: string; // Nur Android
}
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(', ');
}
}
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})` : '');
}
}
  1. 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');
    }
    };
  2. Fehler graceful behandeln

    try {
    const results = await NativeGeocoder.forwardGeocode({
    addressString: address
    });
    } catch (error) {
    // Spezifische Fehlerfälle behandeln
    if (error.message.includes('network')) {
    console.error('Netzwerkfehler');
    } else if (error.message.includes('permission')) {
    console.error('Berechtigung verweigert');
    }
    }
  3. maxResults weise verwenden

    • Für Benutzersuche: Verwenden Sie 5-10 Ergebnisse
    • Für automatische Konvertierung: Verwenden Sie 1 Ergebnis
    • Mehr Ergebnisse = langsamere Antwort
  4. 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;
    }
  • Verwendet CLGeocoder aus CoreLocation
  • Kein API-Schlüssel erforderlich
  • Respektiert automatisch das Gebietsschema des Benutzers
  • Verwendet Android Geocoder API
  • Optionaler Google API-Schlüssel für bessere Ergebnisse
  • Kann auf den Webservice von Google zurückgreifen

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
});
  1. Keine Ergebnisse zurückgegeben

    • Internetverbindung prüfen
    • Adressformat überprüfen
    • Mit allgemeinerer Adresse versuchen
  2. Berechtigungsfehler

    • Sicherstellen, dass Standortberechtigungen gewährt wurden
    • Info.plist/AndroidManifest.xml prüfen
  3. Ungenaue Ergebnisse

    • Spezifischere Adressen verwenden
    • Postleitzahlen einbeziehen, wenn verfügbar
    • Koordinaten für präzise Standorte in Betracht ziehen